diff --git a/.editorconfig b/.editorconfig index 34abdb2eb4..e5dc8c8bdc 100644 --- a/.editorconfig +++ b/.editorconfig @@ -4,7 +4,7 @@ root = true [*] -end_of_line = CRLF +end_of_line = crlf [*.ps1] indent_style = space @@ -13,4 +13,167 @@ indent_size = 4 [*.cs] dotnet_diagnostic.RS0030.severity=error dotnet_diagnostic.RS0031.severity=error -dotnet_diagnostic.RS0035.severity=error \ No newline at end of file +dotnet_diagnostic.RS0035.severity=error +csharp_using_directive_placement = inside_namespace:silent +csharp_prefer_simple_using_statement = true:suggestion +csharp_prefer_braces = true:silent +csharp_style_namespace_declarations = block_scoped:suggestion +csharp_style_prefer_method_group_conversion = true:silent +csharp_style_prefer_top_level_statements = true:silent +csharp_style_expression_bodied_methods = true:silent +csharp_style_expression_bodied_constructors = false:suggestion +csharp_style_expression_bodied_operators = false:silent +csharp_style_expression_bodied_properties = true:silent +csharp_style_expression_bodied_indexers = true:silent +csharp_style_expression_bodied_accessors = true:silent +csharp_style_expression_bodied_lambdas = true:silent +csharp_style_expression_bodied_local_functions = false:silent +csharp_indent_labels = no_change +csharp_space_around_binary_operators = before_and_after +csharp_style_throw_expression = true:suggestion +csharp_style_prefer_null_check_over_type_check = true:suggestion +csharp_prefer_simple_default_expression = true:suggestion +csharp_style_prefer_local_over_anonymous_function = true:suggestion +csharp_style_prefer_index_operator = true:suggestion +csharp_style_implicit_object_creation_when_type_is_apparent = true:suggestion +csharp_style_prefer_range_operator = true:suggestion +csharp_style_prefer_tuple_swap = true:suggestion +csharp_style_prefer_utf8_string_literals = true:suggestion +csharp_style_deconstructed_variable_declaration = true:suggestion +csharp_style_inlined_variable_declaration = true:suggestion +csharp_style_unused_value_expression_statement_preference = discard_variable:silent +csharp_style_unused_value_assignment_preference = discard_variable:suggestion +csharp_prefer_static_local_function = true:suggestion +csharp_style_prefer_readonly_struct = true:suggestion +csharp_style_allow_embedded_statements_on_same_line_experimental = true:silent +csharp_style_allow_blank_lines_between_consecutive_braces_experimental = true:silent +csharp_style_allow_blank_line_after_colon_in_constructor_initializer_experimental = true:silent +csharp_style_conditional_delegate_call = true:suggestion +csharp_style_prefer_switch_expression = true:suggestion +csharp_style_pattern_matching_over_is_with_cast_check = true:suggestion +csharp_style_prefer_pattern_matching = true:suggestion +csharp_style_prefer_not_pattern = true:suggestion +csharp_style_pattern_matching_over_as_with_null_check = true:suggestion +csharp_style_prefer_extended_property_pattern = true:suggestion +csharp_style_var_for_built_in_types = true:suggestion +csharp_style_var_when_type_is_apparent = true:suggestion +csharp_style_var_elsewhere = true:suggestion + +[*.{cs,vb}] +#### Naming styles #### + +# Naming rules + +dotnet_naming_rule.interface_should_be_begins_with_i.severity = error +dotnet_naming_rule.interface_should_be_begins_with_i.symbols = interface +dotnet_naming_rule.interface_should_be_begins_with_i.style = begins_with_i + +dotnet_naming_rule.types_should_be_pascal_case.severity = error +dotnet_naming_rule.types_should_be_pascal_case.symbols = types +dotnet_naming_rule.types_should_be_pascal_case.style = pascal_case + +dotnet_naming_rule.non_field_members_should_be_pascal_case.severity = error +dotnet_naming_rule.non_field_members_should_be_pascal_case.symbols = non_field_members +dotnet_naming_rule.non_field_members_should_be_pascal_case.style = pascal_case + +dotnet_naming_rule.private_fields_should_be_camel_case_underscore_prefix.severity = error +dotnet_naming_rule.private_fields_should_be_camel_case_underscore_prefix.symbols = private_fields +dotnet_naming_rule.private_fields_should_be_camel_case_underscore_prefix.style = camel_case_underscore_prefix + +dotnet_naming_rule.non_private_fields_should_be_pascal_case.severity = error +dotnet_naming_rule.non_private_fields_should_be_pascal_case.symbols = non_private_fields +dotnet_naming_rule.non_private_fields_should_be_pascal_case.style = pascal_case + +dotnet_naming_rule.local_variables_should_be_camel_case.severity = error +dotnet_naming_rule.local_variables_should_be_camel_case.symbols = local_variables +dotnet_naming_rule.local_variables_should_be_camel_case.style = camel_case + +dotnet_naming_rule.constant_fields_should_be_pascal_case.severity = error +dotnet_naming_rule.constant_fields_should_be_pascal_case.symbols = constant_fields +dotnet_naming_rule.constant_fields_should_be_pascal_case.style = pascal_case + +# Symbol specifications + +dotnet_naming_symbols.interface.applicable_kinds = interface +dotnet_naming_symbols.interface.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected +dotnet_naming_symbols.interface.required_modifiers = + +dotnet_naming_symbols.non_private_fields.applicable_kinds = field +dotnet_naming_symbols.non_private_fields.applicable_accessibilities = public, internal, protected, protected_internal +dotnet_naming_symbols.non_private_fields.required_modifiers = + +dotnet_naming_symbols.private_fields.applicable_kinds = field +dotnet_naming_symbols.private_fields.applicable_accessibilities = private, private_protected +dotnet_naming_symbols.private_fields.required_modifiers = + +dotnet_naming_symbols.types.applicable_kinds = class, struct, interface, enum +dotnet_naming_symbols.types.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected +dotnet_naming_symbols.types.required_modifiers = + +dotnet_naming_symbols.non_field_members.applicable_kinds = property, event, method +dotnet_naming_symbols.non_field_members.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected +dotnet_naming_symbols.non_field_members.required_modifiers = + +dotnet_naming_symbols.local_variables.applicable_kinds = parameter, local +dotnet_naming_symbols.local_variables.applicable_accessibilities = local +dotnet_naming_symbols.local_variables.required_modifiers = + +dotnet_naming_symbols.constant_fields.applicable_kinds = field +dotnet_naming_symbols.constant_fields.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected +dotnet_naming_symbols.constant_fields.required_modifiers = const + +# Naming styles + +dotnet_naming_style.pascal_case.required_prefix = +dotnet_naming_style.pascal_case.required_suffix = +dotnet_naming_style.pascal_case.word_separator = +dotnet_naming_style.pascal_case.capitalization = pascal_case + +dotnet_naming_style.camel_case.required_prefix = +dotnet_naming_style.camel_case.required_suffix = +dotnet_naming_style.camel_case.word_separator = +dotnet_naming_style.camel_case.capitalization = camel_case + +dotnet_naming_style.begins_with_i.required_prefix = I +dotnet_naming_style.begins_with_i.required_suffix = +dotnet_naming_style.begins_with_i.word_separator = +dotnet_naming_style.begins_with_i.capitalization = pascal_case + +dotnet_naming_style.camel_case_underscore_prefix.required_prefix = _ +dotnet_naming_style.camel_case_underscore_prefix.required_suffix = +dotnet_naming_style.camel_case_underscore_prefix.word_separator = +dotnet_naming_style.camel_case_underscore_prefix.capitalization = camel_case + +dotnet_style_operator_placement_when_wrapping = beginning_of_line +tab_width = 4 +indent_size = 4 +dotnet_style_coalesce_expression = true:suggestion +dotnet_style_null_propagation = true:suggestion +dotnet_style_prefer_is_null_check_over_reference_equality_method = true:suggestion +dotnet_style_prefer_auto_properties = true:silent +dotnet_style_object_initializer = true:suggestion +dotnet_style_collection_initializer = true:suggestion +dotnet_style_prefer_simplified_boolean_expressions = true:suggestion +dotnet_style_prefer_conditional_expression_over_assignment = true:suggestion +dotnet_style_prefer_conditional_expression_over_return = true:suggestion +dotnet_style_explicit_tuple_names = true:suggestion +dotnet_style_prefer_inferred_tuple_names = true:suggestion +dotnet_style_prefer_inferred_anonymous_type_member_names = true:suggestion +dotnet_style_prefer_compound_assignment = true:suggestion +dotnet_style_prefer_simplified_interpolation = true:suggestion +dotnet_style_namespace_match_folder = true:suggestion +dotnet_style_readonly_field = true:suggestion +dotnet_style_predefined_type_for_locals_parameters_members = true:silent +dotnet_style_predefined_type_for_member_access = true:silent +dotnet_style_require_accessibility_modifiers = for_non_interface_members:silent +dotnet_style_allow_multiple_blank_lines_experimental = true:silent +dotnet_style_allow_statement_immediately_after_block_experimental = true:silent +dotnet_code_quality_unused_parameters = all:suggestion +dotnet_style_parentheses_in_other_binary_operators = always_for_clarity:silent +dotnet_style_parentheses_in_arithmetic_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 +dotnet_style_qualification_for_property = false:suggestion +dotnet_style_qualification_for_field = false:suggestion +dotnet_style_qualification_for_method = false:suggestion +dotnet_style_qualification_for_event = false:suggestion diff --git a/.github/workflows/stale.yml b/.github/workflows/stale.yml new file mode 100644 index 0000000000..0ffccb49d9 --- /dev/null +++ b/.github/workflows/stale.yml @@ -0,0 +1,48 @@ +name: 'Stale Issue and PR Cleanup' +on: + workflow_dispatch: + schedule: + - cron: '0 4 * * *' + +permissions: + issues: write + pull-requests: write + +jobs: + stale: + runs-on: ubuntu-latest + steps: + - uses: actions/stale@v4.1.0 + id: stale + with: + days-before-stale: 30 + days-before-close: 14 + exempt-all-assignees: false + exempt-draft-pr: true + stale-issue-label: "Pending Closure" + stale-pr-label: '0 - Waiting on User' + only-pr-labels: '0 - Waiting on User' + close-issue-label: "No Response / Stale" + close-pr-label: "No Response / Stale" + exempt-issue-labels: 'Security / CVE,0 - Backlog,1 - Ready for work,2 - Working,3 - Review,4 - Done,5 - Push required' + exempt-pr-labels: 'Security / CVE' + labels-to-remove-when-unstale: '0 - Wating on User,Pending closure' + stale-issue-message: | + Is this still relevant? If so, what is blocking it? Is there anything you can do to help move it forward? + This issue will be closed in 14 days if it continues to be inactive. + close-issue-message: | + Dear contributor, + + As this issue seems to have been inactive for quite some time now, it has been automatically closed. + If you feel this is a valid issue, please feel free to re-open the issue if / when a pull request + has been added. + Thank you for your contribution. + + close-pr-message: | + Dear contributor, + + As this PR seems to have been inactive for 30 days after changes / additional information + was requested, it has been automatically closed. + If you feel the changes are still valid, please re-open the PR once all changes or additional information + that was requested has been added. + Thank you for your contribution. diff --git a/.gitignore b/.gitignore index 9b33e30810..4112787edb 100644 --- a/.gitignore +++ b/.gitignore @@ -5,7 +5,8 @@ code_drop [Bb]in obj src/packages -/.vscode/ +/.vscode/** +!/.vscode/settings.json .vs *.suo @@ -38,12 +39,12 @@ src/_dotTrace.chocolatey/ src/chocolatey.sln.GhostDoc.xml chocolatey.official.snk +chocolatey.license.xml docs/generated # Testing related .vagrant -buildOutput.txt # Build related tools/** diff --git a/.notifications/discord.txt b/.notifications/discord.txt new file mode 100644 index 0000000000..b30b55b2a7 --- /dev/null +++ b/.notifications/discord.txt @@ -0,0 +1,5 @@ +We have just released v{0} of the Chocolatey CLI! + +Release notes can be found here: + +https://docs.chocolatey.org/en-us/choco/release-notes#{1} \ No newline at end of file diff --git a/.notifications/mastodon.txt b/.notifications/mastodon.txt new file mode 100644 index 0000000000..3a5b0ac123 --- /dev/null +++ b/.notifications/mastodon.txt @@ -0,0 +1 @@ +We have just released v{0} of the Chocolatey CLI! Release notes can be found here: https://docs.chocolatey.org/en-us/choco/release-notes#{1}. \ No newline at end of file diff --git a/.notifications/slack.txt b/.notifications/slack.txt new file mode 100644 index 0000000000..446fbcc70a --- /dev/null +++ b/.notifications/slack.txt @@ -0,0 +1,5 @@ +@channel We have just released v{0} of the Chocolatey CLI! + +Release notes can be found here: + +https://docs.chocolatey.org/en-us/choco/release-notes#{1} \ No newline at end of file diff --git a/.notifications/twitter.txt b/.notifications/twitter.txt new file mode 100644 index 0000000000..b30b55b2a7 --- /dev/null +++ b/.notifications/twitter.txt @@ -0,0 +1,5 @@ +We have just released v{0} of the Chocolatey CLI! + +Release notes can be found here: + +https://docs.chocolatey.org/en-us/choco/release-notes#{1} \ No newline at end of file diff --git a/.templates/default/issue-note.sbn b/.templates/default/issue-note.sbn index dbc4cf0548..01ae15c08e 100644 --- a/.templates/default/issue-note.sbn +++ b/.templates/default/issue-note.sbn @@ -1 +1 @@ -- {{ issue.title }} - see [#{{ issue.number }}]({{ issue.html_url }}) +- {{ issue.title }} - see [#{{ issue.number }}]({{ issue.html_url }}). diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 0000000000..4dc317cc50 --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,5 @@ +{ + "[powershell]": { + "files.encoding": "utf8bom", + } +} \ No newline at end of file diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index a11a075696..c442e3d46a 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,4 +1,5 @@ # Contributing + The Chocolatey team has very explicit information here regarding the process for contributions, and we will be sticklers about the way you write your commit messages (yes, really), so to save yourself some rework, please make sure you read over this entire document prior to contributing. @@ -10,7 +11,7 @@ The Chocolatey team has very explicit information here regarding the process for - [Package Request? Package Missing?](#package-request-package-missing) - [Submitting an Enhancement / Feature Request?](#submitting-an-enhancement--feature-request) - [Submitting an Enhancement For Choco](#submitting-an-enhancement-for-choco) -- [Contributing](#contributing) +- [Code Contributions](#code-contributions) - [Prerequisites](#prerequisites) - [Definition of Trivial Contributions](#definition-of-trivial-contributions) - [Is the CLA Really Required?](#is-the-cla-really-required) @@ -32,61 +33,71 @@ The Chocolatey team has very explicit information here regarding the process for ## Are You In the Right Place? + Chocolatey is a large ecosystem and each component has their own location for submitting issues and enhancement requests. While the website (the community package repository) may be all you know for packages, it represents only a tiny fraction of existing packages (organizations typically maintain and host their own packages internally). This is the repository for choco.exe (the client CLI tool) for Chocolatey, which spans multiple types of environments. Please follow these decision criteria to see if you are in the right location or if you should head to a different location to submit your request. ### Reporting an Issue/Bug? + ![submitting issues](https://cloud.githubusercontent.com/assets/63502/12534440/fc223b74-c21e-11e5-9a41-1ffc1c9af48f.png) Submitting an Issue (or a Bug)? See the **[Submitting Issues](https://github.com/chocolatey/choco#submitting-issues) section** in the [README](https://github.com/chocolatey/choco/blob/develop/README.md#submitting-issues). #### SolutionVersion.cs + Do not submit issues for missing `SolutionVersion.cs`. Please see [Compiling / Building Source](https://github.com/chocolatey/choco#compiling--building-source). ### Package Issue? + Please see [Request Package Fixes or Updates / Become a maintainer of an existing package](https://docs.chocolatey.org/en-us/community-repository/users/package-triage-process). ### Package Request? Package Missing? -If you are looking for packages to be added to the community feed (aka https://community.chocolatey.org/packages), please see [Package Requests](https://docs.chocolatey.org/en-us/community-repository/users/package-triage-process#package-request-package-missing). + +If you are looking for packages to be added to the community feed (aka ), please see [Package Requests](https://docs.chocolatey.org/en-us/community-repository/users/package-triage-process#package-request-package-missing). ### Submitting an Enhancement / Feature Request? + If this is for choco (the CLI tool), this is the right place. See below. Otherwise see [Submitting Issues](https://github.com/chocolatey/choco#submitting-issues) for enhancements to the website, enhancements to the ChocolateyGUI, etc. #### Submitting an Enhancement For Choco + Log a github issue. There are fewer constraints on this versus reporting issues. -## Contributing +## Code Contributions + The process for contributions is roughly as follows: ### Prerequisites - * Submit the Enhancement ticket. You will need the issue id for your commits. - * Ensure you have signed the Contributor License Agreement (CLA) - without this we are not able to take contributions that are not trivial. - * [Sign the Contributor License Agreement](https://cla-assistant.io/chocolatey/choco). - * You must do this for each Chocolatey project that requires it. - * If you are curious why we would require a CLA, we agree with Julien Ponge - take a look at his [post](https://julien.ponge.org/blog/in-defense-of-contributor-license-agreements/). - * You agree to follow the [etiquette regarding communication](https://github.com/chocolatey/choco#etiquette-regarding-communication). + +- Submit the Enhancement ticket. You will need the issue id for your commits. +- Ensure you have signed the Contributor License Agreement (CLA) - without this we are not able to take contributions that are not trivial. +- [Sign the Contributor License Agreement](https://cla-assistant.io/chocolatey/choco). +- You must do this for each Chocolatey project that requires it. +- If you are curious why we would require a CLA, we agree with Julien Ponge - take a look at his [post](https://julien.ponge.org/blog/in-defense-of-contributor-license-agreements/). +- You agree to follow the [etiquette regarding communication](https://github.com/chocolatey/choco#etiquette-regarding-communication). #### Definition of Trivial Contributions + It's hard to define what is a trivial contribution. Sometimes even a 1 character change can be considered significant. Unfortunately because it can be subjective, the decision on what is trivial comes from the committers of the project and not from folks contributing to the project. It is generally safe to assume that you may be subject to signing the [CLA](https://cla-assistant.io/chocolatey/choco) and be prepared to do so. Ask in advance if you are not sure and for reasons are not able to sign the [CLA](https://cla-assistant.io/chocolatey/choco). What is generally considered trivial: -* Fixing a typo -* Documentation changes -* Fixes to non-production code - like fixing something small in the build code. +- Fixing a typo +- Documentation changes +- Fixes to non-production code - like fixing something small in the build code. What is generally not considered trivial: - * Changes to any code that would be delivered as part of the final product. This includes any scripts that are delivered, such as PowerShell scripts. Yes, even 1 character changes could be considered non-trivial. +- Changes to any code that would be delivered as part of the final product. This includes any scripts that are delivered, such as PowerShell scripts. Yes, even 1 character changes could be considered non-trivial. #### Is the CLA Really Required? Yes, and this aspect is not up for discussion. If you would like more resources on understanding CLAs, please see the following articles: -* [In defense of Contributor License Agreements](https://julien.ponge.org/blog/in-defense-of-contributor-license-agreements/) -* [Contributor License Agreements](http://oss-watch.ac.uk/resources/cla) -* Dissenting opinion - [Why your project doesn't need a Contributor License Agreement](https://sfconservancy.org/blog/2014/jun/09/do-not-need-cla/) +- [In defense of Contributor License Agreements](https://julien.ponge.org/blog/in-defense-of-contributor-license-agreements/) +- [Contributor License Agreements](http://oss-watch.ac.uk/resources/cla) +- Dissenting opinion - [Why your project doesn't need a Contributor License Agreement](https://sfconservancy.org/blog/2014/jun/09/do-not-need-cla/) Overall, the flexibility and legal protections provided by a CLA make it necessary to require a CLA. As there is a company and a licensed version behind Chocolatey, those protections must be afforded. We understand this means some folks won't be able to contribute and that's completely fine. We prefer you to know up front this is required so you can make the best decision about contributing. @@ -97,14 +108,16 @@ If you work for an organization that does not allow you to contribute without at Start with [Prerequisites](#prerequisites) and make sure you can sign the Contributor License Agreement (CLA). ### Get Buyoff Or Find Open Community Issues/Features - * Through a GitHub issue (preferred), through the [mailing list](https://groups.google.com/forum/#!forum/chocolatey), or through [Community Chat](https://ch0.co/community-support), talk about a feature you would like to see (or a bug fix), and why it should be in Chocolatey. - * If approved through the mailing list or in Community chat, ensure the accompanying GitHub issue is created with information and a link back to the mailing list discussion (or the Community Chat conversation). - * Once you get a nod from one of the [Chocolatey Team](https://github.com/chocolatey?tab=members), you can start on the feature. - * Alternatively, if a feature is on the issues list with the [Up For Grabs](https://github.com/chocolatey/choco/issues?q=is%3Aopen+is%3Aissue+label%3A%22Up+For+Grabs%22) label, it is open for a community member (contributor) to patch. You should comment that you are signing up for it on the issue so someone else doesn't also sign up for the work. + +- Through a GitHub issue (preferred), through the [mailing list](https://groups.google.com/forum/#!forum/chocolatey), or through [Community Chat](https://ch0.co/community-support), talk about a feature you would like to see (or a bug fix), and why it should be in Chocolatey. + - If approved through the mailing list or in Community chat, ensure the accompanying GitHub issue is created with information and a link back to the mailing list discussion (or the Community Chat conversation). +- Once you get a nod from one of the [Chocolatey Team](https://github.com/chocolatey?tab=members), you can start on the feature. +- Alternatively, if a feature is on the issues list with the [Up For Grabs](https://github.com/chocolatey/choco/issues?q=is%3Aopen+is%3Aissue+label%3A%22Up+For+Grabs%22) label, it is open for a community member (contributor) to patch. You should comment that you are signing up for it on the issue so someone else doesn't also sign up for the work. ### Set Up Your Environment - * Visual Studio 2010+ is recommended for code contributions. - * For git specific information: + +- Visual Studio 2019+ is recommended for code contributions. +- For git specific information: 1. Create a fork of chocolatey/choco under your GitHub account. See [forks](https://help.github.com/articles/working-with-forks/) for more information. 1. [Clone your fork](https://help.github.com/articles/cloning-a-repository/) locally. 1. Open a command line and navigate to that directory. @@ -112,56 +125,66 @@ Start with [Prerequisites](#prerequisites) and make sure you can sign the Contri 1. Run `git fetch upstream` 1. Ensure you have user name and email set appropriately to attribute your contributions - see [Name](https://help.github.com/articles/setting-your-username-in-git/) / [Email](https://help.github.com/articles/setting-your-email-in-git/). 1. Ensure that the local repository has the following settings (without `--global`, these only apply to the *current* repository): - * `git config core.autocrlf false` - * `git config core.symlinks false` - * `git config merge.ff false` - * `git config merge.log true` - * `git config fetch.prune true` - * `git config blame.ignoreRevsFile .git-blame-ignore-revs --local` + + ```powershell + git config core.autocrlf false` + git config core.symlinks false` + git config merge.ff false` + git config merge.log true` + git config fetch.prune true` + git config blame.ignoreRevsFile .git-blame-ignore-revs --local + ``` + 1. From there you create a branch named specific to the feature. 1. In the branch you do work specific to the feature. 1. For committing the code, please see [Prepare Commits](#prepare-commits). 1. See [Submit Pull Request (PR)](#submit-pull-request-pr). - * Please also observe the following: - * Unless specifically requested, do not reformat the code. It makes it very difficult to see the change you've made. - * Do not change files that are not specific to the feature. - * More covered below in the [**Prepare commits**](#prepare-commits) section. - * Test your changes and please help us out by updating and implementing some automated tests. It is recommended that all contributors spend some time looking over the tests in the source code. You can't go wrong emulating one of the existing tests and then changing it specific to the behavior you are testing. - * While not an absolute requirement, automated tests will help reviewers feel comfortable about your changes, which gets your contributions accepted faster. - * Please do not update your branch from the develop unless we ask you to. See the responding to feedback section below. +- Please also observe the following: + - Unless specifically requested, do not reformat the code. It makes it very difficult to see the change you've made. + - If you must reformat the code, apply the formatting changes in a separate commit to the actual changes so that we can more easily review your work. + - Do not change files that are not specific to the feature. + - More covered below in the [**Prepare commits**](#prepare-commits) section. +- Test your changes and please help us out by updating and implementing some automated tests. It is recommended that all contributors spend some time looking over the tests in the source code. You can't go wrong emulating one of the existing tests and then changing it specific to the behavior you are testing. + - While not an absolute requirement, automated tests will help reviewers feel comfortable about your changes, which gets your contributions accepted faster. +- Please do not update your branch from the develop unless we ask you to. See the responding to feedback section below. ### Code Format / Design + #### CSharp - * If you are using ReSharper, all of this is already in the shared resharper settings. - * Class names and Properties are `PascalCase` - this is nearly the only time you start with uppercase. - * Namespaces (and their representative folders) are lowercase. - * Methods and functions are lowercase. Breaks between words in functions are typically met with an underscore (`_`, e.g. `run_actual()`). - * Variables and parameters are `camelCase`. - * Constants are `UPPER_CASE`. - * There are some adapters over the .NET Framework to ensure some additional functionality works and is consistent. Sometimes this is completely seamless that you are using these (e.g. `Console`). + +These standards are enforced via the `.editorconfig` file in the repository. + +- Class names and almost all members (methods, constants, fields, and properties) are `PascalCase` +- `private` fields are `_camelCase` with an underscore prefix +- Namespaces (and their representative folders) are lowercase. +- Method parameters, local variables, and functions are `camelCase` +- There are some adapters over the .NET Framework to ensure some additional functionality works and is consistent. Sometimes this is completely seamless that you are using these (e.g. `Console`). #### PowerShell - * PowerShell must be CRLF and UTF-8. Git attributes are not used, so Git will not ensure this for you. - * The minimum version of PowerShell this must work with is v2. This makes things somewhat more limited but compatible across the board for all areas Chocolatey is deployed. It is getting harder to find a reference for PowerShell v2, but this is a good one: http://adamringenberg.com/powershell2/table-of-contents/. - * If you add a new file, also ensure you add it to the Visual Studio project and ensure it becomes an embedded resource. - * The last parameter in every function must be `[parameter(ValueFromRemainingArguments = $true)][Object[]] $ignoredArguments`. This allows for future expansion and compatibility - as new parameters are introduced and used, it doesn't break older versions of Chocolatey. - * Do not add new positional elements to functions. We want to promote using named parameters in calling functions. - * Do not remove any existing positional elements from functions. We need to maintain compatibility with older versions of Chocolatey. - * One of the first calls in a function is to debug what was passed to it - `Write-FunctionCallLogMessage -Invocation $MyInvocation -Parameters $PSBoundParameters` + +- PowerShell must be CRLF and UTF-8. Git attributes are not used, so Git will not ensure this for you. +- The minimum version of PowerShell this must work with is v2. This makes things somewhat more limited but compatible across the board for all areas Chocolatey is deployed. It is getting harder to find a reference for PowerShell v2, but this is a good one: . +- If you add a new file, also ensure you add it to the Visual Studio project and ensure it becomes an embedded resource. +- The last parameter in every function must be `[parameter(ValueFromRemainingArguments = $true)][Object[]] $ignoredArguments`. This allows for future expansion and compatibility - as new parameters are introduced and used, it doesn't break older versions of Chocolatey. +- Do not add new positional elements to functions. We want to promote using named parameters in calling functions. +- Do not remove any existing positional elements from functions. We need to maintain compatibility with older versions of Chocolatey. +- One of the first calls in a function is to debug what was passed to it - `Write-FunctionCallLogMessage -Invocation $MyInvocation -Parameters $PSBoundParameters` ### Debugging / Testing + When you want to manually verify your changes and run Choco, you have some options. **NOTE:** Chocolatey behaves differently when built with `Debug` and `Release` configurations. Release is always going to seek out the machine installation (`$env:ChocolateyInstall`), where Debug just runs right next to wherever the choco.exe file is. #### Visual Studio + When you are using Visual Studio, ensure the following: - * Use `Debug` configuration - debug configuration keeps your local changes separate from the machine installed Chocolatey. - * `chocolatey.console` is the project you are looking to run. - * If you make changes to anything that is in `chocolatey.resources`, delete the folder in `chocolatey.console\bin\Debug` that corresponds to where you've made changes as Chocolatey does not automatically detect changes in the files it is extracting from resource manifests. - * The automated testing framework that Chocolatey uses is [NUnit](https://www.nunit.org/), [TinySpec](https://www.nuget.org/packages/TinySpec.NUnit), [Moq](https://www.nuget.org/packages/moq), and [Should](https://www.nuget.org/packages/Should/). Do not be thrown off thinking it using something else based on seeing `Fact` attributes for specs/tests. That is TinySpec. - * For a good understanding of all frameworks used, please see [CREDITS](https://github.com/chocolatey/choco/blob/master/docs/legal/CREDITS.md) +- Use `Debug` configuration - debug configuration keeps your local changes separate from the machine installed Chocolatey. +- `chocolatey.console` is the project you are looking to run. +- If you make changes to anything that is in `chocolatey.resources`, delete the folder in `chocolatey.console\bin\Debug` that corresponds to where you've made changes as Chocolatey does not automatically detect changes in the files it is extracting from resource manifests. +- The automated testing framework that Chocolatey uses is [NUnit](https://www.nunit.org/), [TinySpec](https://www.nuget.org/packages/TinySpec.NUnit), [Moq](https://www.nuget.org/packages/moq), and [Should](https://www.nuget.org/packages/Should/). Do not be thrown off thinking it using something else based on seeing `Fact` attributes for specs/tests. That is TinySpec. +- For a good understanding of all frameworks used, please see [CREDITS](https://github.com/chocolatey/choco/blob/master/docs/legal/CREDITS.md) ##### Automated Tests @@ -175,67 +198,69 @@ We recognize the need for a very tight feedback loop (running and debugging test With the way the testing framework is designed, it is helpful to gain an understanding on how you can debug into tests. There are a couple of known oddities when it comes to trying to run tests in Visual Studio: - * You can run a test or tests within a class. - * You can also right click on a folder (and solution folder), a project, or the solution and run tests. - * You can ***not*** click on a file and attempt to run/debug automated tests. You will see the following message: "The target type doesn't contain tests from a known test framework or a 'Main' method." - * You also cannot run all tests within a file by selecting somewhere outside a testing class and attempting to run tests. You will see the message above. +- You can run a test or tests within a class. +- You can also right click on a folder (and solution folder), a project, or the solution and run tests. +- You can ***not*** click on a file and attempt to run/debug automated tests. You will see the following message: "The target type doesn't contain tests from a known test framework or a 'Main' method." +- You also cannot run all tests within a file by selecting somewhere outside a testing class and attempting to run tests. You will see the message above. Some quick notes on testing terminology (still a WIP): - * Testing - anything done to test, whether manual, automated, or otherwise. - * Automated Testing - Any type of written test that can be run in an automated way, typically in the form of C# tests. - * Spec / Fact / Observation - these are synonyms for a test or validation. - * System Under Test (SUT) - the code or concern you are testing. - * Mock / Fake / Stub / Double - an object that provides a known state back to the system under test when the system under test interacts with other objects. This can be done with unit and whitebox integration testing. This allows for actual unit testing as most units (classes/functions) depend on working with other units (classes/functions) to get or set information and state. While each of [these are slightly different](https://martinfowler.com/articles/mocksArentStubs.html), the basic functionality is that they are standing in for other production code. - * Concern - an area of production code you are testing in e.g. "Concern for AutoUninstallerService". - * Regression Test Suite / Regression Suite - The automated tests that are in the form of code. - * Whitebox Testing - tests where you access the internals of the application. - * Unit Testing - We define a unit as a class and a method in C#. In PowerShell this is per function. If it involves another class or function, you have graduated to an integration. This is where Mocks come in to ensure no outside state is introduced. - * Whitebox Integration Testing - testing anything that is more than a unit. - * System Integration Testing - testing anything that goes out of the bounds of the written production code. Typically when running the code to get or set some state is where you will see this. And yes, even using DateTime.Now counts as system integration testing as it accesses something external to the application. This is why you will see we insulate those calls to something in the application so they can be easily tested against. - * Blackbox Testing - tests where you do not access internals of the application - * Physical Integration Testing - This is where you are testing the application with other components such as config files. - * Blackbox Integration Testing / End to End Testing - This is where you are testing inputs and outputs of the system. +- Testing - anything done to test, whether manual, automated, or otherwise. +- Automated Testing - Any type of written test that can be run in an automated way, typically in the form of C# tests. +- Spec / Fact / Observation - these are synonyms for a test or validation. +- System Under Test (SUT) - the code or concern you are testing. +- Mock / Fake / Stub / Double - an object that provides a known state back to the system under test when the system under test interacts with other objects. This can be done with unit and whitebox integration testing. This allows for actual unit testing as most units (classes/functions) depend on working with other units (classes/functions) to get or set information and state. While each of [these are slightly different](https://martinfowler.com/articles/mocksArentStubs.html), the basic functionality is that they are standing in for other production code. +- Concern - an area of production code you are testing in e.g. "Concern for AutoUninstallerService". +- Regression Test Suite / Regression Suite - The automated tests that are in the form of code. +- Whitebox Testing - tests where you access the internals of the application. + - Unit Testing - We define a unit as a class and a method in C#. In PowerShell this is per function. If it involves another class or function, you have graduated to an integration. This is where Mocks come in to ensure no outside state is introduced. + - Whitebox Integration Testing - testing anything that is more than a unit. + - System Integration Testing - testing anything that goes out of the bounds of the written production code. Typically when running the code to get or set some state is where you will see this. And yes, even using DateTime.Now counts as system integration testing as it accesses something external to the application. This is why you will see we insulate those calls to something in the application so they can be easily tested against. +- Blackbox Testing - tests where you do not access internals of the application + - Physical Integration Testing - This is where you are testing the application with other components such as config files. + - Blackbox Integration Testing / End to End Testing - This is where you are testing inputs and outputs of the system. As far as testing goes, unit tests are extremely quick feedback and great for longer term maintenance, where black box tests give you the most coverage, but are the slowest feedback loops and typically the most frail. Each area of testing has strengths and weaknesses and it's good to understand each of them. **NOTE**: One of the hardest forms of automated testing is unit testing, as it almost always requires faking out other parts of the system (also known as mocking). #### Chocolatey Build + **NOTE:** When you are doing this, we almost always recommend you take the output of the build to another machine to do the testing, like the [Chocolatey Test Environment](https://github.com/chocolatey/chocolatey-test-environment). - * Run `build.bat`. - * There is a detailed log of the output in `code_drop`. - * You are looking for `code_drop\temp\_PublishedApps\choco_merged` or `code_drop\Packages\Chocolatey`. The `choco.exe` file contains everything it needs, but it does unpack the manifest on first use, so you could run into [#1292](https://github.com/chocolatey/choco/issues/1292). - * You will need to pass `--allow-unofficial-build` for it to work when built with release mode. - * You can also try `build.debug.bat` - note that it is newer and it may have an issue or two. It doesn't require `--allow-unofficial-build` as the binaries are built for debugging. - * Use `.\choco.exe` to point to the local file. By default in PowerShell.exe, if you have Chocolatey installed, when you call `choco`, that is using the installed `choco` and not the one in the folder you are currently in. You must be explicit. This catches nearly everyone. +- Run `build.bat`. +- There is a detailed log of the output in `code_drop`. +- You are looking for `code_drop\temp\_PublishedApps\choco_merged` or `code_drop\Packages\Chocolatey`. The `choco.exe` file contains everything it needs, but it does unpack the manifest on first use, so you could run into [#1292](https://github.com/chocolatey/choco/issues/1292). +- You will need to pass `--allow-unofficial-build` for it to work when built with release mode. +- You can also try `build.debug.bat` - note that it is newer and it may have an issue or two. It doesn't require `--allow-unofficial-build` as the binaries are built for debugging. +- Use `.\choco.exe` to point to the local file. By default in PowerShell.exe, if you have Chocolatey installed, when you call `choco`, that is using the installed `choco` and not the one in the folder you are currently in. You must be explicit. This catches nearly everyone. ### Prepare Commits + This section serves to help you understand what makes a good commit. A commit should observe the following: - * A commit is a small logical unit that represents a change. - * Should include new or changed tests relevant to the changes you are making. - * No unnecessary whitespace. Check for whitespace with `git diff --check` and `git diff --cached --check` before commit. - * You can stage parts of a file for commit. +- A commit is a small logical unit that represents a change. +- Should include new or changed tests relevant to the changes you are making. +- No unnecessary whitespace. Check for whitespace with `git diff --check` and `git diff --cached --check` before commit. +- You can stage parts of a file for commit. A commit message should observe the following (based on ["A Note About Git Commit Messages"](http://tbaggery.com/2008/04/19/a-note-about-git-commit-messages.html)): - * The first line of the commit message should be a short description around 50 characters in length and be prefixed with the GitHub issue it refers to with parentheses surrounding that. If the GitHub issue is #25, you should have `(#25)` prefixed to the message. **NOTE:** Previously, the requirement was to use something like `(GH-25)` in commit messages, however, that approach has been deprecated. - * If the commit is about documentation, the message should be prefixed with `(doc)`. - * If it is a trivial commit or one of formatting/spaces fixes, it should be prefixed with `(maint)`. - * After the subject, skip one line and fill out a body if the subject line is not informative enough. - * Sometimes you will find that even a tiny code change has a commit body that needs to be very detailed and make take more time to do than the actual change itself! - * The body: - * Should wrap at `72` characters. - * Explains more fully the reason(s) for the change and contrasts with previous behavior. - * Uses present tense. "Fix" versus "Fixed". +- The first line of the commit message should be a short description around 50 characters in length and be prefixed with the GitHub issue it refers to with parentheses surrounding that. If the GitHub issue is #25, you should have `(#25)` prefixed to the message. **NOTE:** Previously, the requirement was to use something like `(GH-25)` in commit messages, however, that approach has been deprecated. +- If the commit is about documentation, the message should be prefixed with `(doc)`. +- If it is a trivial commit or one of formatting/spaces fixes, it should be prefixed with `(maint)`. +- After the subject, skip one line and fill out a body if the subject line is not informative enough. +- Sometimes you will find that even a tiny code change has a commit body that needs to be very detailed and make take more time to do than the actual change itself! +- The body: + - Should wrap at `72` characters. + - Explains more fully the reason(s) for the change and contrasts with previous behavior. + - Uses present tense. "Fix" versus "Fixed". A good example of a commit message is as follows: -``` +```txt (#7) Installation Adds All Required Folders Previously the installation script worked for the older version of @@ -248,40 +273,43 @@ choco client properly. ``` ### Submit Pull Request (PR) + Prerequisites: - * You are making commits in a feature branch. - * All specs should be passing. +- You are making commits in a feature branch. +- All specs should be passing. Submitting PR: - * Once you feel it is ready, submit the pull request to the `chocolatey/choco` repository against the `develop` branch ([more information on this can be found here](https://help.github.com/articles/creating-a-pull-request)) unless specifically requested to submit it against another branch (for example, a `hotfix` or `release` branch). - * In the case of a larger change that is going to require more discussion, please submit a PR sooner. Waiting until you are ready may mean more changes than you are interested in if the changes are taking things in a direction the committers do not want to go. - * In the pull request, outline what you did and point to specific conversations (as in URLs) and issues that you are are resolving. This is a tremendous help for us in evaluation and acceptance. - * Once the pull request is in, please do not delete the branch or close the pull request (unless something is wrong with it). - * One of the Chocolatey Team members, or one of the committers, will evaluate it within a reasonable time period (which is to say usually within 2-4 weeks). Some things get evaluated faster or fast tracked. We are human and we have active lives outside of open source so don't fret if you haven't seen any activity on your pull request within a month or two. We don't have a Service Level Agreement (SLA) for pull requests. Just know that we will evaluate your pull request. +- Once you feel it is ready, submit the pull request to the `chocolatey/choco` repository against the `develop` branch ([more information on this can be found here](https://help.github.com/articles/creating-a-pull-request)) unless specifically requested to submit it against another branch (for example, a `hotfix` or `release` branch). +- In the case of a larger change that is going to require more discussion, please submit a PR sooner. Waiting until you are ready may mean more changes than you are interested in if the changes are taking things in a direction the committers do not want to go. +- In the pull request, outline what you did and point to specific conversations (as in URLs) and issues that you are are resolving. This is a tremendous help for us in evaluation and acceptance. +- Once the pull request is in, please do not delete the branch or close the pull request (unless something is wrong with it). +- One of the Chocolatey Team members, or one of the committers, will evaluate it within a reasonable time period (which is to say usually within 2-4 weeks). Some things get evaluated faster or fast tracked. We are human and we have active lives outside of open source so don't fret if you haven't seen any activity on your pull request within a month or two. We don't have a Service Level Agreement (SLA) for pull requests. Just know that we will evaluate your pull request. ### Respond to Feedback on Pull Request + We may have feedback for you in the form of requested changes or fixes. We generally like to see that pushed against the same topic branch (it will automatically update the PR). You can also fix/squash/rebase commits and push the same topic branch with `--force` (while it is generally acceptable to do this on topic branches not in the main repository, a force push should be avoided at all costs against the main repository). If we have comments or questions when we do evaluate it and receive no response, it will probably lessen the chance of getting accepted. Eventually this means it will be closed if it is not accepted. Please know this doesn't mean we don't value your contribution, just that things go stale. If in the future you want to pick it back up, feel free to address our concerns/questions/feedback and reopen the issue/open a new PR (referencing old one). Sometimes we may need you to rebase your commit against the latest code before we can review it further. If this happens, you can do the following: - * `git fetch upstream` (upstream would be the mainstream repo or `chocolatey/choco` in this case) - * `git checkout develop` - * `git rebase upstream/develop` - * `git checkout your-branch` - * `git rebase develop` - * Fix any merge conflicts - * `git push origin your-branch` (origin would be your GitHub repo or `your-github-username/choco` in this case). You may need to `git push origin your-branch --force` to get the commits pushed. This is generally acceptable with topic branches not in the mainstream repository. +- `git fetch upstream` (upstream would be the mainstream repo or `chocolatey/choco` in this case) +- `git checkout develop` +- `git rebase upstream/develop` +- `git checkout your-branch` +- `git rebase develop` +- Fix any merge conflicts +- `git push origin your-branch` (origin would be your GitHub repo or `your-github-username/choco` in this case). You may need to `git push origin your-branch --force` to get the commits pushed. This is generally acceptable with topic branches not in the mainstream repository. The only reasons a pull request should be closed and resubmitted are as follows: - * When the pull request is targeting the wrong branch (this doesn't happen as often). - * When there are updates made to the original by someone other than the original contributor (and the PR is not open for contributions). Then the old branch is closed with a note on the newer branch this supersedes #github_number. +- When the pull request is targeting the wrong branch (this doesn't happen as often). +- When there are updates made to the original by someone other than the original contributor (and the PR is not open for contributions). Then the old branch is closed with a note on the newer branch this supersedes #github_number. ## Other General Information + The helpers/utility functions that are available to the packages are what we consider the API. If you are working in the API, please note that you will need to maintain backwards compatibility. If you plan to rename a function or make it more generic, you must provide an alias in the [chocolateyInstaller.psm1](https://github.com/chocolatey/choco/blob/develop/src/chocolatey.resources/helpers/chocolateyInstaller.psm1) as part of what gets exported. You should not remove or reorder parameters, only add optional parameters to the end. They should be named and not positional (we are moving away from positional parameters as much as possible). If you reformat code or hit core functionality without an approval from a person on the Chocolatey Team, it's likely that no matter how awesome it looks afterwards, it will probably not get accepted. Reformatting code makes it harder for us to evaluate exactly what was changed. diff --git a/GenerateDocs.ps1 b/GenerateDocs.ps1 index c2ad41a2a9..4f35a92599 100644 --- a/GenerateDocs.ps1 +++ b/GenerateDocs.ps1 @@ -88,9 +88,9 @@ These are the functions from above as one list. * [Install-ChocolateyPath](xref:install-chocolateypath) - when specifying user path * [Install-ChocolateyEnvironmentVariable](xref:install-chocolateyenvironmentvariable) - when specifying user path * [Install-ChocolateyPinnedTaskBarItem](xref:install-chocolateypinnedtaskbaritem) -* [Install-ChocolateyShortcut](xref:install-chocolateyshortcut) - v0.9.9+ +* [Install-ChocolateyShortcut](xref:install-chocolateyshortcut) * [Update-SessionEnvironment](xref:update-sessionenvironment) -* [Get-PackageParameters](xref:get-packageparameters) - v0.10.8+ +* [Get-PackageParameters](xref:get-packageparameters) ## Complete List (alphabetical order) @@ -363,16 +363,8 @@ function Generate-CommandReference($commandName, $order) { $commandOutput += @("---") $commandOutput += @("Order: $order") $commandOutput += @("xref: choco-command-$commandNameLower") - - if ($commandName -eq 'List') { - $commandOutput += @("Title: $commandName/Search") - $commandOutput += @("Description: $commandName/Search Command (choco $commandNameLower)") - } - else { - $commandOutput += @("Title: $commandName") - $commandOutput += @("Description: $commandName Command (choco $commandNameLower)") - } - + $commandOutput += @("Title: $commandName") + $commandOutput += @("Description: $commandName Command (choco $commandNameLower)") $commandOutput += @("RedirectFrom:") $commandOutput += @(" - docs/commands$commandNameLower") $commandOutput += @(" - docs/commands-$commandNameLower") @@ -512,39 +504,39 @@ Chocolatey makes a number of environment variables available (You can access any * TEMP/TMP - Overridden to the CacheLocation, but may be the same as the original TEMP folder * ChocolateyInstall - Top level folder where Chocolatey is installed - * ChocolateyPackageName - The name of the package, equivalent to the `` field in the nuspec (0.9.9+) - * ChocolateyPackageTitle - The title of the package, equivalent to the `` field in the nuspec (0.10.1+) - * ChocolateyPackageVersion - The version of the package, equivalent to the `<version />` field in the nuspec (0.9.9+) + * ChocolateyPackageName - The name of the package, equivalent to the `<id />` field in the nuspec + * ChocolateyPackageTitle - The title of the package, equivalent to the `<title />` field in the nuspec + * ChocolateyPackageVersion - The version of the package, equivalent to the `<version />` field in the nuspec #### Advanced Environment Variables The following are more advanced settings: - * ChocolateyPackageParameters - Parameters to use with packaging, not the same as install arguments (which are passed directly to the native installer). Based on `--package-parameters`. (0.9.8.22+) - * CHOCOLATEY_VERSION - The version of Choco you normally see. Use if you are 'lighting' things up based on choco version. (0.9.9+) - Otherwise take a dependency on the specific version you need. - * ChocolateyForceX86 = If available and set to 'true', then user has requested 32bit version. (0.9.9+) - Automatically handled in built in Choco functions. - * OS_PLATFORM - Like Windows, macOS, Linux. (0.9.9+) - * OS_VERSION - The version of OS, like 6.1 something something for Windows. (0.9.9+) - * OS_NAME - The reported name of the OS. (0.9.9+) - * IS_PROCESSELEVATED = Is the process elevated? (0.9.9+) - * ChocolateyPackageInstallLocation - Install location of the software that the package installs. Displayed at the end of the package install. (0.9.10+) + * ChocolateyPackageParameters - Parameters to use with packaging, not the same as install arguments (which are passed directly to the native installer). Based on `--package-parameters`. + * CHOCOLATEY_VERSION - The version of Choco you normally see. Use if you are 'lighting' things up based on choco version, otherwise take a dependency on the specific version you need. + * ChocolateyForceX86 = If available and set to 'true', then user has requested 32bit version. Automatically handled in built in Choco functions. + * OS_PLATFORM - Like Windows, macOS, Linux. + * OS_VERSION - The version of OS, like 6.1 something something for Windows. + * OS_NAME - The reported name of the OS. + * IS_PROCESSELEVATED = Is the process elevated? + * ChocolateyPackageInstallLocation - Install location of the software that the package installs. Displayed at the end of the package install. #### Set By Options and Configuration Some environment variables are set based on options that are passed, configuration and/or features that are turned on: - * ChocolateyEnvironmentDebug - Was `--debug` passed? If using the built-in PowerShell host, this is always true (but only logs debug messages to console if `--debug` was passed) (0.9.10+) - * ChocolateyEnvironmentVerbose - Was `--verbose` passed? If using the built-in PowerShell host, this is always true (but only logs verbose messages to console if `--verbose` was passed). (0.9.10+) - * ChocolateyForce - Was `--force` passed? (0.9.10+) - * ChocolateyForceX86 - Was `-x86` passed? (CHECK) - * ChocolateyRequestTimeout - How long before a web request will time out. Set by config `webRequestTimeoutSeconds` (CHECK) - * ChocolateyResponseTimeout - How long to wait for a download to complete? Set by config `commandExecutionTimeoutSeconds` (CHECK) - * ChocolateyPowerShellHost - Are we using the built-in PowerShell host? Set by `--use-system-powershell` or the feature `powershellHost` (0.9.10+) + * ChocolateyEnvironmentDebug - Was `--debug` passed? If using the built-in PowerShell host, this is always true (but only logs debug messages to console if `--debug` was passed) + * ChocolateyEnvironmentVerbose - Was `--verbose` passed? If using the built-in PowerShell host, this is always true (but only logs verbose messages to console if `--verbose` was passed). + * ChocolateyForce - Was `--force` passed? + * ChocolateyForceX86 - Was `-x86` passed? + * ChocolateyRequestTimeout - How long before a web request will time out. Set by config `webRequestTimeoutSeconds` + * ChocolateyResponseTimeout - How long to wait for a download to complete? Set by config `commandExecutionTimeoutSeconds` + * ChocolateyPowerShellHost - Are we using the built-in PowerShell host? Set by `--use-system-powershell` or the feature `powershellHost` #### Business Edition Variables - * ChocolateyInstallArgumentsSensitive - Encrypted arguments passed from command line `--install-arguments-sensitive` that are not logged anywhere. (0.10.1+ and licensed editions 1.6.0+) - * ChocolateyPackageParametersSensitive - Package parameters passed from command line `--package-parameters-sensitive` that are not logged anywhere. (0.10.1+ and licensed editions 1.6.0+) + * ChocolateyInstallArgumentsSensitive - Encrypted arguments passed from command line `--install-arguments-sensitive` that are not logged anywhere. + * ChocolateyPackageParametersSensitive - Package parameters passed from command line `--package-parameters-sensitive` that are not logged anywhere. * ChocolateyLicensedVersion - What version is the licensed edition on? * ChocolateyLicenseType - What edition / type of the licensed edition is installed? @@ -552,30 +544,30 @@ Some environment variables are set based on options that are passed, configurati The following are experimental or use not recommended: - * OS_IS64BIT = This may not return correctly - it may depend on the process the app is running under (0.9.9+) - * CHOCOLATEY_VERSION_PRODUCT = the version of Choco that may match CHOCOLATEY_VERSION but may be different (0.9.9+) - based on git describe - * IS_ADMIN = Is the user an administrator? But doesn't tell you if the process is elevated. (0.9.9+) + * OS_IS64BIT = This may not return correctly - it may depend on the process the app is running under + * CHOCOLATEY_VERSION_PRODUCT = the version of Choco that may match CHOCOLATEY_VERSION but may be different - based on git describe + * IS_ADMIN = Is the user an administrator? But doesn't tell you if the process is elevated. #### Not Useful Or Anti-Pattern If Used - * ChocolateyInstallOverride - Not for use in package automation scripts. Based on `--override-arguments` being passed. (0.9.9+) - * ChocolateyInstallArguments - The installer arguments meant for the native installer. You should use chocolateyPackageParameters instead. Based on `--install-arguments` being passed. (0.9.9+) - * ChocolateyIgnoreChecksums - Was `--ignore-checksums` passed or the feature `checksumFiles` turned off? (0.9.9.9+) - * ChocolateyAllowEmptyChecksums - Was `--allow-empty-checksums` passed or the feature `allowEmptyChecksums` turned on? (0.10.0+) - * ChocolateyAllowEmptyChecksumsSecure - Was `--allow-empty-checksums-secure` passed or the feature `allowEmptyChecksumsSecure` turned on? (0.10.0+) - * ChocolateyChecksum32 - Was `--download-checksum` passed? (0.10.0+) - * ChocolateyChecksumType32 - Was `--download-checksum-type` passed? (0.10.0+) - * ChocolateyChecksum64 - Was `--download-checksum-x64` passed? (0.10.0)+ - * ChocolateyChecksumType64 - Was `--download-checksum-type-x64` passed? (0.10.0)+ - * ChocolateyPackageExitCode - The exit code of the script that just ran - usually set by `Set-PowerShellExitCode` (CHECK) + * ChocolateyInstallOverride - Not for use in package automation scripts. Based on `--override-arguments` being passed. + * ChocolateyInstallArguments - The installer arguments meant for the native installer. You should use chocolateyPackageParameters instead. Based on `--install-arguments` being passed. + * ChocolateyIgnoreChecksums - Was `--ignore-checksums` passed or the feature `checksumFiles` turned off? + * ChocolateyAllowEmptyChecksums - Was `--allow-empty-checksums` passed or the feature `allowEmptyChecksums` turned on? + * ChocolateyAllowEmptyChecksumsSecure - Was `--allow-empty-checksums-secure` passed or the feature `allowEmptyChecksumsSecure` turned on? + * ChocolateyChecksum32 - Was `--download-checksum` passed? + * ChocolateyChecksumType32 - Was `--download-checksum-type` passed? + * ChocolateyChecksum64 - Was `--download-checksum-x64` passed? + * ChocolateyChecksumType64 - Was `--download-checksum-type-x64` passed? + * ChocolateyPackageExitCode - The exit code of the script that just ran - usually set by `Set-PowerShellExitCode` * ChocolateyLastPathUpdate - Set by Chocolatey as part of install, but not used for anything in particular in packaging. - * ChocolateyProxyLocation - The explicit proxy location as set in the configuration `proxy` (0.9.9.9+) - * ChocolateyDownloadCache - Use available download cache? Set by `--skip-download-cache`, `--use-download-cache`, or feature `downloadCache` (0.9.10+ and licensed editions 1.1.0+) - * ChocolateyProxyBypassList - Explicitly set locations to ignore in configuration `proxyBypassList` (0.10.4+) - * ChocolateyProxyBypassOnLocal - Should the proxy bypass on local connections? Set based on configuration `proxyBypassOnLocal` (0.10.4+) - * http_proxy - Set by original `http_proxy` passthrough, or same as `ChocolateyProxyLocation` if explicitly set. (0.10.4+) - * https_proxy - Set by original `https_proxy` passthrough, or same as `ChocolateyProxyLocation` if explicitly set. (0.10.4+) - * no_proxy- Set by original `no_proxy` passthrough, or same as `ChocolateyProxyBypassList` if explicitly set. (0.10.4+) + * ChocolateyProxyLocation - The explicit proxy location as set in the configuration `proxy` + * ChocolateyDownloadCache - Use available download cache? Set by `--skip-download-cache`, `--use-download-cache`, or feature `downloadCache` + * ChocolateyProxyBypassList - Explicitly set locations to ignore in configuration `proxyBypassList` + * ChocolateyProxyBypassOnLocal - Should the proxy bypass on local connections? Set based on configuration `proxyBypassOnLocal` + * http_proxy - Set by original `http_proxy` passthrough, or same as `ChocolateyProxyLocation` if explicitly set. + * https_proxy - Set by original `https_proxy` passthrough, or same as `ChocolateyProxyLocation` if explicitly set. + * no_proxy- Set by original `no_proxy` passthrough, or same as `ChocolateyProxyBypassList` if explicitly set. * ChocolateyPackageFolder - Not for use in package automation scripts. Recommend using `$toolsDir = "$(Split-Path -parent $MyInvocation.MyCommand.Definition)"` as per template generated by `choco new` * ChocolateyToolsLocation - Not for use in package automation scripts. Recommend using Get-ToolsLocation instead '@ diff --git a/Invoke-Tests.ps1 b/Invoke-Tests.ps1 index a172167793..91ef6510aa 100644 --- a/Invoke-Tests.ps1 +++ b/Invoke-Tests.ps1 @@ -31,7 +31,7 @@ $TestsLocation = Join-Path $PSScriptRoot tests $MaxFileNameLength = 110 $LongFiles = Get-ChildItem $TestsLocation -Recurse | Where-Object { ($_.FullName.Length - $TestsLocation.Length) -gt $MaxFileNameLength } | - Select-Object -Property @{Name = 'RelativePath' ; Expression = { $_.FullName.Replace($TestsLocation, [string]::Empty)}}, @{ Name = 'ReductionNeeded' ; Expression = { $_.FullName.Length - $TestsLocation.Length - $MaxFileNameLength } } + Select-Object -Property @{Name = 'RelativePath' ; Expression = { $_.FullName.Replace($TestsLocation, [string]::Empty) } }, @{ Name = 'ReductionNeeded' ; Expression = { $_.FullName.Length - $TestsLocation.Length - $MaxFileNameLength } } if ($LongFiles) { Write-Host "Tests' file paths may be too long for Test Kitchen use. Please shorten file names or paths:" @@ -50,7 +50,8 @@ else { if (-not (Test-Path "$TestPath/packages") -or -not $SkipPackaging) { $null = New-Item -Path "$TestPath/packages" -ItemType Directory -Force # Get and pack packages - $nuspecs = Get-ChildItem -Path $PSScriptRoot/src/chocolatey.tests.integration, $PSScriptRoot/tests/packages -Recurse | Where-Object Name -Like '*.nuspec' + $nuspecs = Get-ChildItem -Path $PSScriptRoot/src/chocolatey.tests.integration, $PSScriptRoot/tests/packages -Recurse -Include *.nuspec + Get-ChildItem -Path $PSScriptRoot/tests/packages -Recurse -Include *.nupkg | Copy-Item -Destination "$TestPath/packages" foreach ($file in $nuspecs) { Write-Host "Packaging $file" @@ -118,6 +119,9 @@ try { } ) } + Should = @{ + ErrorAction = 'Continue' + } } Invoke-Pester -Configuration $PesterConfiguration diff --git a/README.md b/README.md index dcecf8a2a8..ef882edff2 100644 --- a/README.md +++ b/README.md @@ -75,9 +75,11 @@ Please see the [docs](https://docs.chocolatey.org/en-us/) Give `choco.exe -?` a shot (or `choco.exe -h`). For specific commands, add the command and then the help switch e.g. `choco.exe install -h`. ### Requirements -* .NET Framework 4.0+ + +* .NET Framework 4.8+ * PowerShell 2.0+ -* Windows Server 2003+ / Windows 7+ +* Windows Server 2008 R2+ / Windows 10+ + - See our documentation on the [support lifecycle and supported operating systems](https://docs.chocolatey.org/en-us/information/support-lifecycle) for additional information ### License / Credits Apache 2.0 - see [LICENSE](https://github.com/chocolatey/choco/blob/master/LICENSE) and [NOTICE](https://github.com/chocolatey/choco/blob/master/NOTICE) files. diff --git a/docs/legal/CREDITS.md b/docs/legal/CREDITS.md index 701d91adac..6518e8495f 100644 --- a/docs/legal/CREDITS.md +++ b/docs/legal/CREDITS.md @@ -12,7 +12,7 @@ - [log4net @ 2.0.12](#log4net--2012) - [Microsoft.Bcl.HashCode @ 1.1.1](#microsoftbclhashcode--111) - [Microsoft.Web.Xdt @ 2.1.1](#microsoftwebxdt--211) - - [NuGet.Client @ 3.0.0-alpha-20230123-128 (modified)](#nugetclient--300-alpha-20230123-128-modified) + - [Chocolatey.NuGet.Client @ 3.1.0](#chocolateynugetclient--310) - [Rhino.Licensing @ 1.4.1 (modified)](#rhinolicensing--141-modified) - [Shim Generator (shimgen) @ 1.0.0](#shim-generator-shimgen--100) - [SimpleInjector @ 2.8.3](#simpleinjector--283) @@ -601,7 +601,6 @@ SOFTWARE. ### Microsoft.Web.Xdt @ 2.1.1 Chocolatey uses [Microsoft.Web.Xdt](https://www.nuget.org/packages/Microsoft.Web.xdt) to perform Xml Document Transformation. -It is also a requirement of NuGet.Core. [License terms](https://www.microsoft.com/web/webpi/eula/microsoft_web_xmltransform.htm): ```txt @@ -708,7 +707,7 @@ It is also a requirement of NuGet.Core. It also applies even if Microsoft knew or should have known about the possibility of the damages. The above limitation or exclusion may not apply to you because your country may not allow the exclusion or limitation of incidental, consequential or other damages. ``` -### NuGet.Client @ 3.0.0-alpha-20230123-128 (modified) +### Chocolatey.NuGet.Client @ 3.1.0 Chocolatey uses [NuGet.Client](https://github.com/NuGet/NuGet.Client) [(modified)](https://github.com/chocolatey/NuGet.Client) to work with packaging. [License terms](https://github.com/NuGet/NuGet.Client/blob/72f9f2b2eab28c9d91a22065c55aa7702abf7e01/LICENSE.txt): diff --git a/gitreleasemanager.yaml b/gitreleasemanager.yaml index cd9744b436..8234d9bb20 100644 --- a/gitreleasemanager.yaml +++ b/gitreleasemanager.yaml @@ -1,37 +1,37 @@ -issue-labels-include: -- Breaking Change -- Deprecate -- Feature -- C4B Feature -- Bug -- Enhancement -- Documentation -issue-labels-exclude: -- Internal Refactoring -- Build -- NO RELEASE NOTES -issue-labels-alias: - - name: Documentation - header: Documentation - plural: Documentation - - name: Bug - header: Bug Fix - plural: Bug Fixes - - name: Deprecate - header: Deprecated Feature - plural: Deprecated Features -create: - include-sha-section: true - sha-section-heading: "SHA256 Hashes of the release artifacts" - sha-section-line-format: "- `{1}\t{0}`" -close: - use-issue-comments: true - issue-comment: |- - :tada: This issue has been resolved in version {milestone} :tada: - - The release is available on: - - - [GitHub Release](https://github.com/{owner}/{repository}/releases/tag/{milestone}) - - [Chocolatey Package](https://chocolatey.org/packages/chocolatey/{milestone}) - - Your **[GitReleaseManager](https://github.com/GitTools/GitReleaseManager)** bot :package::rocket: +issue-labels-include: +- Breaking Change +- Deprecate +- Feature +- C4B Feature +- Bug +- Improvement +- Documentation +issue-labels-exclude: +- Internal Refactoring +- BuildAutomation +- NO RELEASE NOTES +issue-labels-alias: + - name: Documentation + header: Documentation + plural: Documentation + - name: Bug + header: Bug Fix + plural: Bug Fixes + - name: Deprecate + header: Deprecated Feature + plural: Deprecated Features +create: + include-sha-section: true + sha-section-heading: "SHA256 Hashes of the release artifacts" + sha-section-line-format: "- `{1}\t{0}`" +close: + use-issue-comments: true + issue-comment: |- + :tada: This issue has been resolved in version {milestone} :tada: + + The release is available on: + + - [GitHub Release](https://github.com/{owner}/{repository}/releases/tag/{milestone}) + - [Chocolatey Package](https://chocolatey.org/packages/chocolatey/{milestone}) + + Your **[GitReleaseManager](https://github.com/GitTools/GitReleaseManager)** bot :package::rocket: diff --git a/nuspec/chocolatey/chocolatey/chocolatey.nuspec b/nuspec/chocolatey/chocolatey/chocolatey.nuspec index 4c14e90a89..412e20991a 100644 --- a/nuspec/chocolatey/chocolatey/chocolatey.nuspec +++ b/nuspec/chocolatey/chocolatey/chocolatey.nuspec @@ -19,22 +19,6 @@ <tags>nuget apt-get machine repository chocolatey</tags> <summary>Chocolatey is the package manager for Windows (like apt-get but for Windows)</summary> <description> -> **Warning** -> -> This is a pre-release version of Chocolatey CLI and it is **NOT** suitable for production use! A pre-release version will have bugs that could have a detrimental impact to your environment. Ensure all necessary due diligence steps are taken before using in your environment. - -> **Warning** -> -> This pre-release version of Chocolatey CLI does **NOT** work with the Chocolatey Licensed Extension. It will actually prevent the loading of the Chocolatey Licensed Extension if it is installed. - -> **Note** -> -> If you run into any problems when using this alpha version of Chocolatey CLI we would ask that you comment on this [discussion](https://github.com/chocolatey/choco/discussions/2995), which is where we will be collating issues, and providing workarounds, etc. We will not be accepting issues raised against this alpha release. - -### Known Issues - -See this [list](https://github.com/chocolatey/choco/discussions/2995) for known issues with this pre-release. - Chocolatey is a package manager for Windows (like apt-get but for Windows). It was designed to be a decentralized framework for quickly installing applications and tools that you need. It is built on the NuGet infrastructure currently using PowerShell as its focus for delivering packages from the distros to your door, err computer. Chocolatey is brought to you by the work and inspiration of the community, the work and thankless nights of the [Chocolatey Team](https://github.com/orgs/chocolatey/people), with Rob heading up the direction. diff --git a/nuspec/chocolatey/chocolatey/tools/chocolateysetup.psm1 b/nuspec/chocolatey/chocolatey/tools/chocolateysetup.psm1 index a9543c8c0f..66c25928b5 100644 --- a/nuspec/chocolatey/chocolatey/tools/chocolateysetup.psm1 +++ b/nuspec/chocolatey/chocolatey/tools/chocolateysetup.psm1 @@ -1,4 +1,4 @@ -$thisScriptFolder = (Split-Path -Parent $MyInvocation.MyCommand.Definition) +$thisScriptFolder = (Split-Path -Parent $MyInvocation.MyCommand.Definition) $chocoInstallVariableName = "ChocolateyInstall" $sysDrive = $env:SystemDrive $tempDir = $env:TEMP @@ -78,7 +78,7 @@ function Remove-ShimWithAuthenticodeSignature { function Remove-UnsupportedShimFiles { param([string[]]$Paths) - $shims = @("cpack.exe", "cver.exe") + $shims = @("cpack.exe", "cver.exe", "chocolatey.exe", "cinst.exe", "clist.exe", "cpush.exe", "cuninst.exe", "cup.exe") $Paths | ForEach-Object { $path = $_ @@ -171,8 +171,6 @@ Creating Chocolatey folders if they do not already exist. "@ | Write-Output - Write-ChocolateyWarning "You can safely ignore errors related to missing log files when `n upgrading from a version of Chocolatey less than 0.9.9. `n 'Batch file could not be found' is also safe to ignore. `n 'The system cannot find the file specified' - also safe." - #create the base structure if it doesn't exist Create-DirectoryIfNotExists $chocolateyExePath Create-DirectoryIfNotExists $chocolateyLibPath diff --git a/nuspec/nuget/chocolatey.lib/chocolatey.lib.nuspec b/nuspec/nuget/chocolatey.lib/chocolatey.lib.nuspec index 37c755285c..96e24d58c5 100644 --- a/nuspec/nuget/chocolatey.lib/chocolatey.lib.nuspec +++ b/nuspec/nuget/chocolatey.lib/chocolatey.lib.nuspec @@ -14,22 +14,6 @@ <tags>apt-get machine repository chocolatey</tags> <summary>Chocolatey is the package manager for Windows (like apt-get but for Windows)</summary> <description> -> **Warning** -> -> This is a pre-release version of Chocolatey CLI and it is **NOT** suitable for production use! A pre-release version will have bugs that could have a detrimental impact to your environment. Ensure all necessary due diligence steps are taken before using in your environment. - -> **Warning** -> -> This pre-release version of Chocolatey CLI does **NOT** work with the Chocolatey Licensed Extension. It will actually prevent the loading of the Chocolatey Licensed Extension if it is installed. - -> **Note** -> -> If you run into any problems when using this alpha version of Chocolatey CLI we would ask that you comment on this [discussion](https://github.com/chocolatey/choco/discussions/2995), which is where we will be collating issues, and providing workarounds, etc. We will not be accepting issues raised against this alpha release. - -### Known Issues - -See this [list](https://github.com/chocolatey/choco/discussions/2995) for known issues with this pre-release. - Chocolatey is a package manager for Windows (like apt-get but for Windows). It was designed to be a decentralized framework for quickly installing applications and tools that you need. It is built on the NuGet infrastructure currently using PowerShell as its focus for delivering packages from the distros to your door, err computer. Chocolatey is brought to you by the work and inspiration of the community, the work and thankless nights of the Chocolatey Team (https://github.com/orgs/chocolatey/people), with Rob heading up the direction. diff --git a/recipe.cake b/recipe.cake index a0e753280f..92bfd865b7 100644 --- a/recipe.cake +++ b/recipe.cake @@ -1,4 +1,4 @@ -#load nuget:?package=Chocolatey.Cake.Recipe&version=0.21.0 +#load nuget:?package=Chocolatey.Cake.Recipe&version=0.22.0 /////////////////////////////////////////////////////////////////////////////// // TOOLS diff --git a/src/chocolatey.console/Program.cs b/src/chocolatey.console/Program.cs index 0923255ce2..39b2bbcc91 100644 --- a/src/chocolatey.console/Program.cs +++ b/src/chocolatey.console/Program.cs @@ -49,25 +49,23 @@ namespace chocolatey.console public sealed class Program { - // ReSharper disable InconsistentNaming private static void Main(string[] args) - // ReSharper restore InconsistentNaming { ChocolateyConfiguration config = null; ChocolateyLicense license = null; try { - add_assembly_resolver(); + AddAssemblyResolver(); string loggingLocation = ApplicationParameters.LoggingLocation; //no file system at this point if (!Directory.Exists(loggingLocation)) Directory.CreateDirectory(loggingLocation); - Log4NetAppenderConfiguration.configure(loggingLocation, excludeLoggerNames: ChocolateyLoggers.Trace.to_string()); - Bootstrap.initialize(); - Bootstrap.startup(); - license = License.validate_license(); + Log4NetAppenderConfiguration.Configure(loggingLocation, excludeLoggerNames: ChocolateyLoggers.Trace.ToStringSafe()); + Bootstrap.Initialize(); + Bootstrap.Startup(); + license = License.ValidateLicense(); var container = SimpleInjectorContainer.Container; "LogFileOnly".Log().Info(() => "".PadRight(60, '=')); @@ -77,13 +75,13 @@ private static void Main(string[] args) var warnings = new List<string>(); - if (license.AssemblyLoaded && !is_licensed_assembly_loaded(container)) + if (license.AssemblyLoaded && !IsLicensedAssemblyLoaded(container)) { license.AssemblyLoaded = false; license.IsCompatible = false; } - ConfigurationBuilder.set_up_configuration( + ConfigurationBuilder.SetupConfiguration( args, config, container, @@ -91,32 +89,32 @@ private static void Main(string[] args) warning => { warnings.Add(warning); } ); - if (license.AssemblyLoaded && license.is_licensed_version() && !license.IsCompatible && !config.DisableCompatibilityChecks) + if (license.AssemblyLoaded && license.IsLicensedVersion() && !license.IsCompatible && !config.DisableCompatibilityChecks) { - write_warning_for_incompatible_versions(); + WriteWarningForIncompatibleExtensionVersion(); } if (config.Features.LogWithoutColor) { ApplicationParameters.Log4NetConfigurationResource = @"chocolatey.infrastructure.logging.log4net.nocolor.config.xml"; - Log4NetAppenderConfiguration.configure(loggingLocation, excludeLoggerNames: ChocolateyLoggers.Trace.to_string()); + Log4NetAppenderConfiguration.Configure(loggingLocation, excludeLoggerNames: ChocolateyLoggers.Trace.ToStringSafe()); } if (!string.IsNullOrWhiteSpace(config.AdditionalLogFileLocation)) { - Log4NetAppenderConfiguration.configure_additional_log_file(fileSystem.get_full_path(config.AdditionalLogFileLocation)); + Log4NetAppenderConfiguration.SetupAdditionalLogFile(fileSystem.GetFullPath(config.AdditionalLogFileLocation)); } - report_version_and_exit_if_requested(args, config); + ReportVersionAndExitIfRequested(args, config); - trap_exit_scenarios(config); + TrapExitScenarios(config); if (config.RegularOutput) { #if DEBUG - "chocolatey".Log().Info(ChocolateyLoggers.Important, () => "{0} v{1}{2} (DEBUG BUILD)".format_with(ApplicationParameters.Name, config.Information.ChocolateyProductVersion, license.is_licensed_version() ? " {0}".format_with(license.LicenseType) : string.Empty)); + "chocolatey".Log().Info(ChocolateyLoggers.Important, () => "{0} v{1}{2} (DEBUG BUILD)".FormatWith(ApplicationParameters.Name, config.Information.ChocolateyProductVersion, license.IsLicensedVersion() ? " {0}".FormatWith(license.LicenseType) : string.Empty)); #else - "chocolatey".Log().Info(ChocolateyLoggers.Important, () => "{0} v{1}{2}".format_with(ApplicationParameters.Name, config.Information.ChocolateyProductVersion, license.is_licensed_version() ? " {0}".format_with(license.LicenseType) : string.Empty)); + "chocolatey".Log().Info(ChocolateyLoggers.Important, () => "{0} v{1}{2}".FormatWith(ApplicationParameters.Name, config.Information.ChocolateyProductVersion, license.IsLicensedVersion() ? " {0}".FormatWith(license.LicenseType) : string.Empty)); #endif if (args.Length == 0) { @@ -124,11 +122,11 @@ private static void Main(string[] args) } } - check_installed_dotnetfx_version(); + ThrowIfNotDotNet48(); if (warnings.Count != 0 && config.RegularOutput) { - foreach (var warning in warnings.or_empty_list_if_null()) + foreach (var warning in warnings.OrEmpty()) { "chocolatey".Log().Warn(ChocolateyLoggers.Important, warning); } @@ -136,21 +134,21 @@ private static void Main(string[] args) if (config.HelpRequested || config.UnsuccessfulParsing) { - pause_execution_if_debug(); + PauseIfDebug(); Environment.Exit(config.UnsuccessfulParsing ? 1 : 0); } - var verboseAppenderName = "{0}LoggingColoredConsoleAppender".format_with(ChocolateyLoggers.Verbose.to_string()); - var traceAppenderName = "{0}LoggingColoredConsoleAppender".format_with(ChocolateyLoggers.Trace.to_string()); - Log4NetAppenderConfiguration.set_logging_level_debug_when_debug(config.Debug, verboseAppenderName, traceAppenderName); - Log4NetAppenderConfiguration.set_verbose_logger_when_verbose(config.Verbose, config.Debug, verboseAppenderName); - Log4NetAppenderConfiguration.set_trace_logger_when_trace(config.Trace, traceAppenderName); - "chocolatey".Log().Debug(() => "{0} is running on {1} v {2}".format_with(ApplicationParameters.Name, config.Information.PlatformType, config.Information.PlatformVersion.to_string())); + var verboseAppenderName = "{0}LoggingColoredConsoleAppender".FormatWith(ChocolateyLoggers.Verbose.ToStringSafe()); + var traceAppenderName = "{0}LoggingColoredConsoleAppender".FormatWith(ChocolateyLoggers.Trace.ToStringSafe()); + Log4NetAppenderConfiguration.EnableDebugLoggingIf(config.Debug, verboseAppenderName, traceAppenderName); + Log4NetAppenderConfiguration.EnableVerboseLoggingIf(config.Verbose, config.Debug, verboseAppenderName); + Log4NetAppenderConfiguration.EnableTraceLoggingIf(config.Trace, traceAppenderName); + "chocolatey".Log().Debug(() => "{0} is running on {1} v {2}".FormatWith(ApplicationParameters.Name, config.Information.PlatformType, config.Information.PlatformVersion.ToStringSafe())); //"chocolatey".Log().Debug(() => "Command Line: {0}".format_with(Environment.CommandLine)); - remove_old_chocolatey_exe(fileSystem); + RemoveOldChocoExe(fileSystem); - AssemblyFileExtractor.extract_all_resources_to_relative_directory(fileSystem, Assembly.GetAssembly(typeof(Program)), ApplicationParameters.InstallLocation, new List<string>(), "chocolatey.console", throwError: false); + AssemblyFileExtractor.ExtractAssemblyResourcesToRelativeDirectory(fileSystem, Assembly.GetAssembly(typeof(Program)), ApplicationParameters.InstallLocation, new List<string>(), "chocolatey.console", throwError: false); //refactor - thank goodness this is temporary, cuz manifest resource streams are dumb IList<string> folders = new List<string> { @@ -160,52 +158,52 @@ private static void Main(string[] args) "tools" }; #if !NoResources - AssemblyFileExtractor.extract_all_resources_to_relative_directory(fileSystem, Assembly.GetAssembly(typeof(ChocolateyResourcesAssembly)), ApplicationParameters.InstallLocation, folders, ApplicationParameters.ChocolateyFileResources, throwError: false); + AssemblyFileExtractor.ExtractAssemblyResourcesToRelativeDirectory(fileSystem, Assembly.GetAssembly(typeof(ChocolateyResourcesAssembly)), ApplicationParameters.InstallLocation, folders, ApplicationParameters.ChocolateyFileResources, throwError: false); #endif var application = new ConsoleApplication(); - application.run(args, config, container); + application.Run(args, config, container); } catch (Exception ex) { - if (ApplicationParameters.is_debug_mode_cli_primitive()) + if (ApplicationParameters.IsDebugModeCliPrimitive()) { - "chocolatey".Log().Error(() => "{0} had an error occur:{1}{2}".format_with( + "chocolatey".Log().Error(() => "{0} had an error occur:{1}{2}".FormatWith( ApplicationParameters.Name, Environment.NewLine, ex.ToString())); } else { - "chocolatey".Log().Error(ChocolateyLoggers.Important, () => "{0}".format_with(ex.Message)); - "chocolatey".Log().Error(ChocolateyLoggers.LogFileOnly, () => "More Details: {0}".format_with(ex.ToString())); + "chocolatey".Log().Error(ChocolateyLoggers.Important, () => "{0}".FormatWith(ex.Message)); + "chocolatey".Log().Error(ChocolateyLoggers.LogFileOnly, () => "More Details: {0}".FormatWith(ex.ToString())); } if (Environment.ExitCode == 0) Environment.ExitCode = 1; } finally { - if (license != null && license.AssemblyLoaded && license.is_licensed_version() && !license.IsCompatible && config != null && !config.DisableCompatibilityChecks) + if (license != null && license.AssemblyLoaded && license.IsLicensedVersion() && !license.IsCompatible && config != null && !config.DisableCompatibilityChecks) { - write_warning_for_incompatible_versions(); + WriteWarningForIncompatibleExtensionVersion(); } - "chocolatey".Log().Debug(() => "Exiting with {0}".format_with(Environment.ExitCode)); + "chocolatey".Log().Debug(() => "Exiting with {0}".FormatWith(Environment.ExitCode)); #if DEBUG - "chocolatey".Log().Info(() => "Exiting with {0}".format_with(Environment.ExitCode)); + "chocolatey".Log().Info(() => "Exiting with {0}".FormatWith(Environment.ExitCode)); #endif - pause_execution_if_debug(); - Bootstrap.shutdown(); + PauseIfDebug(); + Bootstrap.Shutdown(); Environment.Exit(Environment.ExitCode); } } - private static bool is_licensed_assembly_loaded(Container container) + private static bool IsLicensedAssemblyLoaded(Container container) { var allExtensions = container.GetAllInstances<ExtensionInformation>(); foreach (var extension in allExtensions) { - if (extension.Name.is_equal_to("chocolatey.licensed")) + if (extension.Name.IsEqualTo("chocolatey.licensed")) { return extension.Status == ExtensionStatus.Enabled || extension.Status == ExtensionStatus.Loaded; } @@ -218,37 +216,37 @@ private static bool is_licensed_assembly_loaded(Container container) return true; } - private static void add_assembly_resolver() + private static void AddAssemblyResolver() { - AppDomain.CurrentDomain.AssemblyResolve += AssemblyResolution.resolve_extension_or_merged_assembly; + AppDomain.CurrentDomain.AssemblyResolve += AssemblyResolution.ResolveExtensionOrMergedAssembly; } - private static void report_version_and_exit_if_requested(string[] args, ChocolateyConfiguration config) + private static void ReportVersionAndExitIfRequested(string[] args, ChocolateyConfiguration config) { if (args == null || args.Length == 0) return; var firstArg = args.FirstOrDefault(); - if (firstArg.is_equal_to("-v") || firstArg.is_equal_to("--version")) + if (firstArg.IsEqualTo("-v") || firstArg.IsEqualTo("--version")) { - "chocolatey".Log().Info(ChocolateyLoggers.Important, () => "{0}".format_with(config.Information.ChocolateyProductVersion)); - pause_execution_if_debug(); + "chocolatey".Log().Info(ChocolateyLoggers.Important, () => "{0}".FormatWith(config.Information.ChocolateyProductVersion)); + PauseIfDebug(); "chocolatey".Log().Debug(() => "Exiting with 0"); Environment.Exit(0); } } - private static void trap_exit_scenarios(ChocolateyConfiguration config) + private static void TrapExitScenarios(ChocolateyConfiguration config) { ExitScenarioHandler.SetHandler(); } - private static void remove_old_chocolatey_exe(IFileSystem fileSystem) + private static void RemoveOldChocoExe(IFileSystem fileSystem) { - FaultTolerance.try_catch_with_logging_exception( + FaultTolerance.TryCatchWithLoggingException( () => { - fileSystem.delete_file(fileSystem.get_current_assembly_path() + ".old"); - fileSystem.delete_file(fileSystem.combine_paths(AppDomain.CurrentDomain.BaseDirectory, "choco.exe.old")); + fileSystem.DeleteFile(fileSystem.GetCurrentAssemblyPath() + ".old"); + fileSystem.DeleteFile(fileSystem.CombinePaths(AppDomain.CurrentDomain.BaseDirectory, "choco.exe.old")); }, errorMessage: "Attempting to delete choco.exe.old ran into an issue", throwError: false, @@ -258,7 +256,7 @@ private static void remove_old_chocolatey_exe(IFileSystem fileSystem) ); } - private static void pause_execution_if_debug() + private static void PauseIfDebug() { #if DEBUG Console.WriteLine("Press enter to continue..."); @@ -266,7 +264,7 @@ private static void pause_execution_if_debug() #endif } - private static void write_warning_for_incompatible_versions() + private static void WriteWarningForIncompatibleExtensionVersion() { "chocolatey".Log().Warn( ChocolateyLoggers.Important, @@ -291,23 +289,23 @@ Or by passing the --skip-compatibility-checks option when executing a command."); } - private static void check_installed_dotnetfx_version() + private static void ThrowIfNotDotNet48() { - if (Platform.get_platform() == PlatformType.Windows) + if (Platform.GetPlatform() == PlatformType.Windows) { // https://learn.microsoft.com/en-us/dotnet/framework/migration-guide/how-to-determine-which-versions-are-installed#minimum-version - const int NET48RELEASEBUILD = 528040; - const string REGKEY = @"SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Full\"; + const int net48ReleaseBuild = 528040; + const string regKey = @"SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Full\"; - using (var ndpKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32).OpenSubKey(REGKEY)) + using (var ndpKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32).OpenSubKey(regKey)) { - if (ndpKey == null || ndpKey.GetValue("Release") == null || (int)ndpKey.GetValue("Release") < NET48RELEASEBUILD) + if (ndpKey == null || ndpKey.GetValue("Release") == null || (int)ndpKey.GetValue("Release") < net48ReleaseBuild) { throw new ApplicationException( @".NET 4.8 is not installed or may need a reboot to complete installation. Please install .NET Framework 4.8 manually and reboot the system. Download at 'https://download.visualstudio.microsoft.com/download/pr/2d6bb6b2-226a-4baa-bdec-798822606ff1/8494001c276a4b96804cde7829c04d7f/ndp48-x86-x64-allos-enu.exe'" - .format_with(Environment.NewLine)); + .FormatWith(Environment.NewLine)); } } } diff --git a/src/chocolatey.console/choco.exe.manifest b/src/chocolatey.console/choco.exe.manifest index 14281f4d5c..c1092e653c 100644 --- a/src/chocolatey.console/choco.exe.manifest +++ b/src/chocolatey.console/choco.exe.manifest @@ -5,32 +5,30 @@ <security> <requestedPrivileges xmlns="urn:schemas-microsoft-com:asm.v3"> <!-- UAC Manifest Options - Specifying requestedExecutionLevel node (below) will disable file and + Specifying requestedExecutionLevel node (below) will disable file and registry virtualization. - + Set level to "asInvoker" when you want choco to run under the context - of the user invoking. This is the same as Chocolatey behavior prior - to 0.10.4 and after 0.10.7. - - Set level to "requireAdministrator" to only allow administrators to + of the user invoking. + + Set level to "requireAdministrator" to only allow administrators to run Chocolatey. - - Set level to "highestAvailable" to allow non-admins to run in + + Set level to "highestAvailable" to allow non-admins to run in non-administrative context, but require administrators to always run - with administrative privileges. This is the recommended and default - behavior of Chocolatey v0.10.4-0.10.6.1. - - NOTE: Currently you will need to make this change every time + with administrative privileges. + + NOTE: Currently you will need to make this change every time Chocolatey is re-installed or upgraded (every new version). At least for now - https://github.com/chocolatey/choco/issues/1206 - - The following is an unsupported use case: If you want to utilize File - and Registry Virtualization for backward compatibility then delete + + The following is an unsupported use case: If you want to utilize File + and Registry Virtualization for backward compatibility then delete the requestedExecutionLevel node. - + NOTE: If you do change this file, make sure that you change the - modification date on choco.exe that this sits next to. Windows - caches manifests based on path and last modified date. So you'll + modification date on choco.exe that this sits next to. Windows + caches manifests based on path and last modified date. So you'll need to change the modification date on choco.exe for the manifest change to take effect. Details: https://github.com/chocolatey/choco/issues/1292#issuecomment-304068121 @@ -39,7 +37,7 @@ </requestedPrivileges> </security> </trustInfo> - + <compatibility xmlns="urn:schemas-microsoft-com:compatibility.v1"> <application> <!-- Windows 10 / Windows Server 2016 --> @@ -50,8 +48,6 @@ <supportedOS Id="{4a2f28e3-53b9-4441-ba9c-d69d4a4a6e38}"/> <!-- Windows 7 / Windows Server 2008 R2 --> <supportedOS Id="{35138b9a-5d96-4fbd-8e2d-a2440225f93a}"/> - <!-- Windows Vista / Windows Server 2008 --> - <supportedOS Id="{e2011457-1546-43c5-a5fe-008deee3d3f0}"/> </application> </compatibility> diff --git a/src/chocolatey.resources/helpers/ChocolateyTabExpansion.ps1 b/src/chocolatey.resources/helpers/ChocolateyTabExpansion.ps1 index 8820ef33da..9aae203a27 100644 --- a/src/chocolatey.resources/helpers/ChocolateyTabExpansion.ps1 +++ b/src/chocolatey.resources/helpers/ChocolateyTabExpansion.ps1 @@ -26,7 +26,7 @@ $script:choco = "$env:ChocolateyInstall\choco.exe" function script:chocoCmdOperations($commands, $command, $filter, $currentArguments) { $currentOptions = @('zzzz') - if ($currentArguments -ne $null -and $currentArguments.Trim() -ne '') { + if (-not [string]::IsNullOrWhiteSpace($currentArguments)) { $currentOptions = $currentArguments.Trim() -split ' ' } @@ -35,56 +35,100 @@ function script:chocoCmdOperations($commands, $command, $filter, $currentArgumen Where-Object { $_ -like "$filter*" } } -$script:someCommands = @('-?', 'search', 'list', 'info', 'install', 'outdated', 'upgrade', 'uninstall', 'new', 'download', 'optimize', 'pack', 'push', 'sync', '-h', '--help', 'pin', 'source', 'config', 'feature', 'apikey', 'export', 'help', 'template', '--version') +$script:chocoCommands = @('-?','search','list','info','install','outdated','upgrade','uninstall','new','pack','push','-h','--help','pin','source','config','feature','apikey','export','help','template','--version') # ensure these all have a space to start, or they will cause issues -$allcommands = " --debug --verbose --trace --noop --help --accept-license --confirm --limit-output --no-progress --log-file='' --execution-timeout='' --cache-location='' --proxy='' --proxy-user='' --proxy-password='' --proxy-bypass-list='' --proxy-bypass-on-local --force --no-color --skip-compatibility-checks" -$proListOptions = " --audit --use-self-service" -$proSearchOptions = " --use-self-service" -$proInfoOptions = " --use-self-service" -$proInstallUpgradeOptions = " --install-directory='' --package-parameters-sensitive='' --max-download-rate='' --install-arguments-sensitive='' --skip-download-cache --use-download-cache --skip-virus-check --virus-check --virus-positives-minimum='' --deflate-package-size --no-deflate-package-size --deflate-nupkg-only --use-self-service" -$proUpgradeOptions = " --exclude-chocolatey-packages-during-upgrade-all --include-chocolatey-packages-during-upgrade-all --use-self-service" -$proNewOptions = " --file='' --build-package --file64='' --from-programs-and-features --use-original-location --keep-remote --url='' --url64='' --checksum='' --checksum64='' --checksumtype='' --pause-on-error --remove-architecture-from-name --include-architecture-in-name" -$proUninstallOptions = " --from-programs-and-features --use-self-service" -$proPinOptions = " --note='' --use-self-service" -$proOutdatedOptions = " --use-self-service" -$proPushOptions = " --use-self-service" +$allcommands = " --debug --verbose --trace --noop --help -? --online --accept-license --confirm --limit-output --no-progress --log-file='' --execution-timeout='' --cache-location='' --proxy='' --proxy-user='' --proxy-password='' --proxy-bypass-list='' --proxy-bypass-on-local --force --no-color --skip-compatibility-checks" $commandOptions = @{ - list = "--id-only --pre --exact --by-id-only --id-starts-with --detailed --prerelease --include-programs --page='' --page-size=''" + $proListOptions + $allcommands - search = "--pre --exact --by-id-only --id-starts-with --detailed --approved-only --not-broken --source='' --user='' --password='' --prerelease --page='' --page-size='' --order-by-popularity --download-cache-only --disable-package-repository-optimizations" + $proSearchOptions + $allcommands - info = "--pre --lo --source='' --user='' --password='' --local-only --prerelease --disable-package-repository-optimizations" + $proInfoOptions + $allcommands - install = "-y -whatif -? --pre --version= --params='' --install-arguments='' --override-arguments --ignore-dependencies --source='' --source='windowsfeatures' --user='' --password='' --prerelease --forcex86 --not-silent --package-parameters='' --exit-when-reboot-detected --ignore-detected-reboot --allow-downgrade --force-dependencies --require-checksums --use-package-exit-codes --ignore-package-exit-codes --skip-automation-scripts --ignore-checksums --allow-empty-checksums --allow-empty-checksums-secure --download-checksum='' --download-checksum-type='' --download-checksum-x64='' --download-checksum-type-x64='' --stop-on-first-package-failure --disable-package-repository-optimizations --pin" + $proInstallUpgradeOptions + $allcommands - pin = "--name='' --version='' -?" + $proPinOptions + $allcommands - outdated = "-? --source='' --user='' --password='' --ignore-pinned --ignore-unfound --pre --prerelease --disable-package-repository-optimizations" + $proOutdatedOptions + $allcommands - upgrade = "-y -whatif -? --pre --version='' --except='' --params='' --install-arguments='' --override-arguments --ignore-dependencies --source='' --source='windowsfeatures' --user='' --password='' --prerelease --forcex86 --not-silent --package-parameters='' --exit-when-reboot-detected --ignore-detected-reboot --allow-downgrade --require-checksums --use-package-exit-codes --ignore-package-exit-codes --skip-automation-scripts --fail-on-unfound --fail-on-not-installed --ignore-checksums --allow-empty-checksums --allow-empty-checksums-secure --download-checksum='' --download-checksum-type='' --download-checksum-x64='' --download-checksum-type-x64='' --exclude-prerelease --stop-on-first-package-failure --use-remembered-options --ignore-remembered-options --skip-when-not-installed --install-if-not-installed --disable-package-repository-optimizations --pin" + $proInstallUpgradeOptions + $proUpgradeOptions + $allcommands - uninstall = "-y -whatif -? --force-dependencies --remove-dependencies --all-versions --source='windowsfeatures' --version= --uninstall-arguments='' --override-arguments --not-silent --params='' --package-parameters='' --exit-when-reboot-detected --ignore-detected-reboot --use-package-exit-codes --ignore-package-exit-codes --skip-automation-scripts --use-autouninstaller --skip-autouninstaller --fail-on-autouninstaller --ignore-autouninstaller-failure --stop-on-first-package-failure" + $proUninstallOptions + $allcommands - new = "--template-name='' --output-directory='' --automaticpackage --version='' --maintainer='' packageversion='' maintainername='' maintainerrepo='' installertype='' url='' url64='' silentargs='' --use-built-in-template -?" + $proNewOptions + $allcommands - pack = "--version='' --output-directory='' -?" + $allcommands - push = "--source='' --api-key='' --timeout='' -?" + $proPushOptions + $allcommands - source = "--name='' --source='' --user='' --password='' --priority= --bypass-proxy --allow-self-service -?" + $allcommands - config = "--name='' --value='' -?" + $allcommands - feature = "--name='' -?" + $allcommands - apikey = "--source='' --api-key='' --remove -?" + $allcommands - download = "--internalize --internalize-all-urls --ignore-dependencies --installed-packages --ignore-unfound-packages --resources-location='' --download-location='' --outputdirectory='' --source='' --version='' --prerelease --user='' --password='' --cert='' --certpassword='' --append-use-original-location --recompile --disable-package-repository-optimizations -? --use-self-service" + $allcommands - sync = "--output-directory='' --id='' --package-id='' -? --use-self-service" + $allcommands - optimize = "--deflate-nupkg-only --id='' -? --use-self-service" + $allcommands - export = "--include-version-numbers --output-file-path='' -?" + $allcommands - template = "--name=''" + $allcommands + list = "--id-only --pre --exact --by-id-only --id-starts-with --detailed --prerelease --include-programs --source='' --page='' --page-size=''" + search = "--id-only --pre --exact --by-id-only --id-starts-with --detailed --approved-only --not-broken --source='' --user='' --password='' --prerelease --include-programs --page='' --page-size='' --order-by-popularity --download-cache-only --disable-package-repository-optimizations" + info = "--pre --source='' --user='' --password='' --prerelease --disable-package-repository-optimizations" + install = "-y -whatif --pre --version= --params='' --install-arguments='' --override-arguments --ignore-dependencies --source='' --source='windowsfeatures' --user='' --password='' --prerelease --forcex86 --not-silent --package-parameters='' --exit-when-reboot-detected --ignore-detected-reboot --allow-downgrade --force-dependencies --require-checksums --use-package-exit-codes --ignore-package-exit-codes --skip-automation-scripts --ignore-checksums --allow-empty-checksums --allow-empty-checksums-secure --download-checksum='' --download-checksum-type='' --download-checksum-x64='' --download-checksum-type-x64='' --stop-on-first-package-failure --disable-package-repository-optimizations --pin" + pin = "--name='' --version=''" + outdated = "--source='' --user='' --password='' --ignore-pinned --ignore-unfound --pre --prerelease --disable-package-repository-optimizations" + upgrade = "-y -whatif --pre --version='' --except='' --params='' --install-arguments='' --override-arguments --ignore-dependencies --source='' --source='windowsfeatures' --user='' --password='' --prerelease --forcex86 --not-silent --package-parameters='' --exit-when-reboot-detected --ignore-detected-reboot --allow-downgrade --require-checksums --use-package-exit-codes --ignore-package-exit-codes --skip-automation-scripts --fail-on-unfound --fail-on-not-installed --ignore-checksums --allow-empty-checksums --allow-empty-checksums-secure --download-checksum='' --download-checksum-type='' --download-checksum-x64='' --download-checksum-type-x64='' --exclude-prerelease --stop-on-first-package-failure --use-remembered-options --ignore-remembered-options --skip-when-not-installed --install-if-not-installed --disable-package-repository-optimizations --pin" + uninstall = "-y -whatif --force-dependencies --remove-dependencies --all-versions --source='windowsfeatures' --version= --uninstall-arguments='' --override-arguments --not-silent --params='' --package-parameters='' --exit-when-reboot-detected --ignore-detected-reboot --use-package-exit-codes --ignore-package-exit-codes --skip-automation-scripts --use-autouninstaller --skip-autouninstaller --fail-on-autouninstaller --ignore-autouninstaller-failure --stop-on-first-package-failure" + new = "--template-name='' --output-directory='' --automaticpackage --version='' --maintainer='' packageversion='' maintainername='' maintainerrepo='' installertype='' url='' url64='' silentargs='' --use-built-in-template" + pack = "--version='' --output-directory=''" + push = "--source='' --api-key='' --timeout=''" + source = "--name='' --source='' --user='' --password='' --priority= --bypass-proxy --allow-self-service" + config = "--name='' --value=''" + feature = "--name=''" + apikey = "--source='' --api-key='' --remove" + export = "--include-version-numbers --output-file-path=''" + template = "--name=''" } + $commandOptions['find'] = $commandOptions['search'] try { - # if license exists - # add in pro/biz switches + $licenseFile = Get-Item -Path "$env:ChocolateyInstall\license\chocolatey.license.xml" -ErrorAction Stop + + if ($licenseFile) { + # Add pro-only commands + $script:chocoCommands = @( + $script:chocoCommands + 'download' + 'optimize' + ) + + $commandOptions.download = "--internalize --internalize-all-urls --ignore-dependencies --installed-packages --ignore-unfound-packages --resources-location='' --download-location='' --outputdirectory='' --source='' --version='' --prerelease --user='' --password='' --cert='' --certpassword='' --append-use-original-location --recompile --disable-package-repository-optimizations" + $commandOptions.sync = "--output-directory='' --id='' --package-id=''" + $commandOptions.optimize = "--deflate-nupkg-only --id=''" + + # Add pro switches to commands that have additional switches on Pro + $proInstallUpgradeOptions = " --install-directory='' --package-parameters-sensitive='' --max-download-rate='' --install-arguments-sensitive='' --skip-download-cache --use-download-cache --skip-virus-check --virus-check --virus-positives-minimum='' --deflate-package-size --no-deflate-package-size --deflate-nupkg-only" + + $commandOptions.install += $proInstallUpgradeOptions + $commandOptions.upgrade += $proInstallUpgradeOptions + " --exclude-chocolatey-packages-during-upgrade-all --include-chocolatey-packages-during-upgrade-all" + $commandOptions.new += " --build-package --use-original-location --keep-remote --url='' --url64='' --checksum='' --checksum64='' --checksumtype='' --pause-on-error" + $commandOptions.pin += " --note=''" + + # Add Business-only commands and options if the license is a Business or Trial license + [xml]$xml = Get-Content -Path $licenseFile.FullName -ErrorAction Stop + $licenseType = $xml.license.type + + if ('Business', 'BusinessTrial' -contains $licenseType) { + + # Add business-only commands + $script:chocoCommands = @( + $script:chocoCommands + 'support' + 'sync' + ) + + $commandOptions.list += " --audit" + $commandOptions.uninstall += " --from-programs-and-features" + $commandOptions.new += " --file='' --file64='' --from-programs-and-features --remove-architecture-from-name --include-architecture-in-name" + + # Add --use-self-service to commands that support it + $selfServiceCommands = 'list', 'find', 'search', 'info', 'install', 'upgrade', 'uninstall', 'pin', 'outdated', 'push', 'download', 'sync', 'optimize' + foreach ($command in $selfServiceCommands) { + $commandOptions.$command += ' --use-self-service' + } + } + } } catch { + # Remove the error that last occurred from $error so it doesn't cause any + # issues for users, as we're deliberately ignoring it. + if ($error.Count -gt 0) { + $error.RemoveAt(0) + } +} + +foreach ($key in @($commandOptions.Keys)) { + $commandOptions.$key += $allcommands } +# Consistent ordering for commands so the added pro commands aren't weirdly out of order +$script:chocoCommands = $script:chocoCommands | Sort-Object -Property { $_ -replace '[^a-z](.*$)', '$1--' } + function script:chocoCommands($filter) { $cmdList = @() if (-not $global:ChocolateyTabSettings.AllCommands) { - $cmdList += $someCommands -like "$filter*" + $cmdList += $script:chocoCommands -like "$filter*" } else { $cmdList += (& $script:choco -h) | @@ -97,14 +141,14 @@ function script:chocoCommands($filter) { } function script:chocoLocalPackages($filter) { - if ($filter -ne $null -and $filter.StartsWith(".")) { + if ($filter -and $filter.StartsWith(".")) { return; } #file search @(& $script:choco list $filter -r --id-starts-with) | ForEach-Object { $_.Split('|')[0] } } function script:chocoLocalPackagesUpgrade($filter) { - if ($filter -ne $null -and $filter.StartsWith(".")) { + if ($filter -and $filter.StartsWith(".")) { return; } #file search @('all|') + @(& $script:choco list $filter -r --id-starts-with) | @@ -113,7 +157,7 @@ function script:chocoLocalPackagesUpgrade($filter) { } function script:chocoRemotePackages($filter) { - if ($filter -ne $null -and $filter.StartsWith(".")) { + if ($filter -and $filter.StartsWith(".")) { return; } #file search @('packages.config|') + @(& $script:choco search $filter --page='0' --page-size='30' -r --id-starts-with --order-by-popularity) | diff --git a/src/chocolatey.resources/helpers/chocolateyInstaller.psm1 b/src/chocolatey.resources/helpers/chocolateyInstaller.psm1 index 35f8de12d9..4b01918725 100644 --- a/src/chocolatey.resources/helpers/chocolateyInstaller.psm1 +++ b/src/chocolatey.resources/helpers/chocolateyInstaller.psm1 @@ -49,7 +49,6 @@ Get-Item -Path "$helpersPath\functions\*.ps1" | # Export built-in functions prior to loading extensions so that # extension-specific loading behavior can be used based on built-in # functions. This allows those overrides to be much more deterministic -# This behavior was broken from v0.9.9.5 - v0.10.3. Export-ModuleMember -Function * -Alias * -Cmdlet * $currentAssemblies = [System.AppDomain]::CurrentDomain.GetAssemblies() diff --git a/src/chocolatey.resources/helpers/chocolateyScriptRunner.ps1 b/src/chocolatey.resources/helpers/chocolateyScriptRunner.ps1 index 9b36bdcbe8..acf12ec874 100644 --- a/src/chocolatey.resources/helpers/chocolateyScriptRunner.ps1 +++ b/src/chocolatey.resources/helpers/chocolateyScriptRunner.ps1 @@ -51,7 +51,7 @@ $7zip = Join-Path $chocoTools '7z.exe' $ShimGen = Join-Path $chocoTools 'shimgen.exe' $checksumExe = Join-Path $chocoTools 'checksum.exe' -if ($PSBoundParameters.ContainsKey('preRunHookScripts')) { +if ($preRunHookScripts) { foreach ($prehookscript in $preRunHookScripts) { Write-Debug "Running Pre-Run Hook '$prehookscript'"; & "$prehookscript" @@ -86,7 +86,7 @@ if ($exitCode -ne $null -and $exitCode -ne '' -and $exitCode -ne 0) { Set-PowerShellExitCode $exitCode } -if ($PSBoundParameters.ContainsKey('postRunHookScripts')) { +if ($postRunHookScripts) { foreach ($posthookscript in $postRunHookScripts) { Write-Debug "Running Post-Run Hook '$posthookscript'"; & "$posthookscript" @@ -95,4 +95,4 @@ if ($PSBoundParameters.ContainsKey('postRunHookScripts')) { Write-Debug '----------------------------------------------------------------------' -Exit $exitCode \ No newline at end of file +Exit $exitCode diff --git a/src/chocolatey.resources/helpers/functions/Format-FileSize.ps1 b/src/chocolatey.resources/helpers/functions/Format-FileSize.ps1 index cf79134f29..a6a92abb2a 100644 --- a/src/chocolatey.resources/helpers/functions/Format-FileSize.ps1 +++ b/src/chocolatey.resources/helpers/functions/Format-FileSize.ps1 @@ -23,8 +23,6 @@ DO NOT USE. Not part of the public API. Formats file size into a human readable format. .NOTES -Available in 0.9.10+. - This function is not part of the API. .INPUTS diff --git a/src/chocolatey.resources/helpers/functions/Get-ChocolateyUnzip.ps1 b/src/chocolatey.resources/helpers/functions/Get-ChocolateyUnzip.ps1 index 3acaea9860..c95f30e3d7 100644 --- a/src/chocolatey.resources/helpers/functions/Get-ChocolateyUnzip.ps1 +++ b/src/chocolatey.resources/helpers/functions/Get-ChocolateyUnzip.ps1 @@ -23,8 +23,6 @@ Unzips an archive file and returns the location for further processing. This unzips files using the 7-zip command line tool 7z.exe. Supported archive formats are listed at: https://sevenzip.osdn.jp/chm/general/formats.htm -Prior to 0.9.10.1, 7za.exe was used. Supported archive formats for -7za.exe are: 7z, lzma, cab, zip, gzip, bzip2, and tar. .INPUTS None @@ -41,21 +39,21 @@ publicly (like on the community feed). Otherwise, please use Install-ChocolateyZipPackage to download those resources from their official distribution points. -Starting in 0.9.10, will automatically call Set-PowerShellExitCode to -set the package exit code based on 7-zip's exit code. +Will automatically call Set-PowerShellExitCode to set the package exit code +based on 7-zip's exit code. .PARAMETER FileFullPath This is the full path to the zip file. If embedding it in the package next to the install script, the path will be like `"$(Split-Path -Parent $MyInvocation.MyCommand.Definition)\\file.zip"` -In 0.10.1+, `File` is an alias for FileFullPath. +`File` is an alias for FileFullPath. This can be a 32-bit or 64-bit file. This is mandatory in earlier versions of Chocolatey, but optional if FileFullPath64 has been provided. .PARAMETER FileFullPath64 -Full file path to a 64-bit native installer to run. Available in 0.10.4+. +Full file path to a 64-bit native installer to run. If embedding in the package, you can get it to the path with `"$(Split-Path -parent $MyInvocation.MyCommand.Definition)\\INSTALLER_FILE"` diff --git a/src/chocolatey.resources/helpers/functions/Get-ChocolateyWebFile.ps1 b/src/chocolatey.resources/helpers/functions/Get-ChocolateyWebFile.ps1 index 212dd3566d..772761eae9 100644 --- a/src/chocolatey.resources/helpers/functions/Get-ChocolateyWebFile.ps1 +++ b/src/chocolatey.resources/helpers/functions/Get-ChocolateyWebFile.ps1 @@ -60,7 +60,7 @@ remove this parameter. Prefer HTTPS when available. Can be HTTP, FTP, or File URIs. -In 0.10.1+, `Url64` is an alias for Url64bit. +`Url64` is an alias for Url64bit. .PARAMETER Checksum The checksum hash value of the Url resource. This allows a checksum to @@ -124,18 +124,16 @@ https://support.microsoft.com/en-us/kb/811833 for more details. The recommendation is to use at least SHA256. .PARAMETER Options -OPTIONAL - Specify custom headers. Available in 0.9.10+. +OPTIONAL - Specify custom headers. .PARAMETER GetOriginalFileName OPTIONAL switch to allow Chocolatey to determine the original file name -from the url resource. Available in 0.9.10+. +from the url resource. .PARAMETER ForceDownload OPTIONAL switch to force download of file every time, even if the file already exists. -Available in 0.10.1+. - .PARAMETER IgnoredArguments Allows splatting with arguments that do not apply. Do not use directly. diff --git a/src/chocolatey.resources/helpers/functions/Get-EnvironmentVariable.ps1 b/src/chocolatey.resources/helpers/functions/Get-EnvironmentVariable.ps1 index 38ea6750a1..d5c49324c0 100644 --- a/src/chocolatey.resources/helpers/functions/Get-EnvironmentVariable.ps1 +++ b/src/chocolatey.resources/helpers/functions/Get-EnvironmentVariable.ps1 @@ -38,7 +38,7 @@ The environment variable target scope. This is `Process`, `User`, or .PARAMETER PreserveVariables A switch parameter stating whether you want to expand the variables or -not. Defaults to false. Available in 0.9.10+. +not. Defaults to false. .PARAMETER IgnoredArguments Allows splatting with arguments that do not apply. Do not use directly. diff --git a/src/chocolatey.resources/helpers/functions/Get-FtpFile.ps1 b/src/chocolatey.resources/helpers/functions/Get-FtpFile.ps1 index a48d632778..3d2e38a727 100644 --- a/src/chocolatey.resources/helpers/functions/Get-FtpFile.ps1 +++ b/src/chocolatey.resources/helpers/functions/Get-FtpFile.ps1 @@ -26,8 +26,8 @@ FileName location specified. This is a low-level function and not recommended for use in package scripts. It is recommended you call `Get-ChocolateyWebFile` instead. -Starting in 0.9.10, will automatically call Set-PowerShellExitCode to -set the package exit code to 404 if the resource is not found. +Will automatically call Set-PowerShellExitCode to set the package +exit code to 404 if the resource is not found. .INPUTS None diff --git a/src/chocolatey.resources/helpers/functions/Get-OSArchitectureWidth.ps1 b/src/chocolatey.resources/helpers/functions/Get-OSArchitectureWidth.ps1 index 1f7097c2a1..37d41b83c9 100644 --- a/src/chocolatey.resources/helpers/functions/Get-OSArchitectureWidth.ps1 +++ b/src/chocolatey.resources/helpers/functions/Get-OSArchitectureWidth.ps1 @@ -28,10 +28,7 @@ of {`32`|`64`}. When your installation script has to know what architecture it is run on, this simple function comes in handy. -Available as `Get-OSArchitectureWidth` in 0.9.10+. If you need -compatibility with pre 0.9.10, please use the alias `Get-ProcessorBits`. - -As of 0.10.14+, ARM64 architecture will automatically select 32bit width as +ARM64 architecture will automatically select 32bit width as there is an emulator for 32 bit and there are no current plans by Microsoft to ship 64 bit x86 emulation for ARM64. For more details, see https://github.com/chocolatey/choco/issues/1800#issuecomment-484293844. diff --git a/src/chocolatey.resources/helpers/functions/Get-PackageParameters.ps1 b/src/chocolatey.resources/helpers/functions/Get-PackageParameters.ps1 index 29bcf11804..2901a98ee9 100644 --- a/src/chocolatey.resources/helpers/functions/Get-PackageParameters.ps1 +++ b/src/chocolatey.resources/helpers/functions/Get-PackageParameters.ps1 @@ -37,7 +37,7 @@ editions). Learn more about using this at https://docs.chocolatey.org/en-us/guides/create/parse-packageparameters-argument .NOTES -Available in 0.10.8+. If you need compatibility with older versions, +If you need compatibility with older versions of Chocolatey, take a dependency on the `chocolatey-core.extension` package which also provides this functionality. If you are pushing to the community package repository (https://community.chocolatey.org/packages), you are required @@ -67,8 +67,8 @@ compatibility with `chocolatey-core.extension`, use `:`. For example `-Parameters "/ITEM1:value /ITEM2:value with spaces" -NOTE: In 0.10.9+, to maintain compatibility with the prior art of the -chocolatey-core.extension method, quotes and apostrophes surrounding +To maintain compatibility with the prior art of the chocolatey-core.extension +function by the same name, quotes and apostrophes surrounding parameter values will be removed. When the param is used, those items can be added back if desired, but it's most important to ensure that existing packages are compatible on upgrade. @@ -101,7 +101,6 @@ if (!$pp['LICENSE']) { $pp['LICENSE'] = '1234' } > $pp = Get-PackageParameters if (!$pp['UserName']) { $pp['UserName'] = "$env:UserName" } -# Requires Chocolatey v0.10.8+ for Read-Host -AsSecureString if (!$pp['Password']) { $pp['Password'] = Read-Host "Enter password for $($pp['UserName']):" -AsSecureString} # fail the install/upgrade if not value is not determined if (!$pp['Password']) { throw "Package needs Password to install, that must be provided in params or in prompt." } diff --git a/src/chocolatey.resources/helpers/functions/Get-UninstallRegistryKey.ps1 b/src/chocolatey.resources/helpers/functions/Get-UninstallRegistryKey.ps1 index f48accff39..2b78392d2e 100644 --- a/src/chocolatey.resources/helpers/functions/Get-UninstallRegistryKey.ps1 +++ b/src/chocolatey.resources/helpers/functions/Get-UninstallRegistryKey.ps1 @@ -28,17 +28,6 @@ chocolateyUninstall.ps1 automation script. The function also prevents `Get-ItemProperty` from failing when handling wrongly encoded registry keys. -.NOTES -Available in 0.9.10+. If you need to maintain compatibility with pre -0.9.10, please add the following to your nuspec (check for minimum -version): - -~~~xml -<dependencies> - <dependency id="chocolatey-core.extension" version="1.1.0" /> -</dependencies> -~~~ - .INPUTS String diff --git a/src/chocolatey.resources/helpers/functions/Get-VirusCheckValid.ps1 b/src/chocolatey.resources/helpers/functions/Get-VirusCheckValid.ps1 index 753e786864..f8291d6f0a 100644 --- a/src/chocolatey.resources/helpers/functions/Get-VirusCheckValid.ps1 +++ b/src/chocolatey.resources/helpers/functions/Get-VirusCheckValid.ps1 @@ -22,7 +22,7 @@ resources. .DESCRIPTION Run a runtime malware check against downloaded resources prior to -allowing Chocolatey to execute a file. This is available in 0.9.10+ only +allowing Chocolatey to execute a file. This is only available in Pro / Business editions. .NOTES diff --git a/src/chocolatey.resources/helpers/functions/Get-WebFile.ps1 b/src/chocolatey.resources/helpers/functions/Get-WebFile.ps1 index df56a7c97d..774a2ede0f 100644 --- a/src/chocolatey.resources/helpers/functions/Get-WebFile.ps1 +++ b/src/chocolatey.resources/helpers/functions/Get-WebFile.ps1 @@ -36,8 +36,8 @@ to the FileName location specified. This is a low-level function and not recommended for use in package scripts. It is recommended you call `Get-ChocolateyWebFile` instead. -Starting in 0.9.10, will automatically call Set-PowerShellExitCode to -set the package exit code to 404 if the resource is not found. +Will automatically call Set-PowerShellExitCode to set the package exit +code to 404 if the resource is not found. .INPUTS None @@ -64,7 +64,7 @@ DO NOT USE - holdover from original function. Silences the progress output. .PARAMETER Options -OPTIONAL - Specify custom headers. Available in 0.9.10+. +OPTIONAL - Specify custom headers. .PARAMETER IgnoredArguments Allows splatting with arguments that do not apply. Do not use directly. diff --git a/src/chocolatey.resources/helpers/functions/Get-WebFileName.ps1 b/src/chocolatey.resources/helpers/functions/Get-WebFileName.ps1 index b2c3de28db..e186e401dc 100644 --- a/src/chocolatey.resources/helpers/functions/Get-WebFileName.ps1 +++ b/src/chocolatey.resources/helpers/functions/Get-WebFileName.ps1 @@ -26,7 +26,6 @@ Uses several techniques to determine the original file name of the file based on the url for the file. .NOTES -Available in 0.9.10+. Falls back to DefaultName when the name cannot be determined. Chocolatey works best when the packages contain the software it is diff --git a/src/chocolatey.resources/helpers/functions/Install-ChocolateyInstallPackage.ps1 b/src/chocolatey.resources/helpers/functions/Install-ChocolateyInstallPackage.ps1 index 7376cac3b8..5945aa924f 100644 --- a/src/chocolatey.resources/helpers/functions/Install-ChocolateyInstallPackage.ps1 +++ b/src/chocolatey.resources/helpers/functions/Install-ChocolateyInstallPackage.ps1 @@ -77,14 +77,13 @@ for the package to be completely unattended. When you are using this with an MSI, it will set up the arguments as follows: `"C:\Full\Path\To\msiexec.exe" /i "$fileFullPath" $silentArgs`, where `$fileFullPath` is `$file` or `$file64`, depending on what has been -decided to be used. Previous to 0.10.4, it will be just `$file` as -passing `$file64` would not have been available yet. +decided to be used. When you use this with MSU, it is similar to MSI above in that it finds the right executable to run. When you use this with executable installers, the `$fileFullPath` will -be `$file` (or `$file64` starting with 0.10.4+) and expects to be a full +be `$file` or `$file64` and expects to be a full path to the file. If the file is in the package, see the parameters for "File" and "File64" to determine how you can get that path at runtime in a deterministic way. SilentArgs is everything you call against that @@ -97,13 +96,13 @@ Full file path to native installer to run. If embedding in the package, you can get it to the path with `"$(Split-Path -parent $MyInvocation.MyCommand.Definition)\\INSTALLER_FILE"` -In 0.10.1+, `FileFullPath` is an alias for File. +`FileFullPath` is an alias for File. This can be a 32-bit or 64-bit file. This is mandatory in earlier versions of Chocolatey, but optional if File64 has been provided. .PARAMETER File64 -Full file path to a 64-bit native installer to run. Available in 0.10.4+. +Full file path to a 64-bit native installer to run. If embedding in the package, you can get it to the path with `"$(Split-Path -parent $MyInvocation.MyCommand.Definition)\\INSTALLER_FILE"` @@ -116,7 +115,7 @@ Array of exit codes indicating success. Defaults to `@(0)`. .PARAMETER UseOnlyPackageSilentArguments Do not allow choco to provide/merge additional silent arguments and -only use the ones available with the package. Available in 0.9.10+. +only use the ones available with the package. .PARAMETER IgnoredArguments Allows splatting with arguments that do not apply. Do not use directly. diff --git a/src/chocolatey.resources/helpers/functions/Install-ChocolateyPackage.ps1 b/src/chocolatey.resources/helpers/functions/Install-ChocolateyPackage.ps1 index 8e03bb999c..5883432193 100644 --- a/src/chocolatey.resources/helpers/functions/Install-ChocolateyPackage.ps1 +++ b/src/chocolatey.resources/helpers/functions/Install-ChocolateyPackage.ps1 @@ -191,28 +191,28 @@ https://support.microsoft.com/en-us/kb/811833 for more details. The recommendation is to use at least SHA256. .PARAMETER Options -OPTIONAL - Specify custom headers. Available in 0.9.10+. +OPTIONAL - Specify custom headers. .PARAMETER File -Will be used for Url if Url is empty. Available in 0.10.7+. +Will be used for Url if Url is empty. This parameter provides compatibility, but should not be used directly and not with the community package repository until January 2018. .PARAMETER File64 -Will be used for Url64bit if Url64bit is empty. Available in 0.10.7+. +Will be used for Url64bit if Url64bit is empty. This parameter provides compatibility, but should not be used directly and not with the community package repository until January 2018. .PARAMETER UseOnlyPackageSilentArguments Do not allow choco to provide/merge additional silent arguments and only -use the ones available with the package. Available in 0.9.10+. +use the ones available with the package. .PARAMETER UseOriginalLocation Do not download the resources. This is typically passed if Url/Url64bit are pointed to local files or files on a share and those files should -be used in place. Available in 0.10.1+. +be used in place. NOTE: You can also use `Install-ChocolateyInstallPackage` for the same functionality (see links). @@ -222,7 +222,6 @@ Allows splatting with arguments that do not apply. Do not use directly. .PARAMETER BeforeInstall Script Specifies the commands to run after download has completed but before install steps have begun. -Available in 0.11.0+. Use this for starting an auxiliary process such as AutoHotkey, so that any timeouts are not affected by the time to download. diff --git a/src/chocolatey.resources/helpers/functions/Install-ChocolateyPowershellCommand.ps1 b/src/chocolatey.resources/helpers/functions/Install-ChocolateyPowershellCommand.ps1 index eda1092614..dba7607c0b 100644 --- a/src/chocolatey.resources/helpers/functions/Install-ChocolateyPowershellCommand.ps1 +++ b/src/chocolatey.resources/helpers/functions/Install-ChocolateyPowershellCommand.ps1 @@ -49,7 +49,7 @@ Full file path to PowerShell file to turn into a command. If embedding it in the package next to the install script, the path will be like `"$(Split-Path -parent $MyInvocation.MyCommand.Definition)\\Script.ps1"` -In 0.10.6+, `File` and `FileFullPath` are aliases for PsFileFullPath. +`File` and `FileFullPath` are aliases for PsFileFullPath. .PARAMETER Url This is the 32 bit url to download the resource from. This resource can @@ -134,7 +134,7 @@ https://support.microsoft.com/en-us/kb/811833 for more details. The recommendation is to use at least SHA256. .PARAMETER Options -OPTIONAL - Specify custom headers. Available in 0.9.10+. +OPTIONAL - Specify custom headers. .PARAMETER IgnoredArguments Allows splatting with arguments that do not apply. Do not use directly. diff --git a/src/chocolatey.resources/helpers/functions/Install-ChocolateyShortcut.ps1 b/src/chocolatey.resources/helpers/functions/Install-ChocolateyShortcut.ps1 index f45a587471..a299a69b42 100644 --- a/src/chocolatey.resources/helpers/functions/Install-ChocolateyShortcut.ps1 +++ b/src/chocolatey.resources/helpers/functions/Install-ChocolateyShortcut.ps1 @@ -45,8 +45,8 @@ The full absolute path to the target for new shortcut. OPTIONAL - The full absolute path of the Working Directory that will be used by the new shortcut. -As of v0.10.12, the directory will be created unless it contains environment -variable expansion like `%AppData%\FooBar`. +The directory will be created unless it contains environment variable +expansion like `%AppData%\FooBar`. .PARAMETER Arguments OPTIONAL - Additional arguments that should be passed along to the new @@ -61,16 +61,17 @@ OPTIONAL - A text description to be associated with the new description. .PARAMETER WindowStyle OPTIONAL - Type of windows target application should open with. -Available in 0.9.10+. + 0 = Hidden, 1 = Normal Size, 3 = Maximized, 7 - Minimized. + Full list table 3.9 here: https://technet.microsoft.com/en-us/library/ee156605.aspx .PARAMETER RunAsAdmin OPTIONAL - Set "Run As Administrator" checkbox for the created the -shortcut. Available in 0.9.10+. +shortcut. .PARAMETER PinToTaskbar -OPTIONAL - Pin the new shortcut to the taskbar. Available in 0.9.10+. +OPTIONAL - Pin the new shortcut to the taskbar. .PARAMETER IgnoredArguments Allows splatting with arguments that do not apply. Do not use directly. @@ -101,7 +102,6 @@ Install-ChocolateyShortcut ` > # Creates a new notepad shortcut on the root of c: that starts # notepad.exe as Administrator. Shortcut is also pinned to taskbar. -# These parameters are available in 0.9.10+. Install-ChocolateyShortcut ` -ShortcutFilePath "C:\notepad.lnk" ` diff --git a/src/chocolatey.resources/helpers/functions/Install-ChocolateyVsixPackage.ps1 b/src/chocolatey.resources/helpers/functions/Install-ChocolateyVsixPackage.ps1 index 2cec0b99c8..1048c72b56 100644 --- a/src/chocolatey.resources/helpers/functions/Install-ChocolateyVsixPackage.ps1 +++ b/src/chocolatey.resources/helpers/functions/Install-ChocolateyVsixPackage.ps1 @@ -45,14 +45,14 @@ None The name of the package - while this is an arbitrary value, it's recommended that it matches the package id. -In 0.10.4+, `Name` is an alias for PackageName. +`Name` is an alias for PackageName. .PARAMETER VsixUrl The URL of the package to be installed. Prefer HTTPS when available. Can be HTTP, FTP, or File URIs. -In 0.10.4+, `Url` is an alias for VsixUrl. +`Url` is an alias for VsixUrl. .PARAMETER VsVersion The major version number of Visual Studio where the @@ -63,7 +63,7 @@ will be targeted. NOTE: For Visual Studio 2015, the VsVersion is 14. It can be determined by looking at the folders under Program Files / Program Files (x86). -In 0.10.4+, `VisualStudioVersion` is an alias for VsVersion. +`VisualStudioVersion` is an alias for VsVersion. .PARAMETER Checksum The checksum hash value of the Url resource. This allows a checksum to @@ -99,10 +99,10 @@ https://support.microsoft.com/en-us/kb/811833 for more details. The recommendation is to use at least SHA256. .PARAMETER Options -OPTIONAL - Specify custom headers. Available in 0.9.10+. +OPTIONAL - Specify custom headers. .PARAMETER File -Will be used for VsixUrl if VsixUrl is empty. Available in 0.10.7+. +Will be used for VsixUrl if VsixUrl is empty. This parameter provides compatibility, but should not be used directly and not with the community package repository until January 2018. diff --git a/src/chocolatey.resources/helpers/functions/Install-ChocolateyZipPackage.ps1 b/src/chocolatey.resources/helpers/functions/Install-ChocolateyZipPackage.ps1 index e49837b4e7..1d956418dd 100644 --- a/src/chocolatey.resources/helpers/functions/Install-ChocolateyZipPackage.ps1 +++ b/src/chocolatey.resources/helpers/functions/Install-ChocolateyZipPackage.ps1 @@ -137,16 +137,16 @@ https://support.microsoft.com/en-us/kb/811833 for more details. The recommendation is to use at least SHA256. .PARAMETER Options -OPTIONAL - Specify custom headers. Available in 0.9.10+. +OPTIONAL - Specify custom headers. .PARAMETER File -Will be used for Url if Url is empty. Available in 0.10.7+. +Will be used for Url if Url is empty. This parameter provides compatibility, but should not be used directly and not with the community package repository until January 2018. .PARAMETER File64 -Will be used for Url64bit if Url64bit is empty. Available in 0.10.7+. +Will be used for Url64bit if Url64bit is empty. This parameter provides compatibility, but should not be used directly and not with the community package repository until January 2018. diff --git a/src/chocolatey.resources/helpers/functions/Start-ChocolateyProcessAsAdmin.ps1 b/src/chocolatey.resources/helpers/functions/Start-ChocolateyProcessAsAdmin.ps1 index a05a69ba49..4ca8dec71b 100644 --- a/src/chocolatey.resources/helpers/functions/Start-ChocolateyProcessAsAdmin.ps1 +++ b/src/chocolatey.resources/helpers/functions/Start-ChocolateyProcessAsAdmin.ps1 @@ -25,14 +25,13 @@ specified, it is run with PowerShell. .NOTES This command will assert UAC/Admin privileges on the machine. -Starting in 0.9.10, will automatically call Set-PowerShellExitCode to -set the package exit code in the following ways: +Will automatically call Set-PowerShellExitCode to set the package exit +code in the following ways: - 4 if the binary turns out to be a text file. - The same exit code returned from the process that is run. If a 3010 is returned, it will set 3010 for the package. -Aliases `Start-ChocolateyProcess` and `Invoke-ChocolateyProcess` -available in 0.10.2+. +Aliases `Start-ChocolateyProcess` and `Invoke-ChocolateyProcess`. .INPUTS None @@ -50,8 +49,6 @@ The executable/application/installer to run. Defaults to `'powershell'`. .PARAMETER Elevated Indicate whether the process should run elevated. -Available in 0.10.2+. - .PARAMETER Minimized Switch indicating if a Windows pops up (if not called with a silent argument) that it should be minimized. @@ -66,9 +63,7 @@ Array of exit codes indicating success. Defaults to `@(0)`. .PARAMETER WorkingDirectory The working directory for the running process. Defaults to `Get-Location`. If current location is a UNC path, uses -`$env:TEMP` for default as of 0.10.14. - -Available in 0.10.1+. +`$env:TEMP` for default. .PARAMETER SensitiveStatements Arguments to pass to `ExeToRun` that are not logged. @@ -77,8 +72,6 @@ Note that only licensed versions of Chocolatey provide a way to pass those values completely through without having them in the install script or on the system in some way. -Available in 0.10.1+. - .PARAMETER IgnoredArguments Allows splatting with arguments that do not apply. Do not use directly. diff --git a/src/chocolatey.resources/helpers/functions/Uninstall-ChocolateyEnvironmentVariable.ps1 b/src/chocolatey.resources/helpers/functions/Uninstall-ChocolateyEnvironmentVariable.ps1 index da05f114fa..f7071de5be 100644 --- a/src/chocolatey.resources/helpers/functions/Uninstall-ChocolateyEnvironmentVariable.ps1 +++ b/src/chocolatey.resources/helpers/functions/Uninstall-ChocolateyEnvironmentVariable.ps1 @@ -28,9 +28,6 @@ the User or to the Machine. If Machine level scoping is specified, the command is elevated to an administrative session. .NOTES -Available in 0.9.10+. If you need compatibility with older versions, -use Install-ChocolateyEnvironmentVariable and set `-VariableValue $null` - This command will assert UAC/Admin privileges on the machine when `-VariableType Machine`. diff --git a/src/chocolatey.resources/helpers/functions/Uninstall-ChocolateyPackage.ps1 b/src/chocolatey.resources/helpers/functions/Uninstall-ChocolateyPackage.ps1 index 91868cd957..44f8172e86 100644 --- a/src/chocolatey.resources/helpers/functions/Uninstall-ChocolateyPackage.ps1 +++ b/src/chocolatey.resources/helpers/functions/Uninstall-ChocolateyPackage.ps1 @@ -23,7 +23,7 @@ Uninstalls software from "Programs and Features". This will uninstall software from your machine (in Programs and Features). This may not be necessary if Auto Uninstaller is turned on. -Choco 0.9.9+ automatically tracks registry changes for "Programs and +Chocolatey CLI automatically tracks registry changes for "Programs and Features" of the underlying software's native installers when installing packages. The "Automatic Uninstaller" (auto uninstaller) service is a feature that can use that information to automatically @@ -38,8 +38,8 @@ Chocolatey but does not remove the software from your system without auto uninstaller. .NOTES -May not be required. Starting in 0.9.10+, the Automatic Uninstaller -(AutoUninstaller) is turned on by default. +May not be required. The Automatic Uninstaller (AutoUninstaller) is +turned on by default. .INPUTS None @@ -54,8 +54,7 @@ recommended that it matches the package id. .PARAMETER FileType This is the extension of the file. This should be either exe or msi. -If what is provided is empty or null, Chocolatey will use 'exe' -starting in 0.10.1. +If what is provided is empty or null, Chocolatey will use 'exe'. .PARAMETER SilentArgs OPTIONAL - These are the parameters to pass to the native uninstaller, diff --git a/src/chocolatey.resources/helpers/functions/Update-SessionEnvironment.ps1 b/src/chocolatey.resources/helpers/functions/Update-SessionEnvironment.ps1 index 964406dc45..725b22bd0f 100644 --- a/src/chocolatey.resources/helpers/functions/Update-SessionEnvironment.ps1 +++ b/src/chocolatey.resources/helpers/functions/Update-SessionEnvironment.ps1 @@ -38,7 +38,7 @@ This method is also added to the user's PowerShell profile as `refreshenv`. When called as `refreshenv`, the method will provide additional output. -Preserves `PSModulePath` as set by the process starting in 0.9.10. +Preserves `PSModulePath` as set by the process. .INPUTS None diff --git a/src/chocolatey.resources/helpers/functions/Write-FunctionCallLogMessage.ps1 b/src/chocolatey.resources/helpers/functions/Write-FunctionCallLogMessage.ps1 index 2cb2800344..d5eb6638fa 100644 --- a/src/chocolatey.resources/helpers/functions/Write-FunctionCallLogMessage.ps1 +++ b/src/chocolatey.resources/helpers/functions/Write-FunctionCallLogMessage.ps1 @@ -23,8 +23,6 @@ DO NOT USE. Not part of the public API. Writes function call as a debug message. .NOTES -Available in 0.10.2+. - This function is not part of the API. .INPUTS diff --git a/src/chocolatey.sln.DotSettings b/src/chocolatey.sln.DotSettings index 0938a31d3f..cf657df444 100644 --- a/src/chocolatey.sln.DotSettings +++ b/src/chocolatey.sln.DotSettings @@ -1,19 +1,4 @@ <wpf:ResourceDictionary xml:space="preserve" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:s="clr-namespace:System;assembly=mscorlib" xmlns:ss="urn:shemas-jetbrains-com:settings-storage-xaml" xmlns:wpf="http://schemas.microsoft.com/winfx/2006/xaml/presentation"> - <s:Boolean x:Key="/Default/CodeEditing/Intellisense/CodeCompletion/IntelliSenseCompletingCharacters/IntelliSenseCompletingCharactersSettingCSharp/UpgradedFromVSSettings/@EntryValue">True</s:Boolean> - <s:String x:Key="/Default/CodeInspection/ExcludedFiles/GeneratedFilesAndFolders/=5563DC61_002D35FD_002D4FAB_002DB331_002D9AE1FDB23F80_002Fd_003Ainfrastructure_002Fd_003Acommandline_002Ff_003AOptions_002Ecs/@EntryIndexedValue">5563DC61-35FD-4FAB-B331-9AE1FDB23F80/d:infrastructure/d:commandline/f:Options.cs</s:String> - <s:String x:Key="/Default/CodeInspection/ExcludedFiles/GeneratedFilesAndFolders/=5C4C60F0_002D47B1_002D498E_002DABF7_002DD315E1A94BC9_002Ff_003ATinySpec_002Ecs/@EntryIndexedValue">5C4C60F0-47B1-498E-ABF7-D315E1A94BC9/f:TinySpec.cs</s:String> - <s:String x:Key="/Default/CodeInspection/GeneratedCode/GeneratedFileMasks/=SolutionVersion_002Ecs/@EntryIndexedValue">SolutionVersion.cs</s:String> - <s:String x:Key="/Default/CodeStyle/CodeCleanup/Profiles/=header_005Fupdates/@EntryIndexedValue"><?xml version="1.0" encoding="utf-16"?><Profile name="header_updates"><CSUpdateFileHeader>True</CSUpdateFileHeader><CSCodeStyleAttributes ArrangeTypeAccessModifier="False" ArrangeTypeMemberAccessModifier="False" SortModifiers="False" RemoveRedundantParentheses="False" AddMissingParentheses="False" ArrangeBraces="False" ArrangeAttributes="False" ArrangeArgumentsStyle="False" ArrangeCodeBodyStyle="False" /><CSOptimizeUsings><OptimizeUsings>False</OptimizeUsings><EmbraceInRegion>False</EmbraceInRegion><RegionName></RegionName></CSOptimizeUsings><XAMLCollapseEmptyTags>False</XAMLCollapseEmptyTags></Profile></s:String> - <s:String x:Key="/Default/CodeStyle/CodeCleanup/Profiles/=sensible/@EntryIndexedValue"><?xml version="1.0" encoding="utf-16"?><Profile name="sensible"><CSArrangeThisQualifier>True</CSArrangeThisQualifier><CSMakeFieldReadonly>True</CSMakeFieldReadonly><CSOptimizeUsings><OptimizeUsings>True</OptimizeUsings><EmbraceInRegion>False</EmbraceInRegion><RegionName></RegionName></CSOptimizeUsings><CSShortenReferences>True</CSShortenReferences><CSReformatCode>True</CSReformatCode><CSRemoveCodeRedundancies>True</CSRemoveCodeRedundancies><CSUseAutoProperty>True</CSUseAutoProperty><CSUseVar><BehavourStyle>CAN_CHANGE_TO_IMPLICIT</BehavourStyle><LocalVariableStyle>IMPLICIT_WHEN_INITIALIZER_HAS_TYPE</LocalVariableStyle><ForeachVariableStyle>ALWAYS_EXPLICIT</ForeachVariableStyle></CSUseVar><CSharpFormatDocComments>True</CSharpFormatDocComments><CSUpdateFileHeader>True</CSUpdateFileHeader></Profile></s:String> - <s:String x:Key="/Default/CodeStyle/CodeCleanup/SilentCleanupProfile/@EntryValue">sensible</s:String> - <s:Boolean x:Key="/Default/CodeStyle/CodeFormatting/CommonFormatter/USE_INDENTS_FROM_MAIN_LANGUAGE_IN_FILE/@EntryValue">False</s:Boolean> - <s:String x:Key="/Default/CodeStyle/CodeFormatting/CSharpFormat/FORCE_IFELSE_BRACES_STYLE/@EntryValue">DO_NOT_CHANGE</s:String> - <s:Boolean x:Key="/Default/CodeStyle/CodeFormatting/CSharpFormat/PLACE_CATCH_ON_NEW_LINE/@EntryValue">True</s:Boolean> - <s:Boolean x:Key="/Default/CodeStyle/CodeFormatting/CSharpFormat/PLACE_ELSE_ON_NEW_LINE/@EntryValue">True</s:Boolean> - <s:Boolean x:Key="/Default/CodeStyle/CodeFormatting/CSharpFormat/PLACE_FINALLY_ON_NEW_LINE/@EntryValue">True</s:Boolean> - <s:Int64 x:Key="/Default/CodeStyle/CodeFormatting/CSharpFormat/WRAP_LIMIT/@EntryValue">220</s:Int64> - <s:Boolean x:Key="/Default/CodeStyle/CodeFormatting/CSharpFormat/WRAP_LINES/@EntryValue">False</s:Boolean> - <s:Boolean x:Key="/Default/CodeStyle/CSharpUsing/AddImportsToDeepestScope/@EntryValue">True</s:Boolean> <s:String x:Key="/Default/CodeStyle/FileHeader/FileHeaderText/@EntryValue">Copyright © 2017 - $CURRENT_YEAR$ Chocolatey Software, Inc Copyright © 2011 - 2017 RealDimensions Software, LLC @@ -30,21 +15,4 @@ 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. </s:String> - <s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/PredefinedNamingRules/=Constants/@EntryIndexedValue"><Policy Inspect="True" Prefix="" Suffix="" Style="AA_BB" /></s:String> - <s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/PredefinedNamingRules/=EnumMember/@EntryIndexedValue"><Policy Inspect="True" Prefix="" Suffix="" Style="AaBb"><ExtraRule Prefix="" Suffix="" Style="aaBb_AaBb" /></Policy></s:String> - <s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/PredefinedNamingRules/=LocalConstants/@EntryIndexedValue"><Policy Inspect="True" Prefix="" Suffix="" Style="aaBb" /></s:String> - <s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/PredefinedNamingRules/=MethodPropertyEvent/@EntryIndexedValue"><Policy Inspect="True" Prefix="" Suffix="" Style="aa_bb"><ExtraRule Prefix="" Suffix="" Style="AaBb" /></Policy></s:String> - <s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/PredefinedNamingRules/=PrivateConstants/@EntryIndexedValue"><Policy Inspect="True" Prefix="" Suffix="" Style="AA_BB" /></s:String> - <s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/PredefinedNamingRules/=PrivateStaticReadonly/@EntryIndexedValue"><Policy Inspect="True" Prefix="_" Suffix="" Style="aaBb" /></s:String> - <s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/PredefinedNamingRules/=TypeParameters/@EntryIndexedValue"><Policy Inspect="True" Prefix="" Suffix="" Style="AaBb" /></s:String> - <s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/PredefinedNamingRules/=TypesAndNamespaces/@EntryIndexedValue"><Policy Inspect="True" Prefix="" Suffix="" Style="AaBb"><ExtraRule Prefix="I" Suffix="" Style="AaBb" /><ExtraRule Prefix="when_" Suffix="" Style="aaBb_aaBb" /><ExtraRule Prefix="when_" Suffix="" Style="AaBb_aaBb" /><ExtraRule Prefix="when_" Suffix="" Style="aaBb_AaBb" /></Policy></s:String> - <s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/UserRules/=474957be_002Df1f1_002D44f8_002Da1ba_002D6fbd8a61587b/@EntryIndexedValue"><Policy><Descriptor Staticness="Static, Instance" AccessRightKinds="Public" Description="Properties"><ElementKinds><Kind Name="PROPERTY" /></ElementKinds></Descriptor><Policy Inspect="True" Prefix="" Suffix="" Style="AaBb" /></Policy></s:String> - <s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/UserRules/=b229e86b_002D47e7_002D493e_002D9c0f_002D2b53080cdad9/@EntryIndexedValue"><Policy><Descriptor Staticness="Static, Instance" AccessRightKinds="Private, Protected, ProtectedInternal, Internal, Public" Description="Methods, Events"><ElementKinds><Kind Name="METHOD" /><Kind Name="EVENT" /></ElementKinds></Descriptor><Policy Inspect="True" Prefix="" Suffix="" Style="aa_bb" /></Policy></s:String> - <s:String x:Key="/Default/Environment/Hierarchy/PsiConfigurationSettingsKey/LocationType/@EntryValue">SOLUTION_FOLDER</s:String> - <s:Boolean x:Key="/Default/Environment/SettingsMigration/IsMigratorApplied/=JetBrains_002EReSharper_002EPsi_002ECSharp_002ECodeStyle_002ECSharpKeepExistingMigration/@EntryIndexedValue">True</s:Boolean> - <s:Boolean x:Key="/Default/Environment/SettingsMigration/IsMigratorApplied/=JetBrains_002EReSharper_002EPsi_002ECSharp_002ECodeStyle_002ECSharpPlaceEmbeddedOnSameLineMigration/@EntryIndexedValue">True</s:Boolean> - <s:Boolean x:Key="/Default/Environment/SettingsMigration/IsMigratorApplied/=JetBrains_002EReSharper_002EPsi_002ECSharp_002ECodeStyle_002ECSharpUseContinuousIndentInsideBracesMigration/@EntryIndexedValue">True</s:Boolean> - <s:Boolean x:Key="/Default/Environment/SettingsMigration/IsMigratorApplied/=JetBrains_002EReSharper_002EPsi_002ECSharp_002ECodeStyle_002ESettingsUpgrade_002EAddAccessorOwnerDeclarationBracesMigration/@EntryIndexedValue">True</s:Boolean> - <s:Boolean x:Key="/Default/Environment/SettingsMigration/IsMigratorApplied/=JetBrains_002EReSharper_002EPsi_002ECSharp_002ECodeStyle_002ESettingsUpgrade_002EMigrateBlankLinesAroundFieldToBlankLinesAroundProperty/@EntryIndexedValue">True</s:Boolean> - <s:Boolean x:Key="/Default/Environment/SettingsMigration/IsMigratorApplied/=JetBrains_002EReSharper_002EPsi_002ECSharp_002ECodeStyle_002ESettingsUpgrade_002EMigrateThisQualifierSettings/@EntryIndexedValue">True</s:Boolean> -</wpf:ResourceDictionary> \ No newline at end of file +</wpf:ResourceDictionary> diff --git a/src/chocolatey.tests.integration/MockEventSubscriptionManager.cs b/src/chocolatey.tests.integration/MockEventSubscriptionManager.cs index a7bfb228c0..b5bf610773 100644 --- a/src/chocolatey.tests.integration/MockEventSubscriptionManager.cs +++ b/src/chocolatey.tests.integration/MockEventSubscriptionManager.cs @@ -33,16 +33,26 @@ public ConcurrentDictionary<Type, IList<object>> Messages get { return _messages.Value; } } - public void publish<Event>(Event eventMessage) where Event : class, IMessage + public void Publish<Event>(Event eventMessage) where Event : class, IMessage { var list = _messages.Value.GetOrAdd(typeof(Event), new List<object>()); list.Add(eventMessage); - Object.publish(eventMessage); + Object.Publish(eventMessage); } - public IDisposable subscribe<Event>(Action<Event> handleEvent, Action<Exception> handleError, Func<Event, bool> filter) where Event : class, IMessage + public IDisposable Subscribe<Event>(Action<Event> handleEvent, Action<Exception> handleError, Func<Event, bool> filter) where Event : class, IMessage { return new Subject<Event>(); } + +#pragma warning disable IDE1006 + [Obsolete("This overload is deprecated and will be removed in v3.")] + public void publish<Event>(Event eventMessage) where Event : class, IMessage + => Publish(eventMessage); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public IDisposable subscribe<Event>(Action<Event> handleEvent, Action<Exception> handleError, Func<Event, bool> filter) where Event : class, IMessage + => Subscribe(handleEvent, handleError, filter); +#pragma warning disable IDE1006 } } diff --git a/src/chocolatey.tests.integration/NUnitSetup.cs b/src/chocolatey.tests.integration/NUnitSetup.cs index a1b5cf992b..73f9b71144 100644 --- a/src/chocolatey.tests.integration/NUnitSetup.cs +++ b/src/chocolatey.tests.integration/NUnitSetup.cs @@ -45,70 +45,70 @@ public class NUnitSetup : tests.NUnitSetup public override void BeforeEverything() { Container = SimpleInjectorContainer.Container; - fix_application_parameter_variables(Container); + FixApplicationParameterVariables(Container); base.BeforeEverything(); // deep copy so we don't have the same configuration and // don't have to worry about issues using it - var config = Container.GetInstance<ChocolateyConfiguration>().deep_copy(); - config.Information.PlatformType = Platform.get_platform(); + var config = Container.GetInstance<ChocolateyConfiguration>().DeepCopy(); + config.Information.PlatformType = Platform.GetPlatform(); config.Information.IsInteractive = false; config.PromptForConfirmation = false; config.Force = true; - unpack_self(Container, config); - build_packages(Container, config); + UnpackSelf(Container, config); + BuildPackages(Container, config); - ConfigurationBuilder.set_up_configuration(new List<string>(), config, Container, new ChocolateyLicense(), null); + ConfigurationBuilder.SetupConfiguration(new List<string>(), config, Container, new ChocolateyLicense(), null); - MockLogger.reset(); + MockLogger.Reset(); } /// <summary> /// Most of the application parameters are already set by runtime and are readonly values. /// They need to be updated, so we can do that with reflection. /// </summary> - private static void fix_application_parameter_variables(Container container) + private static void FixApplicationParameterVariables(Container container) { var fileSystem = container.GetInstance<IFileSystem>(); - var applicationLocation = fileSystem.get_directory_name(fileSystem.get_current_assembly_path()); + var applicationLocation = fileSystem.GetDirectoryName(fileSystem.GetCurrentAssemblyPath()); var field = typeof(ApplicationParameters).GetField("InstallLocation"); field.SetValue(null, applicationLocation); field = typeof(ApplicationParameters).GetField("LoggingLocation"); - field.SetValue(null, fileSystem.combine_paths(ApplicationParameters.InstallLocation, "logs")); + field.SetValue(null, fileSystem.CombinePaths(ApplicationParameters.InstallLocation, "logs")); field = typeof(ApplicationParameters).GetField("GlobalConfigFileLocation"); - field.SetValue(null, fileSystem.combine_paths(ApplicationParameters.InstallLocation, "config", "chocolatey.config")); + field.SetValue(null, fileSystem.CombinePaths(ApplicationParameters.InstallLocation, "config", "chocolatey.config")); field = typeof(ApplicationParameters).GetField("LicenseFileLocation"); - field.SetValue(null, fileSystem.combine_paths(ApplicationParameters.InstallLocation, "license", "chocolatey.license.xml")); + field.SetValue(null, fileSystem.CombinePaths(ApplicationParameters.InstallLocation, "license", "chocolatey.license.xml")); field = typeof(ApplicationParameters).GetField("PackagesLocation"); - field.SetValue(null, fileSystem.combine_paths(ApplicationParameters.InstallLocation, "lib")); + field.SetValue(null, fileSystem.CombinePaths(ApplicationParameters.InstallLocation, "lib")); field = typeof(ApplicationParameters).GetField("PackageFailuresLocation"); - field.SetValue(null, fileSystem.combine_paths(ApplicationParameters.InstallLocation, "lib-bad")); + field.SetValue(null, fileSystem.CombinePaths(ApplicationParameters.InstallLocation, "lib-bad")); field = typeof(ApplicationParameters).GetField("PackageBackupLocation"); - field.SetValue(null, fileSystem.combine_paths(ApplicationParameters.InstallLocation, "lib-bkp")); + field.SetValue(null, fileSystem.CombinePaths(ApplicationParameters.InstallLocation, "lib-bkp")); field = typeof(ApplicationParameters).GetField("ShimsLocation"); - field.SetValue(null, fileSystem.combine_paths(ApplicationParameters.InstallLocation, "bin")); + field.SetValue(null, fileSystem.CombinePaths(ApplicationParameters.InstallLocation, "bin")); field = typeof(ApplicationParameters).GetField("ChocolateyPackageInfoStoreLocation"); - field.SetValue(null, fileSystem.combine_paths(ApplicationParameters.InstallLocation, ".chocolatey")); + field.SetValue(null, fileSystem.CombinePaths(ApplicationParameters.InstallLocation, ".chocolatey")); field = typeof(ApplicationParameters).GetField("ExtensionsLocation"); - field.SetValue(null, fileSystem.combine_paths(ApplicationParameters.HooksLocation, "extensions")); + field.SetValue(null, fileSystem.CombinePaths(ApplicationParameters.HooksLocation, "extensions")); field = typeof(ApplicationParameters).GetField("TemplatesLocation"); - field.SetValue(null, fileSystem.combine_paths(ApplicationParameters.HooksLocation, "templates")); + field.SetValue(null, fileSystem.CombinePaths(ApplicationParameters.HooksLocation, "templates")); field = typeof(ApplicationParameters).GetField("HooksLocation"); - field.SetValue(null, fileSystem.combine_paths(ApplicationParameters.InstallLocation, "hooks")); + field.SetValue(null, fileSystem.CombinePaths(ApplicationParameters.InstallLocation, "hooks")); field = typeof(ApplicationParameters).GetField("LockTransactionalInstallFiles"); field.SetValue(null, false); @@ -121,43 +121,43 @@ private static void fix_application_parameter_variables(Container container) } } - private void unpack_self(Container container, ChocolateyConfiguration config) + private void UnpackSelf(Container container, ChocolateyConfiguration config) { var unpackCommand = container.GetInstance<ChocolateyUnpackSelfCommand>(); - unpackCommand.run(config); + unpackCommand.Run(config); } - private void build_packages(Container container, ChocolateyConfiguration config) + private void BuildPackages(Container container, ChocolateyConfiguration config) { var fileSystem = container.GetInstance<IFileSystem>(); - var contextDir = fileSystem.combine_paths(fileSystem.get_directory_name(fileSystem.get_current_assembly_path()), "context"); + var contextDir = fileSystem.CombinePaths(fileSystem.GetDirectoryName(fileSystem.GetCurrentAssemblyPath()), "context"); // short-circuit building packages if they are already there. - if (fileSystem.get_files(contextDir, "*.nupkg").Any()) + if (fileSystem.GetFiles(contextDir, "*.nupkg").Any()) { - Console.WriteLine("Packages have already been built. Skipping... - If you need to rebuild packages, delete all nupkg files in {0}.".format_with(contextDir)); + Console.WriteLine("Packages have already been built. Skipping... - If you need to rebuild packages, delete all nupkg files in {0}.".FormatWith(contextDir)); return; } - var files = fileSystem.get_files(contextDir, "*.nuspec", SearchOption.AllDirectories); + var files = fileSystem.GetFiles(contextDir, "*.nuspec", SearchOption.AllDirectories); config.PackCommand.PackThrowOnUnsupportedElements = false; var command = container.GetInstance<ChocolateyPackCommand>(); - foreach (var file in files.or_empty_list_if_null()) + foreach (var file in files.OrEmpty()) { config.Input = file; - Console.WriteLine("Building {0}".format_with(file)); - command.run(config); + Console.WriteLine("Building {0}".FormatWith(file)); + command.Run(config); } config.PackCommand.PackThrowOnUnsupportedElements = true; - Console.WriteLine("Moving all nupkgs in {0} to context directory.".format_with(fileSystem.get_current_directory())); - var nupkgs = fileSystem.get_files(fileSystem.get_current_directory(), "*.nupkg"); + Console.WriteLine("Moving all nupkgs in {0} to context directory.".FormatWith(fileSystem.GetCurrentDirectory())); + var nupkgs = fileSystem.GetFiles(fileSystem.GetCurrentDirectory(), "*.nupkg"); - foreach (var nupkg in nupkgs.or_empty_list_if_null()) + foreach (var nupkg in nupkgs.OrEmpty()) { - fileSystem.copy_file(nupkg, fileSystem.combine_paths(contextDir, fileSystem.get_file_name(nupkg)), overwriteExisting: true); - fileSystem.delete_file(nupkg); + fileSystem.CopyFile(nupkg, fileSystem.CombinePaths(contextDir, fileSystem.GetFileName(nupkg)), overwriteExisting: true); + fileSystem.DeleteFile(nupkg); } //concurrency issues when packages are first built out during testing diff --git a/src/chocolatey.tests.integration/Scenario.cs b/src/chocolatey.tests.integration/Scenario.cs index 5f8eb93a2b..53a17c11ce 100644 --- a/src/chocolatey.tests.integration/Scenario.cs +++ b/src/chocolatey.tests.integration/Scenario.cs @@ -41,17 +41,17 @@ public class Scenario public static string get_top_level() { - return _fileSystem.get_directory_name(_fileSystem.get_current_assembly_path()); + return _fileSystem.GetDirectoryName(_fileSystem.GetCurrentAssemblyPath()); } public static string get_package_install_path() { - return _fileSystem.combine_paths(get_top_level(), "lib"); + return _fileSystem.CombinePaths(get_top_level(), "lib"); } public static IEnumerable<string> get_installed_package_paths() { - return _fileSystem.get_files(get_package_install_path(), "*" + NuGetConstants.PackageExtension, SearchOption.AllDirectories); + return _fileSystem.GetFiles(get_package_install_path(), "*" + NuGetConstants.PackageExtension, SearchOption.AllDirectories); } public static void reset(ChocolateyConfiguration config) @@ -62,37 +62,37 @@ public static void reset(ChocolateyConfiguration config) string shimsPath = ApplicationParameters.ShimsLocation; string hooksPath = ApplicationParameters.HooksLocation; - _fileSystem.delete_directory_if_exists(config.CacheLocation, recursive: true, overrideAttributes: true); - _fileSystem.delete_directory_if_exists(config.Sources, recursive: true, overrideAttributes: true); - _fileSystem.delete_directory_if_exists(packagesInstallPath, recursive: true, overrideAttributes: true); - _fileSystem.delete_directory_if_exists(shimsPath, recursive: true, overrideAttributes: true); - _fileSystem.delete_directory_if_exists(badPackagesPath, recursive: true, overrideAttributes: true); - _fileSystem.delete_directory_if_exists(backupPackagesPath, recursive: true, overrideAttributes: true); - _fileSystem.delete_directory_if_exists(_fileSystem.combine_paths(get_top_level(), ".chocolatey"), recursive: true, overrideAttributes: true); - _fileSystem.delete_directory_if_exists(_fileSystem.combine_paths(get_top_level(), "extensions"), recursive: true, overrideAttributes: true); - _fileSystem.delete_directory_if_exists(hooksPath, recursive: true, overrideAttributes: true); - - _fileSystem.create_directory(config.CacheLocation); - _fileSystem.create_directory(config.Sources); - _fileSystem.create_directory(packagesInstallPath); - _fileSystem.create_directory(shimsPath); - _fileSystem.create_directory(badPackagesPath); - _fileSystem.create_directory(backupPackagesPath); - _fileSystem.create_directory(_fileSystem.combine_paths(get_top_level(), ".chocolatey")); - _fileSystem.create_directory(_fileSystem.combine_paths(get_top_level(), "extensions")); + _fileSystem.DeleteDirectoryChecked(config.CacheLocation, recursive: true, overrideAttributes: true); + _fileSystem.DeleteDirectoryChecked(config.Sources, recursive: true, overrideAttributes: true); + _fileSystem.DeleteDirectoryChecked(packagesInstallPath, recursive: true, overrideAttributes: true); + _fileSystem.DeleteDirectoryChecked(shimsPath, recursive: true, overrideAttributes: true); + _fileSystem.DeleteDirectoryChecked(badPackagesPath, recursive: true, overrideAttributes: true); + _fileSystem.DeleteDirectoryChecked(backupPackagesPath, recursive: true, overrideAttributes: true); + _fileSystem.DeleteDirectoryChecked(_fileSystem.CombinePaths(get_top_level(), ".chocolatey"), recursive: true, overrideAttributes: true); + _fileSystem.DeleteDirectoryChecked(_fileSystem.CombinePaths(get_top_level(), "extensions"), recursive: true, overrideAttributes: true); + _fileSystem.DeleteDirectoryChecked(hooksPath, recursive: true, overrideAttributes: true); + + _fileSystem.CreateDirectory(config.CacheLocation); + _fileSystem.CreateDirectory(config.Sources); + _fileSystem.CreateDirectory(packagesInstallPath); + _fileSystem.CreateDirectory(shimsPath); + _fileSystem.CreateDirectory(badPackagesPath); + _fileSystem.CreateDirectory(backupPackagesPath); + _fileSystem.CreateDirectory(_fileSystem.CombinePaths(get_top_level(), ".chocolatey")); + _fileSystem.CreateDirectory(_fileSystem.CombinePaths(get_top_level(), "extensions")); PowershellExecutor.AllowUseWindow = false; } public static void add_packages_to_source_location(ChocolateyConfiguration config, string pattern) { - _fileSystem.create_directory_if_not_exists(config.Sources); - var contextDir = _fileSystem.combine_paths(get_top_level(), "context"); - var files = _fileSystem.get_files(contextDir, pattern, SearchOption.AllDirectories); + _fileSystem.EnsureDirectoryExists(config.Sources); + var contextDir = _fileSystem.CombinePaths(get_top_level(), "context"); + var files = _fileSystem.GetFiles(contextDir, pattern, SearchOption.AllDirectories); - foreach (var file in files.or_empty_list_if_null()) + foreach (var file in files.OrEmpty()) { - _fileSystem.copy_file(_fileSystem.get_full_path(file), _fileSystem.combine_paths(config.Sources, _fileSystem.get_file_name(file)), overwriteExisting: true); + _fileSystem.CopyFile(_fileSystem.GetFullPath(file), _fileSystem.CombinePaths(config.Sources, _fileSystem.GetFileName(file)), overwriteExisting: true); } } @@ -100,12 +100,12 @@ public static void add_machine_source(ChocolateyConfiguration config, string nam { if (string.IsNullOrEmpty(path)) { - path = _fileSystem.combine_paths(get_top_level(), "PrioritySources", name); + path = _fileSystem.CombinePaths(get_top_level(), "PrioritySources", name); } if (createDirectory) { - _fileSystem.create_directory_if_not_exists(path); + _fileSystem.EnsureDirectoryExists(path); } var newSource = new MachineSourceConfiguration @@ -124,9 +124,9 @@ public static string add_packages_to_priority_source_location(ChocolateyConfigur name = "Priority" + priority; } - var prioritySourceDirectory = _fileSystem.combine_paths(get_top_level(), "PrioritySources", name); + var prioritySourceDirectory = _fileSystem.CombinePaths(get_top_level(), "PrioritySources", name); - var machineSource = config.MachineSources.FirstOrDefault(m => m.Name.is_equal_to(name)); + var machineSource = config.MachineSources.FirstOrDefault(m => m.Name.IsEqualTo(name)); if (machineSource == null) { @@ -143,19 +143,19 @@ public static string add_packages_to_priority_source_location(ChocolateyConfigur prioritySourceDirectory = machineSource.Key; } - _fileSystem.create_directory_if_not_exists(prioritySourceDirectory); + _fileSystem.EnsureDirectoryExists(prioritySourceDirectory); - var contextDir = _fileSystem.combine_paths(get_top_level(), "context"); - var files = _fileSystem.get_files(contextDir, pattern, SearchOption.AllDirectories).or_empty_list_if_null().ToList(); + var contextDir = _fileSystem.CombinePaths(get_top_level(), "context"); + var files = _fileSystem.GetFiles(contextDir, pattern, SearchOption.AllDirectories).OrEmpty().ToList(); if (files.Count == 0) { - throw new ApplicationException("No files matching the pattern {0} could be found!".format_with(pattern)); + throw new ApplicationException("No files matching the pattern {0} could be found!".FormatWith(pattern)); } foreach (var file in files) { - _fileSystem.copy_file(_fileSystem.get_full_path(file), _fileSystem.combine_paths(prioritySourceDirectory, _fileSystem.get_file_name(file)), overwriteExisting: true); + _fileSystem.CopyFile(_fileSystem.GetFullPath(file), _fileSystem.CombinePaths(prioritySourceDirectory, _fileSystem.GetFileName(file)), overwriteExisting: true); } return machineSource.Name; @@ -163,16 +163,16 @@ public static string add_packages_to_priority_source_location(ChocolateyConfigur public static void remove_packages_from_destination_location(ChocolateyConfiguration config, string pattern) { - if (!_fileSystem.directory_exists(config.Sources)) + if (!_fileSystem.DirectoryExists(config.Sources)) { return; } - var files = _fileSystem.get_files(config.Sources, pattern, SearchOption.AllDirectories); + var files = _fileSystem.GetFiles(config.Sources, pattern, SearchOption.AllDirectories); foreach (var file in files) { - _fileSystem.delete_file(file); + _fileSystem.DeleteFile(file); } } @@ -182,12 +182,12 @@ public static void install_package(ChocolateyConfiguration config, string packag { _service = NUnitSetup.Container.GetInstance<IChocolateyPackageService>(); } - var installConfig = config.deep_copy(); + var installConfig = config.DeepCopy(); installConfig.PackageNames = packageId; installConfig.Version = version; - installConfig.CommandName = CommandNameType.install.to_string(); - _service.install_run(installConfig); + installConfig.CommandName = CommandNameType.Install.ToStringSafe(); + _service.Install(installConfig); NUnitSetup.MockLogger.Messages.Clear(); } @@ -196,29 +196,29 @@ public static void add_files(IEnumerable<Tuple<string, string>> files) { foreach (var file in files) { - if (_fileSystem.file_exists(file.Item1)) + if (_fileSystem.FileExists(file.Item1)) { - _fileSystem.delete_file(file.Item1); + _fileSystem.DeleteFile(file.Item1); } - _fileSystem.write_file(file.Item1, file.Item2); + _fileSystem.WriteFile(file.Item1, file.Item2); } } public static void create_directory(string directoryPath) { - _fileSystem.create_directory(directoryPath); + _fileSystem.CreateDirectory(directoryPath); } public static void add_changed_version_package_to_source_location(ChocolateyConfiguration config, string pattern, string newVersion) { - _fileSystem.create_directory_if_not_exists(config.Sources); - var contextDir = _fileSystem.combine_paths(get_top_level(), "context"); - var files = _fileSystem.get_files(contextDir, pattern, SearchOption.AllDirectories); + _fileSystem.EnsureDirectoryExists(config.Sources); + var contextDir = _fileSystem.CombinePaths(get_top_level(), "context"); + var files = _fileSystem.GetFiles(contextDir, pattern, SearchOption.AllDirectories); - foreach (var file in files.or_empty_list_if_null()) + foreach (var file in files.OrEmpty()) { - var copyToPath = _fileSystem.combine_paths(config.Sources, _fileSystem.get_file_name(file)); - _fileSystem.copy_file(_fileSystem.get_full_path(file), copyToPath, overwriteExisting: true); + var copyToPath = _fileSystem.CombinePaths(config.Sources, _fileSystem.GetFileName(file)); + _fileSystem.CopyFile(_fileSystem.GetFullPath(file), copyToPath, overwriteExisting: true); change_package_version(copyToPath, newVersion); } } @@ -242,7 +242,7 @@ public static void change_package_version(string existingPackagePath, string new using (var zipArchive = new ZipArchive(packageStream, ZipArchiveMode.Update)) { - var entry = zipArchive.GetEntry("{0}{1}".format_with(packageId, NuGetConstants.ManifestExtension)); + var entry = zipArchive.GetEntry("{0}{1}".FormatWith(packageId, NuGetConstants.ManifestExtension)); using (var nuspecStream = entry.Open()) { nuspecXml.Save(nuspecStream); @@ -250,10 +250,10 @@ public static void change_package_version(string existingPackagePath, string new } } - var renamedPath = _fileSystem.combine_paths( - _fileSystem.get_directory_name(existingPackagePath), - "{0}.{1}{2}".format_with(packageId, newVersion, NuGetConstants.PackageExtension)); - _fileSystem.move_file(existingPackagePath, renamedPath); + var renamedPath = _fileSystem.CombinePaths( + _fileSystem.GetDirectoryName(existingPackagePath), + "{0}.{1}{2}".FormatWith(packageId, newVersion, NuGetConstants.PackageExtension)); + _fileSystem.MoveFile(existingPackagePath, renamedPath); } private static ChocolateyConfiguration baseline_configuration() @@ -264,7 +264,7 @@ private static ChocolateyConfiguration baseline_configuration() // prior commands, so ensure that all items go back to the default values here var config = NUnitSetup.Container.GetInstance<ChocolateyConfiguration>(); - config.Information.PlatformType = Platform.get_platform(); + config.Information.PlatformType = Platform.GetPlatform(); config.Information.IsInteractive = false; config.Information.ChocolateyVersion = "1.2.3"; config.Information.PlatformVersion = new Version(6, 1, 0, 0); @@ -279,12 +279,13 @@ private static ChocolateyConfiguration baseline_configuration() config.Information.IsLicensedVersion = false; config.AcceptLicense = true; config.AllowUnofficialBuild = true; - config.CacheLocation = _fileSystem.get_full_path(_fileSystem.combine_paths(get_top_level(), "cache")); + config.CacheLocation = _fileSystem.GetFullPath(_fileSystem.CombinePaths(get_top_level(), "cache")); config.CommandExecutionTimeoutSeconds = 2700; config.Force = false; config.ForceDependencies = false; config.ForceX86 = false; config.HelpRequested = false; + config.ShowOnlineHelp = false; config.UnsuccessfulParsing = false; config.UnsuccessfulParsing = false; config.IgnoreDependencies = false; @@ -296,7 +297,7 @@ private static ChocolateyConfiguration baseline_configuration() config.PromptForConfirmation = false; config.RegularOutput = true; config.SkipPackageInstallProvider = false; - config.Sources = _fileSystem.get_full_path(_fileSystem.combine_paths(get_top_level(), "packages")); + config.Sources = _fileSystem.GetFullPath(_fileSystem.CombinePaths(get_top_level(), "packages")); config.Version = null; config.Debug = true; config.AllVersions = false; @@ -316,7 +317,7 @@ private static ChocolateyConfiguration baseline_configuration() config.ListCommand.IncludeVersionOverrides = false; config.UpgradeCommand.FailOnNotInstalled = false; config.PinCommand.Name = string.Empty; - config.PinCommand.Command = PinCommandType.unknown; + config.PinCommand.Command = PinCommandType.Unknown; config.ListCommand.IdOnly = false; config.MachineSources.Clear(); @@ -326,7 +327,7 @@ private static ChocolateyConfiguration baseline_configuration() public static ChocolateyConfiguration install() { var config = baseline_configuration(); - config.CommandName = CommandNameType.install.to_string(); + config.CommandName = CommandNameType.Install.ToStringSafe(); return config; } @@ -334,7 +335,7 @@ public static ChocolateyConfiguration install() public static ChocolateyConfiguration upgrade() { var config = baseline_configuration(); - config.CommandName = CommandNameType.upgrade.to_string(); + config.CommandName = CommandNameType.Upgrade.ToStringSafe(); return config; } @@ -342,7 +343,7 @@ public static ChocolateyConfiguration upgrade() public static ChocolateyConfiguration uninstall() { var config = baseline_configuration(); - config.CommandName = CommandNameType.uninstall.to_string(); + config.CommandName = CommandNameType.Uninstall.ToStringSafe(); return config; } @@ -389,6 +390,21 @@ public static ChocolateyConfiguration pack() return config; } + public static ChocolateyConfiguration proxy() + { + return baseline_configuration(); + } + + public static void set_configuration_file_setting(string name, string value) + { + var config = baseline_configuration(); + config.ConfigCommand.Name = name; + config.ConfigCommand.ConfigValue = value; + config.ConfigCommand.Command = ConfigCommandType.Set; + var configService = NUnitSetup.Container.GetInstance<IChocolateyConfigSettingsService>(); + configService.SetConfig(config); + } + private static void delete_test_package_directories() { var topDirectory = get_top_level(); @@ -401,7 +417,7 @@ private static void delete_test_package_directories() foreach (var directory in directoriesToClean) { - _fileSystem.delete_directory_if_exists(directory, recursive: true); + _fileSystem.DeleteDirectoryChecked(directory, recursive: true); } } } diff --git a/src/chocolatey.tests.integration/chocolatey.tests.integration.csproj b/src/chocolatey.tests.integration/chocolatey.tests.integration.csproj index e299819d18..3f66423721 100644 --- a/src/chocolatey.tests.integration/chocolatey.tests.integration.csproj +++ b/src/chocolatey.tests.integration/chocolatey.tests.integration.csproj @@ -78,23 +78,23 @@ <CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet> </PropertyGroup> <ItemGroup> - <Reference Include="Chocolatey.NuGet.Common, Version=3.0.0.204, Culture=neutral, PublicKeyToken=fd112f53c3ab578c, processorArchitecture=MSIL"> - <HintPath>..\packages\Chocolatey.NuGet.Common.3.0.0-alpha-20230315-204\lib\net472\Chocolatey.NuGet.Common.dll</HintPath> + <Reference Include="Chocolatey.NuGet.Common"> + <HintPath>..\packages\Chocolatey.NuGet.Common.3.1.0\lib\net472\Chocolatey.NuGet.Common.dll</HintPath> </Reference> - <Reference Include="Chocolatey.NuGet.Configuration, Version=3.0.0.204, Culture=neutral, PublicKeyToken=fd112f53c3ab578c, processorArchitecture=MSIL"> - <HintPath>..\packages\Chocolatey.NuGet.Configuration.3.0.0-alpha-20230315-204\lib\net472\Chocolatey.NuGet.Configuration.dll</HintPath> + <Reference Include="Chocolatey.NuGet.Configuration"> + <HintPath>..\packages\Chocolatey.NuGet.Configuration.3.1.0\lib\net472\Chocolatey.NuGet.Configuration.dll</HintPath> </Reference> - <Reference Include="Chocolatey.NuGet.Frameworks, Version=3.0.0.204, Culture=neutral, PublicKeyToken=fd112f53c3ab578c, processorArchitecture=MSIL"> - <HintPath>..\packages\Chocolatey.NuGet.Frameworks.3.0.0-alpha-20230315-204\lib\net472\Chocolatey.NuGet.Frameworks.dll</HintPath> + <Reference Include="Chocolatey.NuGet.Frameworks"> + <HintPath>..\packages\Chocolatey.NuGet.Frameworks.3.1.0\lib\net472\Chocolatey.NuGet.Frameworks.dll</HintPath> </Reference> - <Reference Include="Chocolatey.NuGet.Packaging, Version=3.0.0.204, Culture=neutral, PublicKeyToken=fd112f53c3ab578c, processorArchitecture=MSIL"> - <HintPath>..\packages\Chocolatey.NuGet.Packaging.3.0.0-alpha-20230315-204\lib\net472\Chocolatey.NuGet.Packaging.dll</HintPath> + <Reference Include="Chocolatey.NuGet.Packaging"> + <HintPath>..\packages\Chocolatey.NuGet.Packaging.3.1.0\lib\net472\Chocolatey.NuGet.Packaging.dll</HintPath> </Reference> - <Reference Include="Chocolatey.NuGet.Protocol, Version=3.0.0.204, Culture=neutral, PublicKeyToken=fd112f53c3ab578c, processorArchitecture=MSIL"> - <HintPath>..\packages\Chocolatey.NuGet.Protocol.3.0.0-alpha-20230315-204\lib\net472\Chocolatey.NuGet.Protocol.dll</HintPath> + <Reference Include="Chocolatey.NuGet.Protocol"> + <HintPath>..\packages\Chocolatey.NuGet.Protocol.3.1.0\lib\net472\Chocolatey.NuGet.Protocol.dll</HintPath> </Reference> - <Reference Include="Chocolatey.NuGet.Versioning, Version=3.0.0.204, Culture=neutral, PublicKeyToken=fd112f53c3ab578c, processorArchitecture=MSIL"> - <HintPath>..\packages\Chocolatey.NuGet.Versioning.3.0.0-alpha-20230315-204\lib\net472\Chocolatey.NuGet.Versioning.dll</HintPath> + <Reference Include="Chocolatey.NuGet.Versioning"> + <HintPath>..\packages\Chocolatey.NuGet.Versioning.3.1.0\lib\net472\Chocolatey.NuGet.Versioning.dll</HintPath> </Reference> <Reference Include="log4net, Version=2.0.12.0, Culture=neutral, PublicKeyToken=669e0ddf0bb1aa2a, processorArchitecture=MSIL"> <HintPath>..\packages\log4net.2.0.12\lib\net45\log4net.dll</HintPath> @@ -146,6 +146,7 @@ <Reference Include="WindowsBase" /> </ItemGroup> <ItemGroup> + <Compile Include="infrastructure.app\builders\ConfigurationBuilderSpecs.cs" /> <Compile Include="infrastructure.app\services\FilesServiceSpecs.cs" /> <Compile Include="infrastructure\commands\CommandExecutorSpecs.cs" /> <Compile Include="infrastructure\cryptography\CryptoHashProviderSpecs.cs" /> diff --git a/src/chocolatey.tests.integration/context/unsupportedelements/1.0.0/unsupportedelements.nuspec b/src/chocolatey.tests.integration/context/unsupportedelements/1.0.0/unsupportedelements.nuspec index 681e77fea1..68d7e8e42a 100644 --- a/src/chocolatey.tests.integration/context/unsupportedelements/1.0.0/unsupportedelements.nuspec +++ b/src/chocolatey.tests.integration/context/unsupportedelements/1.0.0/unsupportedelements.nuspec @@ -1,6 +1,6 @@ <?xml version="1.0"?> <package xmlns="http://schemas.microsoft.com/packaging/2010/07/nuspec.xsd"> - <metadata> + <metadata minClientVersion="100.0.0"> <id>unsupportedelements</id> <version>1.0.0</version> <title>unsupportedelements diff --git a/src/chocolatey.tests.integration/context/unsupportedelements/1.1.0/unsupportedelements.nuspec b/src/chocolatey.tests.integration/context/unsupportedelements/1.1.0/unsupportedelements.nuspec index a0c1b0f35c..a86b86601a 100644 --- a/src/chocolatey.tests.integration/context/unsupportedelements/1.1.0/unsupportedelements.nuspec +++ b/src/chocolatey.tests.integration/context/unsupportedelements/1.1.0/unsupportedelements.nuspec @@ -1,6 +1,6 @@ - + unsupportedelements 1.1.0 unsupportedelements diff --git a/src/chocolatey.tests.integration/infrastructure.app/builders/ConfigurationBuilderSpecs.cs b/src/chocolatey.tests.integration/infrastructure.app/builders/ConfigurationBuilderSpecs.cs new file mode 100644 index 0000000000..4ff1efca7f --- /dev/null +++ b/src/chocolatey.tests.integration/infrastructure.app/builders/ConfigurationBuilderSpecs.cs @@ -0,0 +1,238 @@ +// Copyright © 2017 - 2023 Chocolatey Software, Inc +// Copyright © 2011 - 2017 RealDimensions Software, LLC +// +// 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. + +namespace chocolatey.tests.integration.infrastructure.app.builders +{ + using System; + using System.Collections.Generic; + using System.Configuration; + using chocolatey.infrastructure.adapters; + using chocolatey.infrastructure.app; + using ConfigurationBuilder = chocolatey.infrastructure.app.builders.ConfigurationBuilder; + using chocolatey.infrastructure.app.configuration; + using chocolatey.infrastructure.app.domain; + using chocolatey.infrastructure.app.services; + using chocolatey.infrastructure.licensing; + using Moq; + using NUnit.Framework; + using Container = SimpleInjector.Container; + using License = System.ComponentModel.License; + using chocolatey.infrastructure.registration; + using Microsoft.Win32; + using scenarios; + using Should; + + public class ConfigurationBuilderSpecs + { + private const string IgnoreSystemProxyReason = "System Proxy not mockable"; + + public abstract class ProxyConfigurationBase : TinySpec + { + protected bool SystemSet = false; + protected bool EnvironmentVariableSet = false; + protected bool ConfigSet = false; + protected bool ArgumentSet = false; + protected const string ConfigurationFileProxySettingName = "proxy"; + protected const string ConfigurationFileProxyBypassSettingName = "proxyBypassList"; + protected const string EnvironmentVariableProxyValue = "EnvironmentVariableSet"; + protected const string CommandArgumentProxyValue = "CommandArgumentSet"; + protected const string ConfigurationFileProxyValue = "ConfigurationFileSet"; + protected const string SystemLevelProxyValue = "SystemLevelSet"; + protected ChocolateyConfiguration Configuration; + protected Container Container; + protected ChocolateyLicense License; + protected Mock Environment; + protected List ArgumentsList = new List(); + + public ProxyConfigurationBase(bool systemSet, bool environmentVariableSet, bool configSet, bool argumentSet) + { + SystemSet = systemSet; + EnvironmentVariableSet = environmentVariableSet; + ConfigSet = configSet; + ArgumentSet = argumentSet; + } + + public override void Context() + { + Configuration = Scenario.proxy(); + Scenario.set_configuration_file_setting(ConfigurationFileProxySettingName, string.Empty); + Scenario.set_configuration_file_setting(ConfigurationFileProxyBypassSettingName, string.Empty); + Scenario.reset(Configuration); + Container = NUnitSetup.Container; + License = new ChocolateyLicense(); + Environment = new Mock(); + ConfigurationBuilder.InitializeWith(new Lazy(() => Environment.Object)); + Environment.Setup(e => e.GetEnvironmentVariable(It.IsAny())).Returns(string.Empty); + ArgumentsList.Clear(); + } + + public override void Because() + { + ConfigurationBuilder.SetupConfiguration(ArgumentsList, Configuration, Container, License, null); + } + } + + // System and Configuration File and Environment Variable and CLI Argument + [TestFixture(false, false, false, false, TestName = "No Proxy Set")] + [TestFixture(true, false, false, false, TestName = "System Set", IgnoreReason = IgnoreSystemProxyReason)] + [TestFixture(true, true, false, false, TestName = "System and Environment Set", IgnoreReason = IgnoreSystemProxyReason)] + [TestFixture(true, true, true, false, TestName = "System and Environment and Configuration Set", IgnoreReason = IgnoreSystemProxyReason)] + [TestFixture(true, true, true, true, TestName = "System and Environment and Configuration and Argument Set", IgnoreReason = IgnoreSystemProxyReason)] + [TestFixture(true, false, true, false, TestName = "System and Configuration Set", IgnoreReason = IgnoreSystemProxyReason)] + [TestFixture(true, false, true, true, TestName = "System and Configuration and Argument Set", IgnoreReason = IgnoreSystemProxyReason)] + [TestFixture(true, false, false, true, TestName = "System and Argument Set", IgnoreReason = IgnoreSystemProxyReason)] + [TestFixture(true, true, false, true, TestName = "System and Environment and Argument Set", IgnoreReason = IgnoreSystemProxyReason)] + [TestFixture(false, true, false, false, TestName = "Environment Set")] + [TestFixture(false, true, true, false, TestName = "Environment and Configuration Set")] + [TestFixture(false, true, false, true, TestName = "Environment and Argument Set")] + [TestFixture(false, true, true, true, TestName = "Environment and Configuration and Argument Set")] + [TestFixture(false, false, true, false, TestName = "Configuration Set")] + [TestFixture(false, false, true, true, TestName = "Configuration and Argument Set")] + [TestFixture(false, false, false, true, TestName = "Argument Set")] + public class WhenProxyConfigurationTests : ProxyConfigurationBase + { + public WhenProxyConfigurationTests(bool system, bool environment, bool config, bool argument) : base(system, environment, config, argument) {} + public override void Context() + { + base.Context(); + + if (SystemSet) + { + // Do System Level things + } + + if (EnvironmentVariableSet) + { + Environment.Setup(e => e.GetEnvironmentVariable(It.IsIn("http_proxy", "https_proxy"))).Returns(EnvironmentVariableProxyValue); + } + else + { + Environment.Setup(e => e.GetEnvironmentVariable(It.IsIn("http_proxy", "https_proxy"))).Returns(string.Empty); + } + + if (ConfigSet) + { + Scenario.set_configuration_file_setting(ConfigurationFileProxySettingName, ConfigurationFileProxyValue); + } + + if (ArgumentSet) + { + ArgumentsList.Add("--proxy='{0}'".FormatWith(CommandArgumentProxyValue)); + } + } + + [Fact] + public void ShouldHaveProxyConfiguration() + { + if (!SystemSet && !ArgumentSet && !ConfigSet && + !EnvironmentVariableSet) + { + Configuration.Proxy.Location.ShouldEqual(string.Empty); + return; + } + + if (ArgumentSet) + { + Configuration.Proxy.Location.ShouldEqual(CommandArgumentProxyValue); + return; + } + + if (ConfigSet) + { + Configuration.Proxy.Location.ShouldEqual(ConfigurationFileProxyValue); + return; + } + + if (EnvironmentVariableSet) + { + Configuration.Proxy.Location.ShouldEqual(EnvironmentVariableProxyValue); + return; + } + + if (SystemSet) + { + Configuration.Proxy.Location.ShouldEqual(SystemLevelProxyValue); + return; + } + } + } + + [TestFixture(false, false, false, false, TestName = "No Bypass Set")] + [TestFixture(false, true, false, false, TestName = "Config Bypass Set")] + [TestFixture(false, true, true, false, TestName = "Config and Environment Variable Bypass Set")] + [TestFixture(false, true, true, true, TestName = "Config and Environment Variable and Argument Bypass Set")] + [TestFixture(false, true, false, true, TestName = "Config and Argument Bypass Set")] + [TestFixture(false, false, true, false, TestName = "Environment Variable Bypass Set")] + [TestFixture(false, false, true, true, TestName = "Environment Variable and Argument Bypass Set")] + public class WhenProxyBypassConfigurationTests : ProxyConfigurationBase + { + public WhenProxyBypassConfigurationTests(bool system, bool environment, bool config, bool argument) : base(system, environment, config, argument) { } + + public override void Context() + { + base.Context(); + + if (ConfigSet) + { + Scenario.set_configuration_file_setting(ConfigurationFileProxyBypassSettingName, ConfigurationFileProxyValue); + } + + if (EnvironmentVariableSet) + { + Environment.Setup(e => e.GetEnvironmentVariable("no_proxy")).Returns(EnvironmentVariableProxyValue); + } + else + { + Environment.Setup(e => e.GetEnvironmentVariable("no_proxy")).Returns(string.Empty); + } + + if (ArgumentSet) + { + ArgumentsList.Add("--proxy-bypass-list='{0}'".FormatWith(CommandArgumentProxyValue)); + } + } + + [Fact] + public void ShouldBypassProxy() + { + if (!ArgumentSet && !ConfigSet && + !EnvironmentVariableSet) + { + Configuration.Proxy.BypassList.ShouldEqual(string.Empty); + return; + } + + if (ArgumentSet) + { + Configuration.Proxy.BypassList.ShouldEqual(CommandArgumentProxyValue); + return; + } + + if (ConfigSet) + { + Configuration.Proxy.BypassList.ShouldEqual(ConfigurationFileProxyValue); + return; + } + + if (EnvironmentVariableSet) + { + Configuration.Proxy.BypassList.ShouldEqual(EnvironmentVariableProxyValue); + return; + } + } + } + } +} diff --git a/src/chocolatey.tests.integration/infrastructure.app/services/FilesServiceSpecs.cs b/src/chocolatey.tests.integration/infrastructure.app/services/FilesServiceSpecs.cs index a78ed7f279..46173c0421 100644 --- a/src/chocolatey.tests.integration/infrastructure.app/services/FilesServiceSpecs.cs +++ b/src/chocolatey.tests.integration/infrastructure.app/services/FilesServiceSpecs.cs @@ -47,7 +47,7 @@ public override void Context() } [SetCulture("en"), SetUICulture("en")] - public class when_FilesService_encounters_locked_files : FilesServiceSpecsBase + public class When_FilesService_encounters_locked_files : FilesServiceSpecsBase { private PackageFiles _result; private readonly ChocolateyConfiguration _config = new ChocolateyConfiguration(); @@ -61,7 +61,7 @@ public override void Context() base.Context(); _contextPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "infrastructure", "filesystem"); _theLockedFile = Path.Combine(_contextPath, "Slipsum.txt"); - _packageResult = new PackageResult("bob", "1.2.3", FileSystem.get_directory_name(_theLockedFile)); + _packageResult = new PackageResult("bob", "1.2.3", FileSystem.GetDirectoryName(_theLockedFile)); _fileStream = new FileStream(_theLockedFile, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None); } @@ -75,17 +75,17 @@ public override void AfterObservations() public override void Because() { - _result = Service.capture_package_files(_packageResult, _config); + _result = Service.CaptureSnapshot(_packageResult, _config); } [Fact] - public void should_not_error() + public void Should_not_error() { //nothing to see here } [Fact] - public void should_log_a_warning() + public void Should_log_a_warning() { MockLogger.Verify(l => l.Warn(It.IsAny()), Times.AtLeastOnce); } @@ -93,13 +93,13 @@ public void should_log_a_warning() [Fact] [WindowsOnly] [Platform(Exclude = "Mono")] - public void should_log_a_warning_about_locked_files() + public void Should_log_a_warning_about_locked_files() { MockLogger.Verify(l => l.Warn(It.Is(s => s.Contains("The process cannot access the file"))), Times.Once); } [Fact] - public void should_return_a_special_code_for_locked_files() + public void Should_return_a_special_code_for_locked_files() { _result.Files.FirstOrDefault(x => x.Path == _theLockedFile).Checksum.ShouldEqual(ApplicationParameters.HashProviderFileLocked); } diff --git a/src/chocolatey.tests.integration/infrastructure/commands/CommandExecutorSpecs.cs b/src/chocolatey.tests.integration/infrastructure/commands/CommandExecutorSpecs.cs index 399c34b220..2232af6b4d 100644 --- a/src/chocolatey.tests.integration/infrastructure/commands/CommandExecutorSpecs.cs +++ b/src/chocolatey.tests.integration/infrastructure/commands/CommandExecutorSpecs.cs @@ -38,7 +38,7 @@ public override void Context() [WindowsOnly] [Platform(Exclude = "Mono")] - public class when_CommandExecutor_errors : CommandExecutorSpecsBase + public class When_CommandExecutor_errors : CommandExecutorSpecsBase { private int result; private string errorOutput; @@ -50,11 +50,11 @@ public override void Context() public override void Because() { - result = commandExecutor.execute( + result = commandExecutor.Execute( "cmd.exe", "/c bob123123", ApplicationParameters.DefaultWaitForExitInSeconds, - fileSystem.get_current_directory(), + fileSystem.GetCurrentDirectory(), null, (s, e) => { errorOutput += e.Data; }, updateProcessPath: false, @@ -62,19 +62,19 @@ public override void Because() } [Fact] - public void should_not_return_an_exit_code_of_zero() + public void Should_not_return_an_exit_code_of_zero() { result.ShouldNotEqual(0); } [Fact] - public void should_contain_error_output() + public void Should_contain_error_output() { errorOutput.ShouldNotBeNull(); } [Fact] - public void should_message_the_error() + public void Should_message_the_error() { errorOutput.ShouldEqual("'bob123123' is not recognized as an internal or external command,operable program or batch file."); } @@ -82,7 +82,7 @@ public void should_message_the_error() [WindowsOnly] [Platform(Exclude = "Mono")] - public class when_CommandExecutor_is_given_a_nonexisting_process : CommandExecutorSpecsBase + public class When_CommandExecutor_is_given_a_nonexisting_process : CommandExecutorSpecsBase { private string result; private string errorOutput; @@ -91,7 +91,7 @@ public override void Because() { try { - commandExecutor.execute("noprocess.exe", "/c bob123123", ApplicationParameters.DefaultWaitForExitInSeconds, null, (s, e) => { errorOutput += e.Data; }); + commandExecutor.Execute("noprocess.exe", "/c bob123123", ApplicationParameters.DefaultWaitForExitInSeconds, null, (s, e) => { errorOutput += e.Data; }); } catch (Exception e) { @@ -100,7 +100,7 @@ public override void Because() } [Fact] - public void should_have_an_error_message() + public void Should_have_an_error_message() { result.ShouldNotBeNull(); } diff --git a/src/chocolatey.tests.integration/infrastructure/cryptography/CryptoHashProviderSpecs.cs b/src/chocolatey.tests.integration/infrastructure/cryptography/CryptoHashProviderSpecs.cs index 9249067706..46c69a5007 100644 --- a/src/chocolatey.tests.integration/infrastructure/cryptography/CryptoHashProviderSpecs.cs +++ b/src/chocolatey.tests.integration/infrastructure/cryptography/CryptoHashProviderSpecs.cs @@ -35,11 +35,11 @@ public override void Context() { FileSystem = new DotNetFileSystem(); Provider = new CryptoHashProvider(FileSystem); - ContextDirectory = FileSystem.combine_paths(FileSystem.get_directory_name(FileSystem.get_current_assembly_path()), "context"); + ContextDirectory = FileSystem.CombinePaths(FileSystem.GetDirectoryName(FileSystem.GetCurrentAssemblyPath()), "context"); } } - public class when_HashProvider_provides_a_hash : CryptoHashProviderSpecsBase + public class When_HashProvider_provides_a_hash : CryptoHashProviderSpecsBase { private string result; private string filePath; @@ -47,16 +47,16 @@ public class when_HashProvider_provides_a_hash : CryptoHashProviderSpecsBase public override void Context() { base.Context(); - filePath = FileSystem.combine_paths(ContextDirectory, "testing.packages.config"); + filePath = FileSystem.CombinePaths(ContextDirectory, "testing.packages.config"); } public override void Because() { - result = Provider.hash_file(filePath); + result = Provider.ComputeFileHash(filePath); } [Fact] - public void should_provide_the_correct_hash_based_on_a_checksum() + public void Should_provide_the_correct_hash_based_on_a_checksum() { var expected = BitConverter.ToString(SHA256.Create().ComputeHash(File.ReadAllBytes(filePath))).Replace("-", string.Empty); diff --git a/src/chocolatey.tests.integration/infrastructure/filesystem/DotNetFileSystemSpecs.cs b/src/chocolatey.tests.integration/infrastructure/filesystem/DotNetFileSystemSpecs.cs index 49bae923e1..eb767bb164 100644 --- a/src/chocolatey.tests.integration/infrastructure/filesystem/DotNetFileSystemSpecs.cs +++ b/src/chocolatey.tests.integration/infrastructure/filesystem/DotNetFileSystemSpecs.cs @@ -50,7 +50,7 @@ public override void Context() } } - public class when_finding_paths_to_executables_with_dotNetFileSystem : DotNetFileSystemSpecsBase + public class When_finding_paths_to_executables_with_dotNetFileSystem : DotNetFileSystemSpecsBase { public override void Because() { @@ -59,8 +59,8 @@ public override void Because() [Fact] public void GetExecutablePath_should_find_existing_executable() { - FileSystem.get_executable_path("cmd").ShouldEqual( - Platform.get_platform() == PlatformType.Windows + FileSystem.GetExecutablePath("cmd").ShouldEqual( + Platform.GetPlatform() == PlatformType.Windows ? "C:\\Windows\\system32\\cmd.exe" : "cmd", StringComparer.OrdinalIgnoreCase @@ -70,8 +70,8 @@ public void GetExecutablePath_should_find_existing_executable() [Fact] public void GetExecutablePath_should_find_existing_executable_with_extension() { - FileSystem.get_executable_path("cmd.exe").ShouldEqual( - Platform.get_platform() == PlatformType.Windows + FileSystem.GetExecutablePath("cmd.exe").ShouldEqual( + Platform.GetPlatform() == PlatformType.Windows ? "c:\\windows\\system32\\cmd.exe" : "cmd.exe", StringComparer.OrdinalIgnoreCase @@ -81,23 +81,23 @@ public void GetExecutablePath_should_find_existing_executable_with_extension() [Fact] public void GetExecutablePath_should_return_same_value_when_executable_is_not_found() { - FileSystem.get_executable_path("daslakjsfdasdfwea").ShouldEqual("daslakjsfdasdfwea"); + FileSystem.GetExecutablePath("daslakjsfdasdfwea").ShouldEqual("daslakjsfdasdfwea"); } [Fact] public void GetExecutablePath_should_return_empty_string_when_value_is_null() { - FileSystem.get_executable_path(null).ShouldEqual(string.Empty); + FileSystem.GetExecutablePath(null).ShouldEqual(string.Empty); } [Fact] public void GetExecutablePath_should_return_empty_string_when_value_is_empty_string() { - FileSystem.get_executable_path(string.Empty).ShouldEqual(string.Empty); + FileSystem.GetExecutablePath(string.Empty).ShouldEqual(string.Empty); } } - public class when_doing_file_system_operations_with_dotNetFileSystem : DotNetFileSystemSpecsBase + public class When_doing_file_system_operations_with_dotNetFileSystem : DotNetFileSystemSpecsBase { public override void Context() { @@ -120,17 +120,17 @@ public override void Because() [Fact] public void GetFiles_should_return_string_array_of_files() { - FileSystem.get_files(ContextPath, "*lipsum*", SearchOption.AllDirectories).ShouldEqual(FileArray); + FileSystem.GetFiles(ContextPath, "*lipsum*", SearchOption.AllDirectories).ShouldEqual(FileArray); } [Fact] public void GetFiles_should_return_files_that_meet_the_pattern() { - string filePath = FileSystem.combine_paths(ContextPath, "chocolateyInstall.ps1"); + string filePath = FileSystem.CombinePaths(ContextPath, "chocolateyInstall.ps1"); - FileSystem.write_file(filePath, "yo"); - var actual = FileSystem.get_files(ContextPath, "chocolateyInstall.ps1", SearchOption.AllDirectories).ToList(); - FileSystem.delete_file(filePath); + FileSystem.WriteFile(filePath, "yo"); + var actual = FileSystem.GetFiles(ContextPath, "chocolateyInstall.ps1", SearchOption.AllDirectories).ToList(); + FileSystem.DeleteFile(filePath); actual.ShouldNotBeEmpty(); actual.Count().ShouldEqual(1); @@ -141,11 +141,11 @@ public void GetFiles_should_return_files_that_meet_the_pattern() [Platform(Exclude = "Mono")] public void GetFiles_should_return_files_that_meet_the_pattern_regardless_of_case() { - string filePath = FileSystem.combine_paths(ContextPath, "chocolateyInstall.ps1"); + string filePath = FileSystem.CombinePaths(ContextPath, "chocolateyInstall.ps1"); - FileSystem.write_file(filePath, "yo"); - var actual = FileSystem.get_files(ContextPath, "chocolateyinstall.ps1", SearchOption.AllDirectories).ToList(); - FileSystem.delete_file(filePath); + FileSystem.WriteFile(filePath, "yo"); + var actual = FileSystem.GetFiles(ContextPath, "chocolateyinstall.ps1", SearchOption.AllDirectories).ToList(); + FileSystem.DeleteFile(filePath); actual.ShouldNotBeEmpty(); actual.Count().ShouldEqual(1); @@ -154,195 +154,195 @@ public void GetFiles_should_return_files_that_meet_the_pattern_regardless_of_cas [Fact] public void FileExists_should_return_true_if_file_exists() { - FileSystem.file_exists(TheTestFile).ShouldBeTrue(); + FileSystem.FileExists(TheTestFile).ShouldBeTrue(); } [Fact] public void FileExists_should_return_false_if_file_does_not_exists() { - FileSystem.file_exists(Path.Combine(ContextPath, "IDontExist.txt")).ShouldBeFalse(); + FileSystem.FileExists(Path.Combine(ContextPath, "IDontExist.txt")).ShouldBeFalse(); } [Fact] public void DirectoryExists_should_return_true_if_directory_exists() { - FileSystem.directory_exists(ContextPath).ShouldBeTrue(); + FileSystem.DirectoryExists(ContextPath).ShouldBeTrue(); } [Fact] public void DirectoryExists_should_return_false_if_directory_does_not_exist() { - FileSystem.directory_exists(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "IDontExist")).ShouldBeFalse(); + FileSystem.DirectoryExists(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "IDontExist")).ShouldBeFalse(); } [Fact] public void GetFileSize_should_return_correct_file_size() { - FileSystem.get_file_size(TheTestFile).ShouldEqual(5377); + FileSystem.GetFileSize(TheTestFile).ShouldEqual(5377); } [Fact] public void GetDirectories_should_return_a_string_array_with_directories() { - FileSystem.get_directories(ContextPath).ShouldEqual(DirectoryArray); + FileSystem.GetDirectories(ContextPath).ShouldEqual(DirectoryArray); } } [WindowsOnly] [Platform(Exclude = "Mono")] - public class when_setting_file_attributes_with_dotNetFileSystem : DotNetFileSystemSpecsBase + public class When_setting_file_attributes_with_dotNetFileSystem : DotNetFileSystemSpecsBase { public override void Context() { base.Context(); SourceFile = Path.Combine(DestinationPath, "attributes.txt"); - File.SetAttributes(SourceFile, (FileSystem.get_file_info_for(SourceFile).Attributes & ~FileAttributes.Hidden)); + File.SetAttributes(SourceFile, (FileSystem.GetFileInfoFor(SourceFile).Attributes & ~FileAttributes.Hidden)); } public override void Because() { - FileSystem.ensure_file_attribute_set(SourceFile, FileAttributes.Hidden); + FileSystem.EnsureFileAttributeSet(SourceFile, FileAttributes.Hidden); } [Fact] - public void visible_file_should_now_be_hidden() + public void Visible_file_should_now_be_hidden() { - ((FileAttributes)FileSystem.get_file_info_for(SourceFile).Attributes & FileAttributes.Hidden).ShouldEqual(FileAttributes.Hidden); + ((FileAttributes)FileSystem.GetFileInfoFor(SourceFile).Attributes & FileAttributes.Hidden).ShouldEqual(FileAttributes.Hidden); } public override void AfterObservations() { base.AfterObservations(); - File.SetAttributes(SourceFile, (FileSystem.get_file_info_for(SourceFile).Attributes & ~FileAttributes.Hidden)); + File.SetAttributes(SourceFile, (FileSystem.GetFileInfoFor(SourceFile).Attributes & ~FileAttributes.Hidden)); } } - public class when_removing_readonly_attributes_with_dotNetFileSystem : DotNetFileSystemSpecsBase + public class When_removing_readonly_attributes_with_dotNetFileSystem : DotNetFileSystemSpecsBase { public override void Context() { base.Context(); SourceFile = Path.Combine(DestinationPath, "attributes.txt"); - File.SetAttributes(SourceFile, (FileSystem.get_file_info_for(SourceFile).Attributes | FileAttributes.ReadOnly)); + File.SetAttributes(SourceFile, (FileSystem.GetFileInfoFor(SourceFile).Attributes | FileAttributes.ReadOnly)); } public override void Because() { - FileSystem.ensure_file_attribute_removed(SourceFile, FileAttributes.ReadOnly); + FileSystem.EnsureFileAttributeRemoved(SourceFile, FileAttributes.ReadOnly); } [Fact] - public void readonly_file_should_no_longer_be_readonly() + public void Readonly_file_should_no_longer_be_readonly() { - ((FileAttributes)FileSystem.get_file_info_for(SourceFile).Attributes & FileAttributes.ReadOnly).ShouldNotEqual(FileAttributes.ReadOnly); + ((FileAttributes)FileSystem.GetFileInfoFor(SourceFile).Attributes & FileAttributes.ReadOnly).ShouldNotEqual(FileAttributes.ReadOnly); } } - public class when_running_fileMove_with_dotNetFileSystem : DotNetFileSystemSpecsBase + public class When_running_fileMove_with_dotNetFileSystem : DotNetFileSystemSpecsBase { public override void Because() { SourceFile = Path.Combine(ContextPath, "MoveMe.txt"); DestFile = Path.Combine(DestinationPath, "MoveMe.txt"); - if (!FileSystem.file_exists(SourceFile)) + if (!FileSystem.FileExists(SourceFile)) { File.Create(SourceFile); } - if (FileSystem.file_exists(DestFile)) + if (FileSystem.FileExists(DestFile)) { File.Delete(DestFile); } - FileSystem.move_file(SourceFile, DestFile); + FileSystem.MoveFile(SourceFile, DestFile); } [Fact] public void Move_me_text_file_should_not_exist_in_the_source_path() { - FileSystem.file_exists(SourceFile).ShouldBeFalse(); + FileSystem.FileExists(SourceFile).ShouldBeFalse(); } [Fact] public void Move_me_text_file_should_exist_in_destination_path() { - FileSystem.file_exists(DestFile).ShouldBeTrue(); + FileSystem.FileExists(DestFile).ShouldBeTrue(); } } - public class when_running_fileCopy_with_dotNetFileSystem : DotNetFileSystemSpecsBase + public class When_running_fileCopy_with_dotNetFileSystem : DotNetFileSystemSpecsBase { public override void Because() { SourceFile = Path.Combine(ContextPath, "CopyMe.txt"); DestFile = Path.Combine(DestinationPath, "CopyMe.txt"); - if (!FileSystem.file_exists(SourceFile)) + if (!FileSystem.FileExists(SourceFile)) { File.Create(SourceFile); } - if (FileSystem.file_exists(DestFile)) + if (FileSystem.FileExists(DestFile)) { File.Delete(DestFile); } //Copy File - FileSystem.copy_file(SourceFile, DestFile, true); + FileSystem.CopyFile(SourceFile, DestFile, true); //Overwrite File - FileSystem.copy_file(SourceFile, DestFile, true); + FileSystem.CopyFile(SourceFile, DestFile, true); } [Fact] public void Copy_me_text_file_should_exist_in_context_path() { - FileSystem.file_exists(SourceFile).ShouldBeTrue(); + FileSystem.FileExists(SourceFile).ShouldBeTrue(); } [Fact] public void Move_me_text_file_should_exist_in_destination_path() { - FileSystem.file_exists(DestFile).ShouldBeTrue(); + FileSystem.FileExists(DestFile).ShouldBeTrue(); } } - public class when_running_fileDelete_with_dotNetFileSystem : DotNetFileSystemSpecsBase + public class When_running_fileDelete_with_dotNetFileSystem : DotNetFileSystemSpecsBase { public override void Because() { DeleteFile = Path.Combine(DestinationPath, "DeleteMe.txt"); - if (!FileSystem.file_exists(DeleteFile)) + if (!FileSystem.FileExists(DeleteFile)) { using (File.Create(DeleteFile)) { } } - FileSystem.delete_file(DeleteFile); + FileSystem.DeleteFile(DeleteFile); } [Fact] - public void delete_me_text_file_should_not_exist() + public void Delete_me_text_file_should_not_exist() { - FileSystem.file_exists(DeleteFile).ShouldBeFalse(); + FileSystem.FileExists(DeleteFile).ShouldBeFalse(); } } - public class when_running_createDirectory_with_dotNetFileSystem : DotNetFileSystemSpecsBase + public class When_running_createDirectory_with_dotNetFileSystem : DotNetFileSystemSpecsBase { public override void Because() { - if (FileSystem.directory_exists(TestDirectory)) + if (FileSystem.DirectoryExists(TestDirectory)) { Directory.Delete(TestDirectory, recursive: true); } - FileSystem.create_directory(TestDirectory); + FileSystem.CreateDirectory(TestDirectory); } [Fact] - public void test_directory_should_exist() + public void Test_directory_should_exist() { - FileSystem.directory_exists(TestDirectory).ShouldBeTrue(); + FileSystem.DirectoryExists(TestDirectory).ShouldBeTrue(); } } - public class when_running_getFileModDate_with_dotNetFileSystem : DotNetFileSystemSpecsBase + public class When_running_getFileModDate_with_dotNetFileSystem : DotNetFileSystemSpecsBase { public override void Because() { @@ -351,9 +351,9 @@ public override void Because() } [Fact] - public void should_have_correct_modified_date() + public void Should_have_correct_modified_date() { - FileSystem.get_file_modified_date(TheTestFile).ToShortDateString().ShouldEqual(DateTime.Now.AddDays(-1).ToShortDateString()); + FileSystem.GetFileModifiedDate(TheTestFile).ToShortDateString().ShouldEqual(DateTime.Now.AddDays(-1).ToShortDateString()); } } } diff --git a/src/chocolatey.tests.integration/packages.config b/src/chocolatey.tests.integration/packages.config index 59b471d0ea..2db5b9d29b 100644 --- a/src/chocolatey.tests.integration/packages.config +++ b/src/chocolatey.tests.integration/packages.config @@ -1,11 +1,11 @@  - - - - - - + + + + + + diff --git a/src/chocolatey.tests.integration/scenarios/InfoScenarios.cs b/src/chocolatey.tests.integration/scenarios/InfoScenarios.cs index cf30c90a4e..89f0bb94e6 100644 --- a/src/chocolatey.tests.integration/scenarios/InfoScenarios.cs +++ b/src/chocolatey.tests.integration/scenarios/InfoScenarios.cs @@ -39,9 +39,9 @@ public override void Context() public override void Because() { - MockLogger.reset(); + MockLogger.Reset(); // There is no info run. It is purely listing with verbose and exact set to true - Results = Service.list_run(Configuration).ToList(); + Results = Service.List(Configuration).ToList(); } } @@ -62,13 +62,13 @@ public override void Context() public override void Because() { - MockLogger.reset(); + MockLogger.Reset(); - Command.run(Configuration); + Command.Run(Configuration); } } - public class when_searching_for_exact_package_through_command : CommandScenariosBase + public class When_searching_for_exact_package_through_command : CommandScenariosBase { public override void Context() { @@ -81,31 +81,31 @@ public override void Context() } [Fact] - public void should_log_standalone_header_with_package_name_and_version() + public void Should_log_standalone_header_with_package_name_and_version() { - MockLogger.Messages.Keys.ShouldContain(LogLevel.Info.to_string()); - MockLogger.Messages[LogLevel.Info.to_string()].ShouldContain("installpackage 1.0.0"); + MockLogger.Messages.Keys.ShouldContain(LogLevel.Info.ToStringSafe()); + MockLogger.Messages[LogLevel.Info.ToStringSafe()].ShouldContain("installpackage 1.0.0"); } [Fact] - public void should_log_package_information() + public void Should_log_package_information() { var lastWriteDate = File.GetLastWriteTimeUtc(Path.Combine("PackageOutput", "installpackage.1.0.0" + NuGetConstants.PackageExtension)) .ToShortDateString(); - MockLogger.Messages.Keys.ShouldContain(LogLevel.Info.to_string()); - MockLogger.Messages[LogLevel.Info.to_string()].ShouldContain(" Title: installpackage | Published: {0}\r\n Number of Downloads: n/a | Downloads for this version: n/a\r\n Package url\r\n Chocolatey Package Source: n/a\r\n Tags: installpackage admin\r\n Software Site: n/a\r\n Software License: n/a\r\n Summary: __REPLACE__\r\n Description: __REPLACE__\r\n".format_with(lastWriteDate)); + MockLogger.Messages.Keys.ShouldContain(LogLevel.Info.ToStringSafe()); + MockLogger.Messages[LogLevel.Info.ToStringSafe()].ShouldContain(" Title: installpackage | Published: {0}\r\n Number of Downloads: n/a | Downloads for this version: n/a\r\n Package url\r\n Chocolatey Package Source: n/a\r\n Tags: installpackage admin\r\n Software Site: n/a\r\n Software License: n/a\r\n Summary: __REPLACE__\r\n Description: __REPLACE__\r\n".FormatWith(lastWriteDate)); } [Fact] - public void should_log_package_count_as_warning() + public void Should_log_package_count_as_warning() { - MockLogger.Messages.Keys.ShouldContain(LogLevel.Warn.to_string()); - MockLogger.Messages[LogLevel.Warn.to_string()].ShouldContain("1 packages found."); + MockLogger.Messages.Keys.ShouldContain(LogLevel.Warn.ToStringSafe()); + MockLogger.Messages[LogLevel.Warn.ToStringSafe()].ShouldContain("1 packages found."); } } - public class when_searching_for_exact_package_with_version_specified : CommandScenariosBase + public class When_searching_for_exact_package_with_version_specified : CommandScenariosBase { public override void Context() { @@ -120,31 +120,31 @@ public override void Context() } [Fact] - public void should_log_standalone_header_with_package_name_and_version() + public void Should_log_standalone_header_with_package_name_and_version() { - MockLogger.Messages.Keys.ShouldContain(LogLevel.Info.to_string()); - MockLogger.Messages[LogLevel.Info.to_string()].ShouldContain("installpackage 1.0.0"); + MockLogger.Messages.Keys.ShouldContain(LogLevel.Info.ToStringSafe()); + MockLogger.Messages[LogLevel.Info.ToStringSafe()].ShouldContain("installpackage 1.0.0"); } [Fact] - public void should_log_package_information() + public void Should_log_package_information() { var lastWriteDate = File.GetLastWriteTimeUtc(Path.Combine("PackageOutput", "installpackage.1.0.0" + NuGetConstants.PackageExtension)) .ToShortDateString(); - MockLogger.Messages.Keys.ShouldContain(LogLevel.Info.to_string()); - MockLogger.Messages[LogLevel.Info.to_string()].ShouldContain(" Title: installpackage | Published: {0}\r\n Number of Downloads: n/a | Downloads for this version: n/a\r\n Package url\r\n Chocolatey Package Source: n/a\r\n Tags: installpackage admin\r\n Software Site: n/a\r\n Software License: n/a\r\n Summary: __REPLACE__\r\n Description: __REPLACE__\r\n".format_with(lastWriteDate)); + MockLogger.Messages.Keys.ShouldContain(LogLevel.Info.ToStringSafe()); + MockLogger.Messages[LogLevel.Info.ToStringSafe()].ShouldContain(" Title: installpackage | Published: {0}\r\n Number of Downloads: n/a | Downloads for this version: n/a\r\n Package url\r\n Chocolatey Package Source: n/a\r\n Tags: installpackage admin\r\n Software Site: n/a\r\n Software License: n/a\r\n Summary: __REPLACE__\r\n Description: __REPLACE__\r\n".FormatWith(lastWriteDate)); } [Fact] - public void should_log_package_count_as_warning() + public void Should_log_package_count_as_warning() { - MockLogger.Messages.Keys.ShouldContain(LogLevel.Warn.to_string()); - MockLogger.Messages[LogLevel.Warn.to_string()].ShouldContain("1 packages found."); + MockLogger.Messages.Keys.ShouldContain(LogLevel.Warn.ToStringSafe()); + MockLogger.Messages[LogLevel.Warn.ToStringSafe()].ShouldContain("1 packages found."); } } - public class when_searching_for_exact_package_with_non_normalized_version_specified : CommandScenariosBase + public class When_searching_for_exact_package_with_non_normalized_version_specified : CommandScenariosBase { public override void Context() { @@ -159,34 +159,34 @@ public override void Context() } [Fact] - public void should_log_standalone_header_with_package_name_and_version() + public void Should_log_standalone_header_with_package_name_and_version() { - MockLogger.Messages.Keys.ShouldContain(LogLevel.Info.to_string()); - MockLogger.Messages[LogLevel.Info.to_string()].ShouldContain("installpackage 1.0.0"); + MockLogger.Messages.Keys.ShouldContain(LogLevel.Info.ToStringSafe()); + MockLogger.Messages[LogLevel.Info.ToStringSafe()].ShouldContain("installpackage 1.0.0"); } [Fact] - public void should_log_package_information() + public void Should_log_package_information() { var lastWriteDate = File.GetLastWriteTimeUtc(Path.Combine("PackageOutput", "installpackage.1.0.0" + NuGetConstants.PackageExtension)) .ToShortDateString(); - MockLogger.Messages.Keys.ShouldContain(LogLevel.Info.to_string()); - MockLogger.Messages[LogLevel.Info.to_string()].ShouldContain(" Title: installpackage | Published: {0}\r\n Number of Downloads: n/a | Downloads for this version: n/a\r\n Package url\r\n Chocolatey Package Source: n/a\r\n Tags: installpackage admin\r\n Software Site: n/a\r\n Software License: n/a\r\n Summary: __REPLACE__\r\n Description: __REPLACE__\r\n".format_with(lastWriteDate)); + MockLogger.Messages.Keys.ShouldContain(LogLevel.Info.ToStringSafe()); + MockLogger.Messages[LogLevel.Info.ToStringSafe()].ShouldContain(" Title: installpackage | Published: {0}\r\n Number of Downloads: n/a | Downloads for this version: n/a\r\n Package url\r\n Chocolatey Package Source: n/a\r\n Tags: installpackage admin\r\n Software Site: n/a\r\n Software License: n/a\r\n Summary: __REPLACE__\r\n Description: __REPLACE__\r\n".FormatWith(lastWriteDate)); } [Fact] - public void should_log_package_count_as_warning() + public void Should_log_package_count_as_warning() { - MockLogger.Messages.Keys.ShouldContain(LogLevel.Warn.to_string()); - MockLogger.Messages[LogLevel.Warn.to_string()].ShouldContain("1 packages found."); + MockLogger.Messages.Keys.ShouldContain(LogLevel.Warn.ToStringSafe()); + MockLogger.Messages[LogLevel.Warn.ToStringSafe()].ShouldContain("1 packages found."); } } - public class when_searching_for_non_normalized_exact_package : CommandScenariosBase + public class When_searching_for_non_normalized_exact_package : CommandScenariosBase { - private string NonNormalizedVersion = "004.0.01.0"; - private string NormalizedVersion = "4.0.1"; + private const string NonNormalizedVersion = "004.0.01.0"; + private const string NormalizedVersion = "4.0.1"; public override void Context() { @@ -200,34 +200,34 @@ public override void Context() } [Fact] - public void should_log_standalone_header_with_package_name_and_version() + public void Should_log_standalone_header_with_package_name_and_version() { - MockLogger.Messages.Keys.ShouldContain(LogLevel.Info.to_string()); - MockLogger.Messages[LogLevel.Info.to_string()].ShouldContain("installpackage {0}".format_with(NormalizedVersion)); + MockLogger.Messages.Keys.ShouldContain(LogLevel.Info.ToStringSafe()); + MockLogger.Messages[LogLevel.Info.ToStringSafe()].ShouldContain("installpackage {0}".FormatWith(NormalizedVersion)); } [Fact] - public void should_log_package_information() + public void Should_log_package_information() { - var lastWriteDate = File.GetLastWriteTimeUtc(Path.Combine("PackageOutput", "installpackage.{0}".format_with(NonNormalizedVersion) + NuGetConstants.PackageExtension)) + var lastWriteDate = File.GetLastWriteTimeUtc(Path.Combine("PackageOutput", "installpackage.{0}".FormatWith(NonNormalizedVersion) + NuGetConstants.PackageExtension)) .ToShortDateString(); - MockLogger.Messages.Keys.ShouldContain(LogLevel.Info.to_string()); - MockLogger.Messages[LogLevel.Info.to_string()].ShouldContain(" Title: installpackage | Published: {0}\r\n Number of Downloads: n/a | Downloads for this version: n/a\r\n Package url\r\n Chocolatey Package Source: n/a\r\n Tags: installpackage admin\r\n Software Site: n/a\r\n Software License: n/a\r\n Summary: __REPLACE__\r\n Description: __REPLACE__\r\n".format_with(lastWriteDate)); + MockLogger.Messages.Keys.ShouldContain(LogLevel.Info.ToStringSafe()); + MockLogger.Messages[LogLevel.Info.ToStringSafe()].ShouldContain(" Title: installpackage | Published: {0}\r\n Number of Downloads: n/a | Downloads for this version: n/a\r\n Package url\r\n Chocolatey Package Source: n/a\r\n Tags: installpackage admin\r\n Software Site: n/a\r\n Software License: n/a\r\n Summary: __REPLACE__\r\n Description: __REPLACE__\r\n".FormatWith(lastWriteDate)); } [Fact] - public void should_log_package_count_as_warning() + public void Should_log_package_count_as_warning() { - MockLogger.Messages.Keys.ShouldContain(LogLevel.Warn.to_string()); - MockLogger.Messages[LogLevel.Warn.to_string()].ShouldContain("1 packages found."); + MockLogger.Messages.Keys.ShouldContain(LogLevel.Warn.ToStringSafe()); + MockLogger.Messages[LogLevel.Warn.ToStringSafe()].ShouldContain("1 packages found."); } } - public class when_searching_for_non_normalized_exact_package_with_version_specified : CommandScenariosBase + public class When_searching_for_non_normalized_exact_package_with_version_specified : CommandScenariosBase { - private string NonNormalizedVersion = "004.0.01.0"; - private string NormalizedVersion = "4.0.1"; + private const string NonNormalizedVersion = "004.0.01.0"; + private const string NormalizedVersion = "4.0.1"; public override void Context() { @@ -243,34 +243,34 @@ public override void Context() } [Fact] - public void should_log_standalone_header_with_package_name_and_version() + public void Should_log_standalone_header_with_package_name_and_version() { - MockLogger.Messages.Keys.ShouldContain(LogLevel.Info.to_string()); - MockLogger.Messages[LogLevel.Info.to_string()].ShouldContain("installpackage {0}".format_with(NormalizedVersion)); + MockLogger.Messages.Keys.ShouldContain(LogLevel.Info.ToStringSafe()); + MockLogger.Messages[LogLevel.Info.ToStringSafe()].ShouldContain("installpackage {0}".FormatWith(NormalizedVersion)); } [Fact] - public void should_log_package_information() + public void Should_log_package_information() { - var lastWriteDate = File.GetLastWriteTimeUtc(Path.Combine("PackageOutput", "installpackage.{0}".format_with(NonNormalizedVersion) + NuGetConstants.PackageExtension)) + var lastWriteDate = File.GetLastWriteTimeUtc(Path.Combine("PackageOutput", "installpackage.{0}".FormatWith(NonNormalizedVersion) + NuGetConstants.PackageExtension)) .ToShortDateString(); - MockLogger.Messages.Keys.ShouldContain(LogLevel.Info.to_string()); - MockLogger.Messages[LogLevel.Info.to_string()].ShouldContain(" Title: installpackage | Published: {0}\r\n Number of Downloads: n/a | Downloads for this version: n/a\r\n Package url\r\n Chocolatey Package Source: n/a\r\n Tags: installpackage admin\r\n Software Site: n/a\r\n Software License: n/a\r\n Summary: __REPLACE__\r\n Description: __REPLACE__\r\n".format_with(lastWriteDate)); + MockLogger.Messages.Keys.ShouldContain(LogLevel.Info.ToStringSafe()); + MockLogger.Messages[LogLevel.Info.ToStringSafe()].ShouldContain(" Title: installpackage | Published: {0}\r\n Number of Downloads: n/a | Downloads for this version: n/a\r\n Package url\r\n Chocolatey Package Source: n/a\r\n Tags: installpackage admin\r\n Software Site: n/a\r\n Software License: n/a\r\n Summary: __REPLACE__\r\n Description: __REPLACE__\r\n".FormatWith(lastWriteDate)); } [Fact] - public void should_log_package_count_as_warning() + public void Should_log_package_count_as_warning() { - MockLogger.Messages.Keys.ShouldContain(LogLevel.Warn.to_string()); - MockLogger.Messages[LogLevel.Warn.to_string()].ShouldContain("1 packages found."); + MockLogger.Messages.Keys.ShouldContain(LogLevel.Warn.ToStringSafe()); + MockLogger.Messages[LogLevel.Warn.ToStringSafe()].ShouldContain("1 packages found."); } } - public class when_searching_for_non_normalized_exact_package_with_non_normalized_version_specified : CommandScenariosBase + public class When_searching_for_non_normalized_exact_package_with_non_normalized_version_specified : CommandScenariosBase { - private string NonNormalizedVersion = "004.0.01.0"; - private string NormalizedVersion = "4.0.1"; + private const string NonNormalizedVersion = "004.0.01.0"; + private const string NormalizedVersion = "4.0.1"; public override void Context() { @@ -286,31 +286,31 @@ public override void Context() } [Fact] - public void should_log_standalone_header_with_package_name_and_version() + public void Should_log_standalone_header_with_package_name_and_version() { - MockLogger.Messages.Keys.ShouldContain(LogLevel.Info.to_string()); - MockLogger.Messages[LogLevel.Info.to_string()].ShouldContain("installpackage {0}".format_with(NormalizedVersion)); + MockLogger.Messages.Keys.ShouldContain(LogLevel.Info.ToStringSafe()); + MockLogger.Messages[LogLevel.Info.ToStringSafe()].ShouldContain("installpackage {0}".FormatWith(NormalizedVersion)); } [Fact] - public void should_log_package_information() + public void Should_log_package_information() { - var lastWriteDate = File.GetLastWriteTimeUtc(Path.Combine("PackageOutput", "installpackage.{0}".format_with(NonNormalizedVersion) + NuGetConstants.PackageExtension)) + var lastWriteDate = File.GetLastWriteTimeUtc(Path.Combine("PackageOutput", "installpackage.{0}".FormatWith(NonNormalizedVersion) + NuGetConstants.PackageExtension)) .ToShortDateString(); - MockLogger.Messages.Keys.ShouldContain(LogLevel.Info.to_string()); - MockLogger.Messages[LogLevel.Info.to_string()].ShouldContain(" Title: installpackage | Published: {0}\r\n Number of Downloads: n/a | Downloads for this version: n/a\r\n Package url\r\n Chocolatey Package Source: n/a\r\n Tags: installpackage admin\r\n Software Site: n/a\r\n Software License: n/a\r\n Summary: __REPLACE__\r\n Description: __REPLACE__\r\n".format_with(lastWriteDate)); + MockLogger.Messages.Keys.ShouldContain(LogLevel.Info.ToStringSafe()); + MockLogger.Messages[LogLevel.Info.ToStringSafe()].ShouldContain(" Title: installpackage | Published: {0}\r\n Number of Downloads: n/a | Downloads for this version: n/a\r\n Package url\r\n Chocolatey Package Source: n/a\r\n Tags: installpackage admin\r\n Software Site: n/a\r\n Software License: n/a\r\n Summary: __REPLACE__\r\n Description: __REPLACE__\r\n".FormatWith(lastWriteDate)); } [Fact] - public void should_log_package_count_as_warning() + public void Should_log_package_count_as_warning() { - MockLogger.Messages.Keys.ShouldContain(LogLevel.Warn.to_string()); - MockLogger.Messages[LogLevel.Warn.to_string()].ShouldContain("1 packages found."); + MockLogger.Messages.Keys.ShouldContain(LogLevel.Warn.ToStringSafe()); + MockLogger.Messages[LogLevel.Warn.ToStringSafe()].ShouldContain("1 packages found."); } } - public class when_searching_for_exact_package_with_dot_relative_path_source : when_searching_for_exact_package_through_command + public class When_searching_for_exact_package_with_dot_relative_path_source : When_searching_for_exact_package_through_command { public override void Context() { @@ -334,31 +334,31 @@ public override void Because() } [Fact] - public new void should_log_standalone_header_with_package_name_and_version() + public new void Should_log_standalone_header_with_package_name_and_version() { - MockLogger.Messages.Keys.ShouldContain(LogLevel.Info.to_string()); - MockLogger.Messages[LogLevel.Info.to_string()].ShouldContain("installpackage 1.0.0"); + MockLogger.Messages.Keys.ShouldContain(LogLevel.Info.ToStringSafe()); + MockLogger.Messages[LogLevel.Info.ToStringSafe()].ShouldContain("installpackage 1.0.0"); } [Fact] - public new void should_log_package_information() + public new void Should_log_package_information() { var lastWriteDate = File.GetLastWriteTimeUtc(Path.Combine("PackageOutput", "installpackage.1.0.0" + NuGetConstants.PackageExtension)) .ToShortDateString(); - MockLogger.Messages.Keys.ShouldContain(LogLevel.Info.to_string()); - MockLogger.Messages[LogLevel.Info.to_string()].ShouldContain(" Title: installpackage | Published: {0}\r\n Number of Downloads: n/a | Downloads for this version: n/a\r\n Package url\r\n Chocolatey Package Source: n/a\r\n Tags: installpackage admin\r\n Software Site: n/a\r\n Software License: n/a\r\n Summary: __REPLACE__\r\n Description: __REPLACE__\r\n".format_with(lastWriteDate)); + MockLogger.Messages.Keys.ShouldContain(LogLevel.Info.ToStringSafe()); + MockLogger.Messages[LogLevel.Info.ToStringSafe()].ShouldContain(" Title: installpackage | Published: {0}\r\n Number of Downloads: n/a | Downloads for this version: n/a\r\n Package url\r\n Chocolatey Package Source: n/a\r\n Tags: installpackage admin\r\n Software Site: n/a\r\n Software License: n/a\r\n Summary: __REPLACE__\r\n Description: __REPLACE__\r\n".FormatWith(lastWriteDate)); } [Fact] - public new void should_log_package_count_as_warning() + public new void Should_log_package_count_as_warning() { - MockLogger.Messages.Keys.ShouldContain(LogLevel.Warn.to_string()); - MockLogger.Messages[LogLevel.Warn.to_string()].ShouldContain("1 packages found."); + MockLogger.Messages.Keys.ShouldContain(LogLevel.Warn.ToStringSafe()); + MockLogger.Messages[LogLevel.Warn.ToStringSafe()].ShouldContain("1 packages found."); } } - public class when_searching_for_exact_package_with_verbose_output : ScenariosBase + public class When_searching_for_exact_package_with_verbose_output : ScenariosBase { public override void Context() { @@ -370,46 +370,46 @@ public override void Context() } [Fact] - public void should_show_only_one_result() + public void Should_show_only_one_result() { Results.Count.ShouldEqual(1, "Expected 1 package to be returned!"); } [Fact] - public void should_set_exit_code_to_zero() + public void Should_set_exit_code_to_zero() { Results[0].ExitCode.ShouldEqual(0); } [Fact] - public void should_not_be_reported_as_inconclusive() + public void Should_not_be_reported_as_inconclusive() { Results[0].Inconclusive.ShouldBeFalse(); } [Fact] - public void should_report_expected_name() + public void Should_report_expected_name() { Results[0].Name.ShouldEqual("installpackage"); } [Fact] - public void should_set_source_to_expected_value() + public void Should_set_source_to_expected_value() { Results[0].Source.ShouldEqual( - ((Platform.get_platform() == PlatformType.Windows ? "file:///" : "file://") + Path.Combine(Environment.CurrentDirectory, "PackageOutput")) + ((Platform.GetPlatform() == PlatformType.Windows ? "file:///" : "file://") + Path.Combine(Environment.CurrentDirectory, "PackageOutput")) .Replace("\\","/")); } [Fact] - public void should_set_expected_version() + public void Should_set_expected_version() { Results[0].Version.ShouldEqual("1.0.0"); } } [Categories.SourcePriority] - public class when_searching_for_a_package_in_a_priority_source : ScenariosBase + public class When_searching_for_a_package_in_a_priority_source : ScenariosBase { public override void Context() { @@ -420,31 +420,31 @@ public override void Context() } [Fact] - public void should_show_only_one_result() + public void Should_show_only_one_result() { Results.Count.ShouldEqual(1, "Expected 1 package to be returned!"); } [Fact] - public void should_set_exit_code_to_zero() + public void Should_set_exit_code_to_zero() { Results[0].ExitCode.ShouldEqual(0); } [Fact] - public void should_not_be_reported_as_inconclusive() + public void Should_not_be_reported_as_inconclusive() { Results[0].Inconclusive.ShouldBeFalse(); } [Fact] - public void should_report_expected_name() + public void Should_report_expected_name() { Results[0].Name.ShouldEqual("test-package"); } [Fact] - public void should_set_source_to_expected_value() + public void Should_set_source_to_expected_value() { var expectedSource = "file:///" + Path.Combine( Scenario.get_top_level(), @@ -455,14 +455,14 @@ public void should_set_source_to_expected_value() } [Fact] - public void should_set_expected_version() + public void Should_set_expected_version() { Results[0].Version.ShouldEqual("0.1.0"); } } [Categories.SourcePriority] - public class when_searching_for_a_package_in_and_prioritised_source_has_lower_version : ScenariosBase + public class When_searching_for_a_package_in_and_prioritised_source_has_lower_version : ScenariosBase { public override void Context() { @@ -476,31 +476,31 @@ public override void Context() } [Fact] - public void should_show_only_one_result() + public void Should_show_only_one_result() { Results.Count.ShouldEqual(1, "Expected 1 package to be returned!"); } [Fact] - public void should_set_exit_code_to_zero() + public void Should_set_exit_code_to_zero() { Results[0].ExitCode.ShouldEqual(0); } [Fact] - public void should_not_be_reported_as_inconclusive() + public void Should_not_be_reported_as_inconclusive() { Results[0].Inconclusive.ShouldBeFalse(); } [Fact] - public void should_report_expected_name() + public void Should_report_expected_name() { Results[0].Name.ShouldEqual("upgradepackage"); } [Fact] - public void should_set_source_to_expected_value() + public void Should_set_source_to_expected_value() { var expectedSource = "file:///" + Path.Combine( Scenario.get_top_level(), @@ -511,7 +511,7 @@ public void should_set_source_to_expected_value() } [Fact] - public void should_set_expected_version() + public void Should_set_expected_version() { Results[0].Version.ShouldEqual("1.0.0"); } diff --git a/src/chocolatey.tests.integration/scenarios/InstallScenarios.cs b/src/chocolatey.tests.integration/scenarios/InstallScenarios.cs index 8e3b83ea73..674e860890 100644 --- a/src/chocolatey.tests.integration/scenarios/InstallScenarios.cs +++ b/src/chocolatey.tests.integration/scenarios/InstallScenarios.cs @@ -59,7 +59,7 @@ public override void Context() } } - public class when_noop_installing_a_package : ScenariosBase + public class When_noop_installing_a_package : ScenariosBase { public override void Context() { @@ -69,11 +69,11 @@ public override void Context() public override void Because() { - Service.install_noop(Configuration); + Service.InstallDryRun(Configuration); } [Fact] - public void should_not_install_a_package_in_the_lib_directory() + public void Should_not_install_a_package_in_the_lib_directory() { var packageDir = Path.Combine(Scenario.get_top_level(), "lib", Configuration.PackageNames); @@ -81,10 +81,10 @@ public void should_not_install_a_package_in_the_lib_directory() } [Fact] - public void should_contain_a_message_that_it_would_have_used_Nuget_to_install_a_package() + public void Should_contain_a_message_that_it_would_have_used_Nuget_to_install_a_package() { bool expectedMessage = false; - foreach (var message in MockLogger.MessagesFor(LogLevel.Info).or_empty_list_if_null()) + foreach (var message in MockLogger.MessagesFor(LogLevel.Info).OrEmpty()) { if (message.Contains("would have used NuGet to install packages")) expectedMessage = true; } @@ -95,19 +95,19 @@ public void should_contain_a_message_that_it_would_have_used_Nuget_to_install_a_ [Fact] [WindowsOnly] [Platform(Exclude = "Mono")] - public void should_contain_a_message_that_it_would_have_run_a_powershell_script() + public void Should_contain_a_message_that_it_would_have_run_a_powershell_script() { - MockLogger.contains_message("chocolateyinstall.ps1", LogLevel.Info).ShouldBeTrue(); + MockLogger.ContainsMessage("chocolateyinstall.ps1", LogLevel.Info).ShouldBeTrue(); } [Fact] - public void should_not_contain_a_message_that_it_would_have_run_powershell_modification_script() + public void Should_not_contain_a_message_that_it_would_have_run_powershell_modification_script() { - MockLogger.contains_message("chocolateyBeforeModify.ps1", LogLevel.Info).ShouldBeFalse(); + MockLogger.ContainsMessage("chocolateyBeforeModify.ps1", LogLevel.Info).ShouldBeFalse(); } } - public class when_noop_installing_a_package_that_does_not_exist : ScenariosBase + public class When_noop_installing_a_package_that_does_not_exist : ScenariosBase { public override void Context() { @@ -118,11 +118,11 @@ public override void Context() public override void Because() { - Service.install_noop(Configuration); + Service.InstallDryRun(Configuration); } [Fact] - public void should_not_install_a_package_in_the_lib_directory() + public void Should_not_install_a_package_in_the_lib_directory() { var packageDir = Path.Combine(Scenario.get_top_level(), "lib", Configuration.PackageNames); @@ -130,10 +130,10 @@ public void should_not_install_a_package_in_the_lib_directory() } [Fact] - public void should_contain_a_message_that_it_would_have_used_Nuget_to_install_a_package() + public void Should_contain_a_message_that_it_would_have_used_Nuget_to_install_a_package() { bool expectedMessage = false; - foreach (var message in MockLogger.MessagesFor(LogLevel.Info).or_empty_list_if_null()) + foreach (var message in MockLogger.MessagesFor(LogLevel.Info).OrEmpty()) { if (message.Contains("would have used NuGet to install packages")) expectedMessage = true; } @@ -142,10 +142,10 @@ public void should_contain_a_message_that_it_would_have_used_Nuget_to_install_a_ } [Fact] - public void should_contain_a_message_that_it_was_unable_to_find_package() + public void Should_contain_a_message_that_it_was_unable_to_find_package() { bool expectedMessage = false; - foreach (var message in MockLogger.MessagesFor(LogLevel.Error).or_empty_list_if_null()) + foreach (var message in MockLogger.MessagesFor(LogLevel.Error).OrEmpty()) { if (message.Contains("somethingnonexisting not installed. The package was not found with the source(s) listed")) expectedMessage = true; } @@ -154,7 +154,7 @@ public void should_contain_a_message_that_it_was_unable_to_find_package() } } - public class when_installing_a_package_happy_path : ScenariosBase + public class When_installing_a_package_happy_path : ScenariosBase { private PackageResult packageResult; @@ -172,18 +172,18 @@ public override void Context() public override void Because() { - Results = Service.install_run(Configuration); + Results = Service.Install(Configuration); packageResult = Results.FirstOrDefault().Value; } [Fact] - public void should_install_where_install_location_reports() + public void Should_install_where_install_location_reports() { DirectoryAssert.Exists(packageResult.InstallLocation); } [Fact] - public void should_install_the_package_in_the_lib_directory() + public void Should_install_the_package_in_the_lib_directory() { var packageDir = Path.Combine(Scenario.get_top_level(), "lib", Configuration.PackageNames); @@ -191,19 +191,19 @@ public void should_install_the_package_in_the_lib_directory() } [Fact] - public void should_install_the_expected_version_of_the_package() + public void Should_install_the_expected_version_of_the_package() { var packageFile = Path.Combine(Scenario.get_top_level(), "lib", Configuration.PackageNames, Configuration.PackageNames + NuGetConstants.PackageExtension); using (var packageReader = new PackageArchiveReader(packageFile)) { - packageReader.NuspecReader.GetVersion().to_string().ShouldEqual(TestVersion()); + packageReader.NuspecReader.GetVersion().ToStringSafe().ShouldEqual(TestVersion()); } } [Fact] [WindowsOnly] [Platform(Exclude = "Mono")] - public void should_create_a_shim_for_console_in_the_bin_directory() + public void Should_create_a_shim_for_console_in_the_bin_directory() { var shimfile = Path.Combine(Scenario.get_top_level(), "bin", "console.exe"); @@ -213,7 +213,7 @@ public void should_create_a_shim_for_console_in_the_bin_directory() [Fact] [WindowsOnly] [Platform(Exclude = "Mono")] - public void should_create_a_shim_for_graphical_in_the_bin_directory() + public void Should_create_a_shim_for_graphical_in_the_bin_directory() { var shimfile = Path.Combine(Scenario.get_top_level(), "bin", "graphical.exe"); @@ -221,7 +221,7 @@ public void should_create_a_shim_for_graphical_in_the_bin_directory() } [Fact] - public void should_not_create_a_shim_for_ignored_executable_in_the_bin_directory() + public void Should_not_create_a_shim_for_ignored_executable_in_the_bin_directory() { var shimfile = Path.Combine(Scenario.get_top_level(), "bin", "not.installed.exe"); @@ -229,7 +229,7 @@ public void should_not_create_a_shim_for_ignored_executable_in_the_bin_directory } [Fact] - public void should_not_create_a_shim_for_mismatched_case_ignored_executable_in_the_bin_directory() + public void Should_not_create_a_shim_for_mismatched_case_ignored_executable_in_the_bin_directory() { var shimfile = Path.Combine(Scenario.get_top_level(), "bin", "casemismatch.exe"); @@ -237,7 +237,7 @@ public void should_not_create_a_shim_for_mismatched_case_ignored_executable_in_t } [Fact] - public void should_not_create_an_extensions_folder_for_the_package() + public void Should_not_create_an_extensions_folder_for_the_package() { var extensionsDirectory = Path.Combine(Scenario.get_top_level(), "extensions", Configuration.PackageNames); @@ -245,7 +245,7 @@ public void should_not_create_an_extensions_folder_for_the_package() } [Fact] - public void should_not_create_an_hooks_folder_for_the_package() + public void Should_not_create_an_hooks_folder_for_the_package() { var hooksDirectory = Path.Combine(Scenario.get_top_level(), "hooks", Configuration.PackageNames); @@ -255,12 +255,12 @@ public void should_not_create_an_hooks_folder_for_the_package() [Fact] [WindowsOnly] [Platform(Exclude = "Mono")] - public void should_have_a_console_shim_that_is_set_for_non_gui_access() + public void Should_have_a_console_shim_that_is_set_for_non_gui_access() { var messages = new List(); var shimfile = Path.Combine(Scenario.get_top_level(), "bin", "console.exe"); - CommandExecutor.execute( + CommandExecutor.Execute( shimfile, "--shimgen-noop", 10, @@ -270,7 +270,7 @@ public void should_have_a_console_shim_that_is_set_for_non_gui_access() var messageFound = false; - foreach (var message in messages.or_empty_list_if_null()) + foreach (var message in messages.OrEmpty()) { if (string.IsNullOrWhiteSpace(message)) continue; if (message.Contains("is gui? False")) messageFound = true; @@ -282,12 +282,12 @@ public void should_have_a_console_shim_that_is_set_for_non_gui_access() [Fact] [WindowsOnly] [Platform(Exclude = "Mono")] - public void should_have_a_graphical_shim_that_is_set_for_gui_access() + public void Should_have_a_graphical_shim_that_is_set_for_gui_access() { var messages = new List(); var shimfile = Path.Combine(Scenario.get_top_level(), "bin", "graphical.exe"); - CommandExecutor.execute( + CommandExecutor.Execute( shimfile, "--shimgen-noop", 10, @@ -297,7 +297,7 @@ public void should_have_a_graphical_shim_that_is_set_for_gui_access() var messageFound = false; - foreach (var message in messages.or_empty_list_if_null()) + foreach (var message in messages.OrEmpty()) { if (string.IsNullOrWhiteSpace(message)) continue; if (message.Contains("is gui? True")) messageFound = true; @@ -307,10 +307,10 @@ public void should_have_a_graphical_shim_that_is_set_for_gui_access() } [Fact] - public void should_contain_a_warning_message_that_it_installed_successfully() + public void Should_contain_a_warning_message_that_it_installed_successfully() { bool installedSuccessfully = false; - foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).or_empty_list_if_null()) + foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).OrEmpty()) { if (message.Contains("1/1")) installedSuccessfully = true; } @@ -319,31 +319,31 @@ public void should_contain_a_warning_message_that_it_installed_successfully() } [Fact] - public void should_have_a_successful_package_result() + public void Should_have_a_successful_package_result() { packageResult.Success.ShouldBeTrue(); } [Fact] - public void should_not_have_inconclusive_package_result() + public void Should_not_have_inconclusive_package_result() { packageResult.Inconclusive.ShouldBeFalse(); } [Fact] - public void should_not_have_warning_package_result() + public void Should_not_have_warning_package_result() { packageResult.Warning.ShouldBeFalse(); } [Fact] - public void config_should_match_package_result_name() + public void Config_should_match_package_result_name() { packageResult.Name.ShouldEqual(Configuration.PackageNames); } [Fact] - public void should_have_a_version_of_one_dot_zero_dot_zero() + public void Should_have_a_version_of_one_dot_zero_dot_zero() { packageResult.Version.ShouldEqual(TestVersion()); } @@ -351,11 +351,11 @@ public void should_have_a_version_of_one_dot_zero_dot_zero() [Fact] [WindowsOnly] [Platform(Exclude = "Mono")] - public void should_have_executed_chocolateyInstall_script() + public void Should_have_executed_chocolateyInstall_script() { - var message = "installpackage v{0} has been installed".format_with(TestVersion()); + var message = "installpackage v{0} has been installed".FormatWith(TestVersion()); - MockLogger.contains_message(message, LogLevel.Info).ShouldBeTrue(); + MockLogger.ContainsMessage(message, LogLevel.Info).ShouldBeTrue(); } protected string TestVersion() @@ -372,23 +372,23 @@ protected string TestVersion() } [Categories.SemVer20] - public class when_installing_a_package_with_semver_2_0_meta_data : when_installing_a_package_happy_path + public class When_installing_a_package_with_semver_2_0_meta_data : When_installing_a_package_happy_path { protected override string TestSemVersion => "0.9.9+build.543"; } [Categories.SemVer20] - public class when_installing_a_package_with_semver_2_0_pre_release_tag : when_installing_a_package_happy_path + public class When_installing_a_package_with_semver_2_0_pre_release_tag : When_installing_a_package_happy_path { protected override string TestSemVersion => "1.0.0-alpha.34"; } - public class when_installing_packages_with_packages_config : ScenariosBase + public class When_installing_packages_with_packages_config : ScenariosBase { public override void Context() { base.Context(); - var packagesConfig = "{0}{1}context{1}testing.packages.config".format_with(Scenario.get_top_level(), Path.DirectorySeparatorChar); + var packagesConfig = "{0}{1}context{1}testing.packages.config".FormatWith(Scenario.get_top_level(), Path.DirectorySeparatorChar); Configuration.PackageNames = Configuration.Input = packagesConfig; Scenario.add_packages_to_source_location(Configuration, "hasdependency.1.0.0*" + NuGetConstants.PackageExtension); Scenario.add_packages_to_source_location(Configuration, "isdependency.1.0.0*" + NuGetConstants.PackageExtension); @@ -398,22 +398,22 @@ public override void Context() public override void Because() { - Results = Service.install_run(Configuration); + Results = Service.Install(Configuration); } [Fact] - public void should_install_where_install_location_reports() + public void Should_install_where_install_location_reports() { foreach (var packageResult in Results) { - if (packageResult.Value.Name.is_equal_to("missingpackage")) continue; + if (packageResult.Value.Name.IsEqualTo("missingpackage")) continue; DirectoryAssert.Exists(packageResult.Value.InstallLocation); } } [Fact] - public void should_install_expected_packages_in_the_lib_directory() + public void Should_install_expected_packages_in_the_lib_directory() { var packagesExpected = new List { @@ -430,7 +430,7 @@ public void should_install_expected_packages_in_the_lib_directory() } [Fact] - public void should_install_the_dependency_in_the_lib_directory() + public void Should_install_the_dependency_in_the_lib_directory() { var packageDir = Path.Combine(Scenario.get_top_level(), "lib", "isdependency"); @@ -438,10 +438,10 @@ public void should_install_the_dependency_in_the_lib_directory() } [Fact] - public void should_contain_a_warning_message_that_it_installed_4_out_of_5_packages_successfully() + public void Should_contain_a_warning_message_that_it_installed_4_out_of_5_packages_successfully() { bool installedSuccessfully = false; - foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).or_empty_list_if_null()) + foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).OrEmpty()) { if (message.Contains("5/6")) installedSuccessfully = true; } @@ -450,10 +450,10 @@ public void should_contain_a_warning_message_that_it_installed_4_out_of_5_packag } [Fact] - public void should_contain_a_message_that_upgradepackage_with_an_expected_specified_version_was_installed() + public void Should_contain_a_message_that_upgradepackage_with_an_expected_specified_version_was_installed() { bool expectedMessage = false; - foreach (var message in MockLogger.MessagesFor(LogLevel.Info).or_empty_list_if_null()) + foreach (var message in MockLogger.MessagesFor(LogLevel.Info).OrEmpty()) { if (message.Contains("upgradepackage v1.0.0")) expectedMessage = true; } @@ -462,29 +462,29 @@ public void should_contain_a_message_that_upgradepackage_with_an_expected_specif } [Fact] - public void should_have_a_successful_package_result_for_all_but_expected_missing_package() + public void Should_have_a_successful_package_result_for_all_but_expected_missing_package() { foreach (var packageResult in Results) { - if (packageResult.Value.Name.is_equal_to("missingpackage")) continue; + if (packageResult.Value.Name.IsEqualTo("missingpackage")) continue; packageResult.Value.Success.ShouldBeTrue(); } } [Fact] - public void should_not_have_a_successful_package_result_for_missing_package() + public void Should_not_have_a_successful_package_result_for_missing_package() { foreach (var packageResult in Results) { - if (!packageResult.Value.Name.is_equal_to("missingpackage")) continue; + if (!packageResult.Value.Name.IsEqualTo("missingpackage")) continue; packageResult.Value.Success.ShouldBeFalse(); } } [Fact] - public void should_not_have_inconclusive_package_result() + public void Should_not_have_inconclusive_package_result() { foreach (var packageResult in Results) { @@ -493,7 +493,7 @@ public void should_not_have_inconclusive_package_result() } [Fact] - public void should_not_have_warning_package_result() + public void Should_not_have_warning_package_result() { foreach (var packageResult in Results) { @@ -502,10 +502,10 @@ public void should_not_have_warning_package_result() } [Fact] - public void should_specify_config_file_is_being_used_in_message() + public void Should_specify_config_file_is_being_used_in_message() { bool expectedMessage = false; - foreach (var message in MockLogger.MessagesFor(LogLevel.Info).or_empty_list_if_null()) + foreach (var message in MockLogger.MessagesFor(LogLevel.Info).OrEmpty()) { if (message.Contains("Installing from config file:")) expectedMessage = true; } @@ -514,10 +514,10 @@ public void should_specify_config_file_is_being_used_in_message() } [Fact] - public void should_print_out_package_from_config_file_in_message() + public void Should_print_out_package_from_config_file_in_message() { bool expectedMessage = false; - foreach (var message in MockLogger.MessagesFor(LogLevel.Info).or_empty_list_if_null()) + foreach (var message in MockLogger.MessagesFor(LogLevel.Info).OrEmpty()) { if (message.Contains("installpackage")) expectedMessage = true; } @@ -526,7 +526,7 @@ public void should_print_out_package_from_config_file_in_message() } } - public class when_installing_an_already_installed_package : ScenariosBase + public class When_installing_an_already_installed_package : ScenariosBase { private PackageResult packageResult; @@ -538,12 +538,12 @@ public override void Context() public override void Because() { - Results = Service.install_run(Configuration); + Results = Service.Install(Configuration); packageResult = Results.FirstOrDefault().Value; } [Fact] - public void should_still_have_a_package_in_the_lib_directory() + public void Should_still_have_a_package_in_the_lib_directory() { var packageDir = Path.Combine(Scenario.get_top_level(), "lib", Configuration.PackageNames); @@ -551,20 +551,20 @@ public void should_still_have_a_package_in_the_lib_directory() } [Fact] - public void should_still_have_the_expected_version_of_the_package_installed() + public void Should_still_have_the_expected_version_of_the_package_installed() { var packageFile = Path.Combine(Scenario.get_top_level(), "lib", Configuration.PackageNames, Configuration.PackageNames + NuGetConstants.PackageExtension); using (var packageReader = new PackageArchiveReader(packageFile)) { - packageReader.NuspecReader.GetVersion().to_string().ShouldEqual("1.0.0"); + packageReader.NuspecReader.GetVersion().ToStringSafe().ShouldEqual("1.0.0"); } } [Fact] - public void should_contain_a_warning_message_that_it_was_unable_to_install_any_packages() + public void Should_contain_a_warning_message_that_it_was_unable_to_install_any_packages() { bool installWarning = false; - foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).or_empty_list_if_null()) + foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).OrEmpty()) { if (message.Contains("0/1")) installWarning = true; } @@ -573,10 +573,10 @@ public void should_contain_a_warning_message_that_it_was_unable_to_install_any_p } [Fact] - public void should_contain_a_message_about_force_to_reinstall() + public void Should_contain_a_message_about_force_to_reinstall() { bool installWarning = false; - foreach (var messageType in MockLogger.Messages.or_empty_list_if_null()) + foreach (var messageType in MockLogger.Messages.OrEmpty()) { foreach (var message in messageType.Value) { @@ -588,19 +588,19 @@ public void should_contain_a_message_about_force_to_reinstall() } [Fact] - public void should_have_inconclusive_package_result() + public void Should_have_inconclusive_package_result() { packageResult.Inconclusive.ShouldBeTrue(); } [Fact] - public void should_ave_warning_package_result() + public void Should_ave_warning_package_result() { packageResult.Warning.ShouldBeTrue(); } } - public class when_force_installing_an_already_installed_package : ScenariosBase + public class When_force_installing_an_already_installed_package : ScenariosBase { private PackageResult packageResult; private readonly string modifiedText = "bob"; @@ -617,18 +617,18 @@ public override void Context() public override void Because() { - Results = Service.install_run(Configuration); + Results = Service.Install(Configuration); packageResult = Results.FirstOrDefault().Value; } [Fact] - public void should_install_where_install_location_reports() + public void Should_install_where_install_location_reports() { DirectoryAssert.Exists(packageResult.InstallLocation); } [Fact] - public void should_install_the_package_in_the_lib_directory() + public void Should_install_the_package_in_the_lib_directory() { var packageDir = Path.Combine(Scenario.get_top_level(), "lib", Configuration.PackageNames); @@ -636,24 +636,24 @@ public void should_install_the_package_in_the_lib_directory() } [Fact] - public void should_install_the_same_version_of_the_package() + public void Should_install_the_same_version_of_the_package() { var packageFile = Path.Combine(Scenario.get_top_level(), "lib", Configuration.PackageNames, Configuration.PackageNames + NuGetConstants.PackageExtension); using (var packageReader = new PackageArchiveReader(packageFile)) { - packageReader.NuspecReader.GetVersion().to_string().ShouldEqual("1.0.0"); + packageReader.NuspecReader.GetVersion().ToStringSafe().ShouldEqual("1.0.0"); } } [Fact] - public void should_remove_and_re_add_the_package_files_in_the_lib_directory() + public void Should_remove_and_re_add_the_package_files_in_the_lib_directory() { var modifiedFile = Path.Combine(Scenario.get_top_level(), "lib", Configuration.PackageNames, "tools", "chocolateyinstall.ps1"); File.ReadAllText(modifiedFile).ShouldNotEqual(modifiedText); } [Fact] - public void should_delete_the_rollback() + public void Should_delete_the_rollback() { var packageDir = Path.Combine(Scenario.get_top_level(), "lib-bkp", Configuration.PackageNames); @@ -661,10 +661,10 @@ public void should_delete_the_rollback() } [Fact] - public void should_contain_a_warning_message_that_it_installed_successfully() + public void Should_contain_a_warning_message_that_it_installed_successfully() { bool installedSuccessfully = false; - foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).or_empty_list_if_null()) + foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).OrEmpty()) { if (message.Contains("1/1")) installedSuccessfully = true; } @@ -673,31 +673,31 @@ public void should_contain_a_warning_message_that_it_installed_successfully() } [Fact] - public void should_have_a_successful_package_result() + public void Should_have_a_successful_package_result() { packageResult.Success.ShouldBeTrue(); } [Fact] - public void should_not_have_inconclusive_package_result() + public void Should_not_have_inconclusive_package_result() { packageResult.Inconclusive.ShouldBeFalse(); } [Fact] - public void should_not_have_warning_package_result() + public void Should_not_have_warning_package_result() { packageResult.Warning.ShouldBeFalse(); } [Fact] - public void config_should_match_package_result_name() + public void Config_should_match_package_result_name() { packageResult.Name.ShouldEqual(Configuration.PackageNames); } [Fact] - public void should_have_a_version_of_one_dot_zero_dot_zero() + public void Should_have_a_version_of_one_dot_zero_dot_zero() { packageResult.Version.ShouldEqual("1.0.0"); } @@ -705,7 +705,7 @@ public void should_have_a_version_of_one_dot_zero_dot_zero() [WindowsOnly] [Platform(Exclude = "Mono")] - public class when_force_installing_an_already_installed_package_that_errors : ScenariosBase + public class When_force_installing_an_already_installed_package_that_errors : ScenariosBase { private PackageResult packageResult; private readonly string modifiedText = "bob"; @@ -725,12 +725,12 @@ public override void Context() public override void Because() { - Results = Service.install_run(Configuration); + Results = Service.Install(Configuration); packageResult = Results.FirstOrDefault().Value; } [Fact] - public void should_restore_the_backup_version_of_the_package() + public void Should_restore_the_backup_version_of_the_package() { var packageFile = Path.Combine(Scenario.get_top_level(), "lib", Configuration.PackageNames, Configuration.PackageNames + NuGetConstants.PackageExtension); using (var packageReader = new PackageArchiveReader(packageFile)) @@ -740,14 +740,14 @@ public void should_restore_the_backup_version_of_the_package() } [Fact] - public void should_restore_the_original_files_in_the_package_lib_folder() + public void Should_restore_the_original_files_in_the_package_lib_folder() { var modifiedFile = Path.Combine(Scenario.get_top_level(), "lib", Configuration.PackageNames, "tools", "chocolateyInstall.ps1"); File.ReadAllText(modifiedFile).ShouldEqual(modifiedText); } [Fact] - public void should_delete_the_rollback() + public void Should_delete_the_rollback() { var packageDir = Path.Combine(Scenario.get_top_level(), "lib-bkp", Configuration.PackageNames); @@ -755,10 +755,10 @@ public void should_delete_the_rollback() } [Fact] - public void should_contain_a_message_that_it_was_unsuccessful() + public void Should_contain_a_message_that_it_was_unsuccessful() { bool installedSuccessfully = false; - foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).or_empty_list_if_null()) + foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).OrEmpty()) { if (message.Contains("0/1")) installedSuccessfully = true; } @@ -767,19 +767,19 @@ public void should_contain_a_message_that_it_was_unsuccessful() } [Fact] - public void should_not_have_a_successful_package_result() + public void Should_not_have_a_successful_package_result() { packageResult.Success.ShouldBeFalse(); } [Fact] - public void should_not_have_inconclusive_package_result() + public void Should_not_have_inconclusive_package_result() { packageResult.Inconclusive.ShouldBeFalse(); } [Fact] - public void should_not_have_warning_package_result() + public void Should_not_have_warning_package_result() { packageResult.Warning.ShouldBeFalse(); } @@ -787,7 +787,7 @@ public void should_not_have_warning_package_result() [WindowsOnly] [Platform(Exclude = "Mono")] - public class when_force_installing_an_already_installed_package_with_a_read_and_delete_share_locked_file : ScenariosBase + public class When_force_installing_an_already_installed_package_with_a_read_and_delete_share_locked_file : ScenariosBase { private PackageResult packageResult; private FileStream fileStream; @@ -810,18 +810,18 @@ public override void AfterObservations() public override void Because() { - Results = Service.install_run(Configuration); + Results = Service.Install(Configuration); packageResult = Results.FirstOrDefault().Value; } [Fact] - public void should_install_where_install_location_reports() + public void Should_install_where_install_location_reports() { DirectoryAssert.Exists(packageResult.InstallLocation); } [Fact] - public void should_reinstall_the_package_in_the_lib_directory() + public void Should_reinstall_the_package_in_the_lib_directory() { var packageDir = Path.Combine(Scenario.get_top_level(), "lib", Configuration.PackageNames); @@ -829,19 +829,19 @@ public void should_reinstall_the_package_in_the_lib_directory() } [Fact] - public void should_reinstall_the_same_version_of_the_package() + public void Should_reinstall_the_same_version_of_the_package() { var packageFile = Path.Combine(Scenario.get_top_level(), "lib", Configuration.PackageNames, Configuration.PackageNames + NuGetConstants.PackageExtension); using (var packageReader = new PackageArchiveReader(packageFile)) { - packageReader.NuspecReader.GetVersion().to_string().ShouldEqual("1.0.0"); + packageReader.NuspecReader.GetVersion().ToStringSafe().ShouldEqual("1.0.0"); } } [Fact] [Pending("Does not work under .Net 4.8, See issue #2690")] [Broken] - public void should_not_be_able_delete_the_rollback() + public void Should_not_be_able_delete_the_rollback() { var packageDir = Path.Combine(Scenario.get_top_level(), "lib-bkp", Configuration.PackageNames); @@ -849,10 +849,10 @@ public void should_not_be_able_delete_the_rollback() } [Fact] - public void should_contain_a_message_that_it_installed_successfully() + public void Should_contain_a_message_that_it_installed_successfully() { bool expectedMessage = false; - foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).or_empty_list_if_null()) + foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).OrEmpty()) { if (message.Contains("1/1")) expectedMessage = true; } @@ -861,31 +861,31 @@ public void should_contain_a_message_that_it_installed_successfully() } [Fact] - public void should_have_a_successful_package_result() + public void Should_have_a_successful_package_result() { packageResult.Success.ShouldBeTrue(); } [Fact] - public void should_not_have_inconclusive_package_result() + public void Should_not_have_inconclusive_package_result() { packageResult.Inconclusive.ShouldBeFalse(); } [Fact] - public void should_not_have_warning_package_result() + public void Should_not_have_warning_package_result() { packageResult.Warning.ShouldBeFalse(); } [Fact] - public void config_should_match_package_result_name() + public void Config_should_match_package_result_name() { packageResult.Name.ShouldEqual(Configuration.PackageNames); } [Fact] - public void should_have_a_version_of_one_dot_zero_dot_zero() + public void Should_have_a_version_of_one_dot_zero_dot_zero() { packageResult.Version.ShouldEqual("1.0.0"); } @@ -893,7 +893,7 @@ public void should_have_a_version_of_one_dot_zero_dot_zero() [WindowsOnly] [Platform(Exclude = "Mono")] - public class when_force_installing_an_already_installed_package_with_with_an_exclusively_locked_file : ScenariosBase + public class When_force_installing_an_already_installed_package_with_with_an_exclusively_locked_file : ScenariosBase { private PackageResult packageResult; private FileStream fileStream; @@ -916,12 +916,12 @@ public override void AfterObservations() public override void Because() { - Results = Service.install_run(Configuration); + Results = Service.Install(Configuration); packageResult = Results.FirstOrDefault().Value; } [Fact] - public void should_have_a_package_installed_in_the_lib_directory() + public void Should_have_a_package_installed_in_the_lib_directory() { var packageDir = Path.Combine(Scenario.get_top_level(), "lib", Configuration.PackageNames); @@ -929,17 +929,17 @@ public void should_have_a_package_installed_in_the_lib_directory() } [Fact] - public void should_still_have_the_package_installed_with_the_expected_version_of_the_package() + public void Should_still_have_the_package_installed_with_the_expected_version_of_the_package() { var packageFile = Path.Combine(Scenario.get_top_level(), "lib", Configuration.PackageNames, Configuration.PackageNames + NuGetConstants.PackageExtension); using (var packageReader = new PackageArchiveReader(packageFile)) { - packageReader.NuspecReader.GetVersion().to_string().ShouldEqual("1.0.0"); + packageReader.NuspecReader.GetVersion().ToStringSafe().ShouldEqual("1.0.0"); } } [Fact] - public void should_delete_the_rollback() + public void Should_delete_the_rollback() { var packageDir = Path.Combine(Scenario.get_top_level(), "lib-bkp", Configuration.PackageNames); @@ -947,10 +947,10 @@ public void should_delete_the_rollback() } [Fact] - public void should_contain_a_message_that_it_was_unable_to_reinstall_successfully() + public void Should_contain_a_message_that_it_was_unable_to_reinstall_successfully() { bool expectedMessage = false; - foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).or_empty_list_if_null()) + foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).OrEmpty()) { if (message.Contains("0/1")) expectedMessage = true; } @@ -959,25 +959,25 @@ public void should_contain_a_message_that_it_was_unable_to_reinstall_successfull } [Fact] - public void should_not_have_a_successful_package_result() + public void Should_not_have_a_successful_package_result() { packageResult.Success.ShouldBeFalse(); } [Fact] - public void should_have_inconclusive_package_result() + public void Should_have_inconclusive_package_result() { packageResult.Inconclusive.ShouldBeTrue(); } [Fact] - public void should_not_have_warning_package_result() + public void Should_not_have_warning_package_result() { packageResult.Warning.ShouldBeFalse(); } } - public class when_installing_a_package_that_exists_but_a_version_that_does_not_exist : ScenariosBase + public class When_installing_a_package_that_exists_but_a_version_that_does_not_exist : ScenariosBase { private PackageResult packageResult; @@ -989,12 +989,12 @@ public override void Context() public override void Because() { - Results = Service.install_run(Configuration); + Results = Service.Install(Configuration); packageResult = Results.FirstOrDefault().Value; } [Fact] - public void should_not_install_a_package_in_the_lib_directory() + public void Should_not_install_a_package_in_the_lib_directory() { var packageDir = Path.Combine(Scenario.get_top_level(), "lib", Configuration.PackageNames); @@ -1002,10 +1002,10 @@ public void should_not_install_a_package_in_the_lib_directory() } [Fact] - public void should_contain_a_warning_message_that_it_did_not_install_successfully() + public void Should_contain_a_warning_message_that_it_did_not_install_successfully() { bool installedSuccessfully = false; - foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).or_empty_list_if_null()) + foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).OrEmpty()) { if (message.Contains("0/1")) installedSuccessfully = true; } @@ -1014,25 +1014,25 @@ public void should_contain_a_warning_message_that_it_did_not_install_successfull } [Fact] - public void should_not_have_a_successful_package_result() + public void Should_not_have_a_successful_package_result() { packageResult.Success.ShouldBeFalse(); } [Fact] - public void should_not_have_inconclusive_package_result() + public void Should_not_have_inconclusive_package_result() { packageResult.Inconclusive.ShouldBeFalse(); } [Fact] - public void should_not_have_warning_package_result() + public void Should_not_have_warning_package_result() { packageResult.Warning.ShouldBeFalse(); } [Fact] - public void should_have_an_error_package_result() + public void Should_have_an_error_package_result() { bool errorFound = false; foreach (var message in packageResult.Messages) @@ -1047,7 +1047,7 @@ public void should_have_an_error_package_result() } [Fact] - public void should_have_expected_error_in_package_result() + public void Should_have_expected_error_in_package_result() { bool errorFound = false; foreach (var message in packageResult.Messages) @@ -1062,13 +1062,13 @@ public void should_have_expected_error_in_package_result() } [Fact] - public void should_have_a_version_of_one_dot_zero_dot_one() + public void Should_have_a_version_of_one_dot_zero_dot_one() { packageResult.Version.ShouldEqual("1.0.1"); } } - public class when_installing_a_package_that_does_not_exist : ScenariosBase + public class When_installing_a_package_that_does_not_exist : ScenariosBase { private PackageResult packageResult; @@ -1080,12 +1080,12 @@ public override void Context() public override void Because() { - Results = Service.install_run(Configuration); + Results = Service.Install(Configuration); packageResult = Results.FirstOrDefault().Value; } [Fact] - public void should_not_install_a_package_in_the_lib_directory() + public void Should_not_install_a_package_in_the_lib_directory() { var packageDir = Path.Combine(Scenario.get_top_level(), "lib", Configuration.PackageNames); @@ -1093,10 +1093,10 @@ public void should_not_install_a_package_in_the_lib_directory() } [Fact] - public void should_contain_a_warning_message_that_it_was_unable_to_install_a_package() + public void Should_contain_a_warning_message_that_it_was_unable_to_install_a_package() { bool installedSuccessfully = false; - foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).or_empty_list_if_null()) + foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).OrEmpty()) { if (message.Contains("0/1")) installedSuccessfully = true; } @@ -1105,25 +1105,25 @@ public void should_contain_a_warning_message_that_it_was_unable_to_install_a_pac } [Fact] - public void should_not_have_a_successful_package_result() + public void Should_not_have_a_successful_package_result() { packageResult.Success.ShouldBeFalse(); } [Fact] - public void should_not_have_inconclusive_package_result() + public void Should_not_have_inconclusive_package_result() { packageResult.Inconclusive.ShouldBeFalse(); } [Fact] - public void should_not_have_warning_package_result() + public void Should_not_have_warning_package_result() { packageResult.Warning.ShouldBeFalse(); } [Fact] - public void should_have_an_error_package_result() + public void Should_have_an_error_package_result() { bool errorFound = false; foreach (var message in packageResult.Messages) @@ -1138,7 +1138,7 @@ public void should_have_an_error_package_result() } [Fact] - public void should_have_expected_error_in_package_result() + public void Should_have_expected_error_in_package_result() { bool errorFound = false; foreach (var message in packageResult.Messages) @@ -1155,7 +1155,7 @@ public void should_have_expected_error_in_package_result() [WindowsOnly] [Platform(Exclude = "Mono")] - public class when_installing_a_package_that_errors : ScenariosBase + public class When_installing_a_package_that_errors : ScenariosBase { private PackageResult packageResult; @@ -1167,12 +1167,12 @@ public override void Context() public override void Because() { - Results = Service.install_run(Configuration); + Results = Service.Install(Configuration); packageResult = Results.FirstOrDefault().Value; } [Fact] - public void should_not_install_a_package_in_the_lib_directory() + public void Should_not_install_a_package_in_the_lib_directory() { var packageDir = Path.Combine(Scenario.get_top_level(), "lib", Configuration.PackageNames); @@ -1180,7 +1180,7 @@ public void should_not_install_a_package_in_the_lib_directory() } [Fact] - public void should_put_a_package_in_the_lib_bad_directory() + public void Should_put_a_package_in_the_lib_bad_directory() { var packageDir = Path.Combine(Scenario.get_top_level(), "lib-bad", Configuration.PackageNames); @@ -1188,10 +1188,10 @@ public void should_put_a_package_in_the_lib_bad_directory() } [Fact] - public void should_contain_a_warning_message_that_it_was_unable_to_install_a_package() + public void Should_contain_a_warning_message_that_it_was_unable_to_install_a_package() { bool installedSuccessfully = false; - foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).or_empty_list_if_null()) + foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).OrEmpty()) { if (message.Contains("0/1")) installedSuccessfully = true; } @@ -1200,25 +1200,25 @@ public void should_contain_a_warning_message_that_it_was_unable_to_install_a_pac } [Fact] - public void should_not_have_a_successful_package_result() + public void Should_not_have_a_successful_package_result() { packageResult.Success.ShouldBeFalse(); } [Fact] - public void should_not_have_inconclusive_package_result() + public void Should_not_have_inconclusive_package_result() { packageResult.Inconclusive.ShouldBeFalse(); } [Fact] - public void should_not_have_warning_package_result() + public void Should_not_have_warning_package_result() { packageResult.Warning.ShouldBeFalse(); } [Fact] - public void should_have_an_error_package_result() + public void Should_have_an_error_package_result() { bool errorFound = false; foreach (var message in packageResult.Messages) @@ -1233,7 +1233,7 @@ public void should_have_an_error_package_result() } [Fact] - public void should_have_expected_error_in_package_result() + public void Should_have_expected_error_in_package_result() { bool errorFound = false; foreach (var message in packageResult.Messages) @@ -1248,7 +1248,7 @@ public void should_have_expected_error_in_package_result() } } - public class when_installing_a_package_that_has_nonterminating_errors : ScenariosBase + public class When_installing_a_package_that_has_nonterminating_errors : ScenariosBase { private PackageResult packageResult; @@ -1263,18 +1263,18 @@ public override void Context() public override void Because() { - Results = Service.install_run(Configuration); + Results = Service.Install(Configuration); packageResult = Results.FirstOrDefault().Value; } [Fact] - public void should_install_where_install_location_reports() + public void Should_install_where_install_location_reports() { DirectoryAssert.Exists(packageResult.InstallLocation); } [Fact] - public void should_install_the_package_in_the_lib_directory() + public void Should_install_the_package_in_the_lib_directory() { var packageDir = Path.Combine(Scenario.get_top_level(), "lib", Configuration.Input); @@ -1282,7 +1282,7 @@ public void should_install_the_package_in_the_lib_directory() } [Fact] - public void should_install_the_expected_version_of_the_package() + public void Should_install_the_expected_version_of_the_package() { var packageFile = Path.Combine(Scenario.get_top_level(), "lib", Configuration.Input, Configuration.Input + NuGetConstants.PackageExtension); using (var packageReader = new PackageArchiveReader(packageFile)) @@ -1292,10 +1292,10 @@ public void should_install_the_expected_version_of_the_package() } [Fact] - public void should_contain_a_message_that_it_installed_successfully() + public void Should_contain_a_message_that_it_installed_successfully() { bool installedSuccessfully = false; - foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).or_empty_list_if_null()) + foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).OrEmpty()) { if (message.Contains("1/1")) installedSuccessfully = true; } @@ -1304,31 +1304,31 @@ public void should_contain_a_message_that_it_installed_successfully() } [Fact] - public void should_have_a_successful_package_result() + public void Should_have_a_successful_package_result() { packageResult.Success.ShouldBeTrue(); } [Fact] - public void should_not_have_inconclusive_package_result() + public void Should_not_have_inconclusive_package_result() { packageResult.Inconclusive.ShouldBeFalse(); } [Fact] - public void should_not_have_warning_package_result() + public void Should_not_have_warning_package_result() { packageResult.Warning.ShouldBeFalse(); } [Fact] - public void config_should_match_package_result_name() + public void Config_should_match_package_result_name() { packageResult.Name.ShouldEqual(Configuration.Input); } [Fact] - public void should_have_a_version_of_one_dot_zero_dot_zero() + public void Should_have_a_version_of_one_dot_zero_dot_zero() { packageResult.Version.ShouldEqual("1.0.0"); } @@ -1336,7 +1336,7 @@ public void should_have_a_version_of_one_dot_zero_dot_zero() [WindowsOnly] [Platform(Exclude = "Mono")] - public class when_installing_a_package_that_has_nonterminating_errors_with_fail_on_stderr : ScenariosBase + public class When_installing_a_package_that_has_nonterminating_errors_with_fail_on_stderr : ScenariosBase { private PackageResult packageResult; @@ -1351,12 +1351,12 @@ public override void Context() public override void Because() { - Results = Service.install_run(Configuration); + Results = Service.Install(Configuration); packageResult = Results.FirstOrDefault().Value; } [Fact] - public void should_not_install_a_package_in_the_lib_directory() + public void Should_not_install_a_package_in_the_lib_directory() { var packageDir = Path.Combine(Scenario.get_top_level(), "lib", Configuration.PackageNames); @@ -1364,7 +1364,7 @@ public void should_not_install_a_package_in_the_lib_directory() } [Fact] - public void should_put_a_package_in_the_lib_bad_directory() + public void Should_put_a_package_in_the_lib_bad_directory() { var packageDir = Path.Combine(Scenario.get_top_level(), "lib-bad", Configuration.PackageNames); @@ -1372,10 +1372,10 @@ public void should_put_a_package_in_the_lib_bad_directory() } [Fact] - public void should_contain_a_warning_message_that_it_was_unable_to_install_a_package() + public void Should_contain_a_warning_message_that_it_was_unable_to_install_a_package() { bool installedSuccessfully = false; - foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).or_empty_list_if_null()) + foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).OrEmpty()) { if (message.Contains("0/1")) installedSuccessfully = true; } @@ -1384,25 +1384,25 @@ public void should_contain_a_warning_message_that_it_was_unable_to_install_a_pac } [Fact] - public void should_not_have_a_successful_package_result() + public void Should_not_have_a_successful_package_result() { packageResult.Success.ShouldBeFalse(); } [Fact] - public void should_not_have_inconclusive_package_result() + public void Should_not_have_inconclusive_package_result() { packageResult.Inconclusive.ShouldBeFalse(); } [Fact] - public void should_not_have_warning_package_result() + public void Should_not_have_warning_package_result() { packageResult.Warning.ShouldBeFalse(); } [Fact] - public void should_have_an_error_package_result() + public void Should_have_an_error_package_result() { bool errorFound = false; foreach (var message in packageResult.Messages) @@ -1417,7 +1417,7 @@ public void should_have_an_error_package_result() } [Fact] - public void should_have_expected_error_in_package_result() + public void Should_have_expected_error_in_package_result() { bool errorFound = false; foreach (var message in packageResult.Messages) @@ -1432,7 +1432,7 @@ public void should_have_expected_error_in_package_result() } } - public class when_installing_a_package_with_dependencies_happy : ScenariosBase + public class When_installing_a_package_with_dependencies_happy : ScenariosBase { public override void Context() { @@ -1445,11 +1445,11 @@ public override void Context() public override void Because() { - Results = Service.install_run(Configuration); + Results = Service.Install(Configuration); } [Fact] - public void should_install_where_install_location_reports() + public void Should_install_where_install_location_reports() { foreach (var packageResult in Results) { @@ -1458,7 +1458,7 @@ public void should_install_where_install_location_reports() } [Fact] - public void should_install_a_package_in_the_lib_directory() + public void Should_install_a_package_in_the_lib_directory() { var packageDir = Path.Combine(Scenario.get_top_level(), "lib", Configuration.PackageNames); @@ -1466,7 +1466,7 @@ public void should_install_a_package_in_the_lib_directory() } [Fact] - public void should_install_the_dependency_in_the_lib_directory() + public void Should_install_the_dependency_in_the_lib_directory() { var packageDir = Path.Combine(Scenario.get_top_level(), "lib", "isdependency"); @@ -1474,20 +1474,20 @@ public void should_install_the_dependency_in_the_lib_directory() } [Fact] - public void should_install_the_expected_version_of_the_dependency() + public void Should_install_the_expected_version_of_the_dependency() { var packageFile = Path.Combine(Scenario.get_top_level(), "lib", "isdependency", "isdependency.nupkg"); using (var packageReader = new PackageArchiveReader(packageFile)) { - packageReader.NuspecReader.GetVersion().to_string().ShouldEqual("1.0.0"); + packageReader.NuspecReader.GetVersion().ToStringSafe().ShouldEqual("1.0.0"); } } [Fact] - public void should_contain_a_message_that_everything_installed_successfully() + public void Should_contain_a_message_that_everything_installed_successfully() { bool expectedMessage = false; - foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).or_empty_list_if_null()) + foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).OrEmpty()) { if (message.Contains("3/3")) expectedMessage = true; } @@ -1496,7 +1496,7 @@ public void should_contain_a_message_that_everything_installed_successfully() } [Fact] - public void should_have_a_successful_package_result() + public void Should_have_a_successful_package_result() { foreach (var packageResult in Results) { @@ -1505,7 +1505,7 @@ public void should_have_a_successful_package_result() } [Fact] - public void should_not_have_inconclusive_package_result() + public void Should_not_have_inconclusive_package_result() { foreach (var packageResult in Results) { @@ -1514,7 +1514,7 @@ public void should_not_have_inconclusive_package_result() } [Fact] - public void should_not_have_warning_package_result() + public void Should_not_have_warning_package_result() { foreach (var packageResult in Results) { @@ -1523,7 +1523,7 @@ public void should_not_have_warning_package_result() } [Fact] - public void should_have_a_version_of_one_dot_zero_dot_zero() + public void Should_have_a_version_of_one_dot_zero_dot_zero() { foreach (var packageResult in Results) { @@ -1532,7 +1532,7 @@ public void should_have_a_version_of_one_dot_zero_dot_zero() } } - public class when_force_installing_an_already_installed_package_with_dependencies : ScenariosBase + public class When_force_installing_an_already_installed_package_with_dependencies : ScenariosBase { public override void Context() { @@ -1549,11 +1549,11 @@ public override void Context() public override void Because() { - Results = Service.install_run(Configuration); + Results = Service.Install(Configuration); } [Fact] - public void should_install_where_install_location_reports() + public void Should_install_where_install_location_reports() { foreach (var packageResult in Results) { @@ -1562,7 +1562,7 @@ public void should_install_where_install_location_reports() } [Fact] - public void should_install_a_package_in_the_lib_directory() + public void Should_install_a_package_in_the_lib_directory() { var packageDir = Path.Combine(Scenario.get_top_level(), "lib", Configuration.PackageNames); @@ -1570,17 +1570,17 @@ public void should_install_a_package_in_the_lib_directory() } [Fact] - public void should_reinstall_the_exact_same_version_of_the_package() + public void Should_reinstall_the_exact_same_version_of_the_package() { var packageFile = Path.Combine(Scenario.get_top_level(), "lib", Configuration.PackageNames, Configuration.PackageNames + NuGetConstants.PackageExtension); using (var packageReader = new PackageArchiveReader(packageFile)) { - packageReader.NuspecReader.GetVersion().to_string().ShouldEqual("1.0.0"); + packageReader.NuspecReader.GetVersion().ToStringSafe().ShouldEqual("1.0.0"); } } [Fact] - public void should_still_have_the_dependency_in_the_lib_directory() + public void Should_still_have_the_dependency_in_the_lib_directory() { var packageDir = Path.Combine(Scenario.get_top_level(), "lib", "isdependency"); @@ -1588,20 +1588,20 @@ public void should_still_have_the_dependency_in_the_lib_directory() } [Fact] - public void should_not_upgrade_the_dependency() + public void Should_not_upgrade_the_dependency() { var packageFile = Path.Combine(Scenario.get_top_level(), "lib", "isdependency", "isdependency.nupkg"); using (var packageReader = new PackageArchiveReader(packageFile)) { - packageReader.NuspecReader.GetVersion().to_string().ShouldEqual("1.0.0"); + packageReader.NuspecReader.GetVersion().ToStringSafe().ShouldEqual("1.0.0"); } } [Fact] - public void should_contain_a_message_that_it_installed_successfully() + public void Should_contain_a_message_that_it_installed_successfully() { bool expectedMessage = false; - foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).or_empty_list_if_null()) + foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).OrEmpty()) { if (message.Contains("1/1")) expectedMessage = true; } @@ -1610,7 +1610,7 @@ public void should_contain_a_message_that_it_installed_successfully() } [Fact] - public void should_have_a_successful_package_result() + public void Should_have_a_successful_package_result() { foreach (var packageResult in Results) { @@ -1619,7 +1619,7 @@ public void should_have_a_successful_package_result() } [Fact] - public void should_not_have_inconclusive_package_result() + public void Should_not_have_inconclusive_package_result() { foreach (var packageResult in Results) { @@ -1628,7 +1628,7 @@ public void should_not_have_inconclusive_package_result() } [Fact] - public void should_not_have_warning_package_result() + public void Should_not_have_warning_package_result() { foreach (var packageResult in Results) { @@ -1637,7 +1637,7 @@ public void should_not_have_warning_package_result() } [Fact] - public void should_have_a_version_of_one_dot_zero_dot_zero() + public void Should_have_a_version_of_one_dot_zero_dot_zero() { foreach (var packageResult in Results) { @@ -1646,7 +1646,7 @@ public void should_have_a_version_of_one_dot_zero_dot_zero() } } - public class when_force_installing_an_already_installed_package_forcing_dependencies : ScenariosBase + public class When_force_installing_an_already_installed_package_forcing_dependencies : ScenariosBase { private IEnumerable _installedPackagePaths; public override void Context() @@ -1670,11 +1670,11 @@ public override void Context() public override void Because() { - Results = Service.install_run(Configuration); + Results = Service.Install(Configuration); } [Fact] - public void should_install_where_install_location_reports() + public void Should_install_where_install_location_reports() { foreach (var packageResult in Results) { @@ -1683,7 +1683,7 @@ public void should_install_where_install_location_reports() } [Fact] - public void should_install_a_package_in_the_lib_directory() + public void Should_install_a_package_in_the_lib_directory() { var packageDir = Path.Combine(Scenario.get_top_level(), "lib", Configuration.PackageNames); @@ -1691,17 +1691,17 @@ public void should_install_a_package_in_the_lib_directory() } [Fact] - public void should_reinstall_the_exact_same_version_of_the_package() + public void Should_reinstall_the_exact_same_version_of_the_package() { var packageFile = Path.Combine(Scenario.get_top_level(), "lib", Configuration.PackageNames, Configuration.PackageNames + NuGetConstants.PackageExtension); using (var packageReader = new PackageArchiveReader(packageFile)) { - packageReader.NuspecReader.GetVersion().to_string().ShouldEqual("1.0.0"); + packageReader.NuspecReader.GetVersion().ToStringSafe().ShouldEqual("1.0.0"); } } [Fact] - public void should_not_remove_any_existing_packages_in_the_lib_directory() + public void Should_not_remove_any_existing_packages_in_the_lib_directory() { foreach (var packagePath in _installedPackagePaths) { @@ -1710,7 +1710,7 @@ public void should_not_remove_any_existing_packages_in_the_lib_directory() } [Fact] - public void should_install_the_dependency_in_the_lib_directory() + public void Should_install_the_dependency_in_the_lib_directory() { var packageDir = Path.Combine(Scenario.get_top_level(), "lib", "isdependency"); @@ -1718,30 +1718,30 @@ public void should_install_the_dependency_in_the_lib_directory() } [Fact] - public void should_reinstall_the_floating_dependency_with_the_latest_version_that_satisfies_the_dependency() + public void Should_reinstall_the_floating_dependency_with_the_latest_version_that_satisfies_the_dependency() { var packageFile = Path.Combine(Scenario.get_top_level(), "lib", "isdependency", "isdependency.nupkg"); using (var packageReader = new PackageArchiveReader(packageFile)) { - packageReader.NuspecReader.GetVersion().to_string().ShouldEqual("1.0.0"); + packageReader.NuspecReader.GetVersion().ToStringSafe().ShouldEqual("1.0.0"); } } [Fact] - public void should_reinstall_the_exact_same_version_of_the_exact_dependency() + public void Should_reinstall_the_exact_same_version_of_the_exact_dependency() { var packageFile = Path.Combine(Scenario.get_top_level(), "lib", "isexactversiondependency", "isexactversiondependency.nupkg"); using (var packageReader = new PackageArchiveReader(packageFile)) { - packageReader.NuspecReader.GetVersion().to_string().ShouldEqual("1.0.0"); + packageReader.NuspecReader.GetVersion().ToStringSafe().ShouldEqual("1.0.0"); } } [Fact] - public void should_contain_a_warning_message_that_it_installed_successfully() + public void Should_contain_a_warning_message_that_it_installed_successfully() { bool installedSuccessfully = false; - foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).or_empty_list_if_null()) + foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).OrEmpty()) { if (message.Contains("3/3")) installedSuccessfully = true; } @@ -1750,7 +1750,7 @@ public void should_contain_a_warning_message_that_it_installed_successfully() } [Fact] - public void should_have_a_successful_package_result() + public void Should_have_a_successful_package_result() { foreach (var packageResult in Results) { @@ -1759,7 +1759,7 @@ public void should_have_a_successful_package_result() } [Fact] - public void should_not_have_inconclusive_package_result() + public void Should_not_have_inconclusive_package_result() { foreach (var packageResult in Results) { @@ -1768,7 +1768,7 @@ public void should_not_have_inconclusive_package_result() } [Fact] - public void should_not_have_warning_package_result() + public void Should_not_have_warning_package_result() { foreach (var packageResult in Results) { @@ -1777,7 +1777,7 @@ public void should_not_have_warning_package_result() } } - public class when_force_installing_an_already_installed_package_ignoring_dependencies : ScenariosBase + public class When_force_installing_an_already_installed_package_ignoring_dependencies : ScenariosBase { public override void Context() { @@ -1795,11 +1795,11 @@ public override void Context() public override void Because() { - Results = Service.install_run(Configuration); + Results = Service.Install(Configuration); } [Fact] - public void should_install_where_install_location_reports() + public void Should_install_where_install_location_reports() { foreach (var packageResult in Results) { @@ -1808,7 +1808,7 @@ public void should_install_where_install_location_reports() } [Fact] - public void should_install_a_package_in_the_lib_directory() + public void Should_install_a_package_in_the_lib_directory() { var packageDir = Path.Combine(Scenario.get_top_level(), "lib", Configuration.PackageNames); @@ -1816,17 +1816,17 @@ public void should_install_a_package_in_the_lib_directory() } [Fact] - public void should_reinstall_the_exact_same_version_of_the_package() + public void Should_reinstall_the_exact_same_version_of_the_package() { var packageFile = Path.Combine(Scenario.get_top_level(), "lib", Configuration.PackageNames, Configuration.PackageNames + NuGetConstants.PackageExtension); using (var packageReader = new PackageArchiveReader(packageFile)) { - packageReader.NuspecReader.GetVersion().to_string().ShouldEqual("1.0.0"); + packageReader.NuspecReader.GetVersion().ToStringSafe().ShouldEqual("1.0.0"); } } [Fact] - public void should_install_the_dependency_in_the_lib_directory() + public void Should_install_the_dependency_in_the_lib_directory() { var packageDir = Path.Combine(Scenario.get_top_level(), "lib", "isdependency"); @@ -1834,30 +1834,30 @@ public void should_install_the_dependency_in_the_lib_directory() } [Fact] - public void should_not_touch_the_floating_dependency() + public void Should_not_touch_the_floating_dependency() { var packageFile = Path.Combine(Scenario.get_top_level(), "lib", "isdependency", "isdependency.nupkg"); using (var packageReader = new PackageArchiveReader(packageFile)) { - packageReader.NuspecReader.GetVersion().to_string().ShouldEqual("1.0.0"); + packageReader.NuspecReader.GetVersion().ToStringSafe().ShouldEqual("1.0.0"); } } [Fact] - public void should_not_touch_the_exact_dependency() + public void Should_not_touch_the_exact_dependency() { var packageFile = Path.Combine(Scenario.get_top_level(), "lib", "isexactversiondependency", "isexactversiondependency.nupkg"); using (var packageReader = new PackageArchiveReader(packageFile)) { - packageReader.NuspecReader.GetVersion().to_string().ShouldEqual("1.0.0"); + packageReader.NuspecReader.GetVersion().ToStringSafe().ShouldEqual("1.0.0"); } } [Fact] - public void should_contain_a_warning_message_that_it_installed_successfully() + public void Should_contain_a_warning_message_that_it_installed_successfully() { bool installedSuccessfully = false; - foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).or_empty_list_if_null()) + foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).OrEmpty()) { if (message.Contains("1/1")) installedSuccessfully = true; } @@ -1866,7 +1866,7 @@ public void should_contain_a_warning_message_that_it_installed_successfully() } [Fact] - public void should_have_a_successful_package_result() + public void Should_have_a_successful_package_result() { foreach (var packageResult in Results) { @@ -1875,7 +1875,7 @@ public void should_have_a_successful_package_result() } [Fact] - public void should_not_have_inconclusive_package_result() + public void Should_not_have_inconclusive_package_result() { foreach (var packageResult in Results) { @@ -1884,7 +1884,7 @@ public void should_not_have_inconclusive_package_result() } [Fact] - public void should_not_have_warning_package_result() + public void Should_not_have_warning_package_result() { foreach (var packageResult in Results) { @@ -1893,7 +1893,7 @@ public void should_not_have_warning_package_result() } } - public class when_force_installing_an_already_installed_package_forcing_and_ignoring_dependencies : ScenariosBase + public class When_force_installing_an_already_installed_package_forcing_and_ignoring_dependencies : ScenariosBase { public override void Context() { @@ -1912,11 +1912,11 @@ public override void Context() public override void Because() { - Results = Service.install_run(Configuration); + Results = Service.Install(Configuration); } [Fact] - public void should_install_where_install_location_reports() + public void Should_install_where_install_location_reports() { foreach (var packageResult in Results) { @@ -1925,7 +1925,7 @@ public void should_install_where_install_location_reports() } [Fact] - public void should_install_a_package_in_the_lib_directory() + public void Should_install_a_package_in_the_lib_directory() { var packageDir = Path.Combine(Scenario.get_top_level(), "lib", Configuration.PackageNames); @@ -1933,34 +1933,34 @@ public void should_install_a_package_in_the_lib_directory() } [Fact] - public void should_reinstall_the_exact_same_version_of_the_package() + public void Should_reinstall_the_exact_same_version_of_the_package() { var packageFile = Path.Combine(Scenario.get_top_level(), "lib", Configuration.PackageNames, Configuration.PackageNames + NuGetConstants.PackageExtension); using (var packageReader = new PackageArchiveReader(packageFile)) { - packageReader.NuspecReader.GetVersion().to_string().ShouldEqual("1.0.0"); + packageReader.NuspecReader.GetVersion().ToStringSafe().ShouldEqual("1.0.0"); } } [Fact] - public void should_remove_the_floating_dependency() + public void Should_remove_the_floating_dependency() { var dependency = Path.Combine(Scenario.get_top_level(), "lib", "isdependency"); DirectoryAssert.DoesNotExist(dependency); } [Fact] - public void should_remove_the_exact_dependency() + public void Should_remove_the_exact_dependency() { var dependency = Path.Combine(Scenario.get_top_level(), "lib", "isexactversiondependency"); DirectoryAssert.DoesNotExist(dependency); } [Fact] - public void should_contain_a_warning_message_that_it_installed_successfully() + public void Should_contain_a_warning_message_that_it_installed_successfully() { bool installedSuccessfully = false; - foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).or_empty_list_if_null()) + foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).OrEmpty()) { if (message.Contains("1/1")) installedSuccessfully = true; } @@ -1969,7 +1969,7 @@ public void should_contain_a_warning_message_that_it_installed_successfully() } [Fact] - public void should_have_a_successful_package_result() + public void Should_have_a_successful_package_result() { foreach (var packageResult in Results) { @@ -1978,7 +1978,7 @@ public void should_have_a_successful_package_result() } [Fact] - public void should_not_have_inconclusive_package_result() + public void Should_not_have_inconclusive_package_result() { foreach (var packageResult in Results) { @@ -1987,7 +1987,7 @@ public void should_not_have_inconclusive_package_result() } [Fact] - public void should_not_have_warning_package_result() + public void Should_not_have_warning_package_result() { foreach (var packageResult in Results) { @@ -1996,7 +1996,7 @@ public void should_not_have_warning_package_result() } } - public class when_installing_a_package_with_dependencies_and_dependency_cannot_be_found : ScenariosBase + public class When_installing_a_package_with_dependencies_and_dependency_cannot_be_found : ScenariosBase { public override void Context() { @@ -2007,11 +2007,11 @@ public override void Context() public override void Because() { - Results = Service.install_run(Configuration); + Results = Service.Install(Configuration); } [Fact] - public void should_not_install_a_package_in_the_lib_directory() + public void Should_not_install_a_package_in_the_lib_directory() { var packageDir = Path.Combine(Scenario.get_top_level(), "lib", Configuration.PackageNames); @@ -2019,7 +2019,7 @@ public void should_not_install_a_package_in_the_lib_directory() } [Fact] - public void should_not_install_the_dependency_in_the_lib_directory() + public void Should_not_install_the_dependency_in_the_lib_directory() { var packageDir = Path.Combine(Scenario.get_top_level(), "lib", "isdependency"); @@ -2027,10 +2027,10 @@ public void should_not_install_the_dependency_in_the_lib_directory() } [Fact] - public void should_contain_a_warning_message_that_it_was_unable_to_install_any_packages() + public void Should_contain_a_warning_message_that_it_was_unable_to_install_any_packages() { bool installedSuccessfully = false; - foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).or_empty_list_if_null()) + foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).OrEmpty()) { if (message.Contains("0/1")) installedSuccessfully = true; } @@ -2039,7 +2039,7 @@ public void should_contain_a_warning_message_that_it_was_unable_to_install_any_p } [Fact] - public void should_not_have_a_successful_package_result() + public void Should_not_have_a_successful_package_result() { foreach (var packageResult in Results) { @@ -2048,7 +2048,7 @@ public void should_not_have_a_successful_package_result() } [Fact] - public void should_not_have_inconclusive_package_result() + public void Should_not_have_inconclusive_package_result() { foreach (var packageResult in Results) { @@ -2057,7 +2057,7 @@ public void should_not_have_inconclusive_package_result() } [Fact] - public void should_not_have_warning_package_result() + public void Should_not_have_warning_package_result() { foreach (var packageResult in Results) { @@ -2066,7 +2066,7 @@ public void should_not_have_warning_package_result() } [Fact] - public void should_have_an_error_package_result() + public void Should_have_an_error_package_result() { bool errorFound = false; @@ -2085,7 +2085,7 @@ public void should_have_an_error_package_result() } [Fact] - public void should_have_expected_error_in_package_result() + public void Should_have_expected_error_in_package_result() { bool errorFound = false; @@ -2104,7 +2104,7 @@ public void should_have_expected_error_in_package_result() } } - public class when_installing_a_package_ignoring_dependencies_that_cannot_be_found : ScenariosBase + public class When_installing_a_package_ignoring_dependencies_that_cannot_be_found : ScenariosBase { private PackageResult packageResult; @@ -2118,18 +2118,18 @@ public override void Context() public override void Because() { - Results = Service.install_run(Configuration); + Results = Service.Install(Configuration); packageResult = Results.FirstOrDefault().Value; } [Fact] - public void should_install_where_install_location_reports() + public void Should_install_where_install_location_reports() { DirectoryAssert.Exists(packageResult.InstallLocation); } [Fact] - public void should_install_a_package_in_the_lib_directory() + public void Should_install_a_package_in_the_lib_directory() { var packageDir = Path.Combine(Scenario.get_top_level(), "lib", Configuration.PackageNames); @@ -2137,17 +2137,17 @@ public void should_install_a_package_in_the_lib_directory() } [Fact] - public void should_install_the_expected_version_of_the_package() + public void Should_install_the_expected_version_of_the_package() { var packageFile = Path.Combine(Scenario.get_top_level(), "lib", Configuration.PackageNames, Configuration.PackageNames + NuGetConstants.PackageExtension); using (var packageReader = new PackageArchiveReader(packageFile)) { - packageReader.NuspecReader.GetVersion().to_string().ShouldEqual("2.1.0"); + packageReader.NuspecReader.GetVersion().ToStringSafe().ShouldEqual("2.1.0"); } } [Fact] - public void should_not_install_the_dependency_in_the_lib_directory() + public void Should_not_install_the_dependency_in_the_lib_directory() { var packageDir = Path.Combine(Scenario.get_top_level(), "lib", "isdependency"); @@ -2155,10 +2155,10 @@ public void should_not_install_the_dependency_in_the_lib_directory() } [Fact] - public void should_contain_a_warning_message_that_it_installed_successfully() + public void Should_contain_a_warning_message_that_it_installed_successfully() { bool installedSuccessfully = false; - foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).or_empty_list_if_null()) + foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).OrEmpty()) { if (message.Contains("1/1")) installedSuccessfully = true; } @@ -2167,31 +2167,31 @@ public void should_contain_a_warning_message_that_it_installed_successfully() } [Fact] - public void should_have_a_successful_package_result() + public void Should_have_a_successful_package_result() { packageResult.Success.ShouldBeTrue(); } [Fact] - public void should_not_have_inconclusive_package_result() + public void Should_not_have_inconclusive_package_result() { packageResult.Inconclusive.ShouldBeFalse(); } [Fact] - public void should_not_have_warning_package_result() + public void Should_not_have_warning_package_result() { packageResult.Warning.ShouldBeFalse(); } [Fact] - public void config_should_match_package_result_name() + public void Config_should_match_package_result_name() { packageResult.Name.ShouldEqual(Configuration.PackageNames); } } - public class when_installing_a_package_that_depends_on_a_newer_version_of_an_installed_dependency : ScenariosBase + public class When_installing_a_package_that_depends_on_a_newer_version_of_an_installed_dependency : ScenariosBase { public override void Context() { @@ -2206,11 +2206,11 @@ public override void Context() public override void Because() { - Results = Service.install_run(Configuration); + Results = Service.Install(Configuration); } [Fact] - public void should_install_where_install_location_reports() + public void Should_install_where_install_location_reports() { foreach (var packageResult in Results) { @@ -2219,7 +2219,7 @@ public void should_install_where_install_location_reports() } [Fact] - public void should_install_a_package_in_the_lib_directory() + public void Should_install_a_package_in_the_lib_directory() { var packageDir = Path.Combine(Scenario.get_top_level(), "lib", Configuration.PackageNames); @@ -2227,17 +2227,17 @@ public void should_install_a_package_in_the_lib_directory() } [Fact] - public void should_install_the_expected_version_of_the_package() + public void Should_install_the_expected_version_of_the_package() { var packageFile = Path.Combine(Scenario.get_top_level(), "lib", Configuration.PackageNames, Configuration.PackageNames + NuGetConstants.PackageExtension); using (var packageReader = new PackageArchiveReader(packageFile)) { - packageReader.NuspecReader.GetVersion().to_string().ShouldEqual("1.6.0"); + packageReader.NuspecReader.GetVersion().ToStringSafe().ShouldEqual("1.6.0"); } } [Fact] - public void should_install_the_dependency_in_the_lib_directory() + public void Should_install_the_dependency_in_the_lib_directory() { var packageDir = Path.Combine(Scenario.get_top_level(), "lib", "isdependency"); @@ -2245,20 +2245,20 @@ public void should_install_the_dependency_in_the_lib_directory() } [Fact] - public void should_upgrade_the_dependency() + public void Should_upgrade_the_dependency() { var packageFile = Path.Combine(Scenario.get_top_level(), "lib", "isdependency", "isdependency.nupkg"); using (var packageReader = new PackageArchiveReader(packageFile)) { - packageReader.NuspecReader.GetVersion().to_string().ShouldEqual("1.1.0"); + packageReader.NuspecReader.GetVersion().ToStringSafe().ShouldEqual("1.1.0"); } } [Fact] - public void should_contain_a_warning_message_that_it_installed_successfully() + public void Should_contain_a_warning_message_that_it_installed_successfully() { bool installedSuccessfully = false; - foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).or_empty_list_if_null()) + foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).OrEmpty()) { if (message.Contains("3/3")) installedSuccessfully = true; } @@ -2267,7 +2267,7 @@ public void should_contain_a_warning_message_that_it_installed_successfully() } [Fact] - public void should_have_a_successful_package_result() + public void Should_have_a_successful_package_result() { foreach (var packageResult in Results) { @@ -2276,7 +2276,7 @@ public void should_have_a_successful_package_result() } [Fact] - public void should_not_have_inconclusive_package_result() + public void Should_not_have_inconclusive_package_result() { foreach (var packageResult in Results) { @@ -2285,7 +2285,7 @@ public void should_not_have_inconclusive_package_result() } [Fact] - public void should_not_have_warning_package_result() + public void Should_not_have_warning_package_result() { foreach (var packageResult in Results) { @@ -2294,7 +2294,7 @@ public void should_not_have_warning_package_result() } } - public class when_installing_a_package_that_depends_on_an_unavailable_newer_version_of_an_installed_dependency : ScenariosBase + public class When_installing_a_package_that_depends_on_an_unavailable_newer_version_of_an_installed_dependency : ScenariosBase { public override void Context() { @@ -2308,11 +2308,11 @@ public override void Context() public override void Because() { - Results = Service.install_run(Configuration); + Results = Service.Install(Configuration); } [Fact] - public void should_not_install_the_package_in_the_lib_directory() + public void Should_not_install_the_package_in_the_lib_directory() { var packageDir = Path.Combine(Scenario.get_top_level(), "lib", Configuration.PackageNames); @@ -2320,10 +2320,10 @@ public void should_not_install_the_package_in_the_lib_directory() } [Fact] - public void should_contain_a_message_that_is_was_unable_to_install_any_packages() + public void Should_contain_a_message_that_is_was_unable_to_install_any_packages() { bool expectedMessage = false; - foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).or_empty_list_if_null()) + foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).OrEmpty()) { if (message.Contains("0/1")) expectedMessage = true; } @@ -2332,7 +2332,7 @@ public void should_contain_a_message_that_is_was_unable_to_install_any_packages( } [Fact] - public void should_not_have_a_successful_package_result() + public void Should_not_have_a_successful_package_result() { foreach (var packageResult in Results) { @@ -2341,7 +2341,7 @@ public void should_not_have_a_successful_package_result() } [Fact] - public void should_not_have_inconclusive_package_result() + public void Should_not_have_inconclusive_package_result() { foreach (var packageResult in Results) { @@ -2350,7 +2350,7 @@ public void should_not_have_inconclusive_package_result() } [Fact] - public void should_not_have_warning_package_result() + public void Should_not_have_warning_package_result() { foreach (var packageResult in Results) { @@ -2359,7 +2359,7 @@ public void should_not_have_warning_package_result() } } - public class when_installing_a_package_that_depends_on_an_unavailable_newer_version_of_an_installed_dependency_ignoring_dependencies : ScenariosBase + public class When_installing_a_package_that_depends_on_an_unavailable_newer_version_of_an_installed_dependency_ignoring_dependencies : ScenariosBase { public override void Context() { @@ -2374,11 +2374,11 @@ public override void Context() public override void Because() { - Results = Service.install_run(Configuration); + Results = Service.Install(Configuration); } [Fact] - public void should_install_where_install_location_reports() + public void Should_install_where_install_location_reports() { foreach (var packageResult in Results) { @@ -2387,7 +2387,7 @@ public void should_install_where_install_location_reports() } [Fact] - public void should_install_a_package_in_the_lib_directory() + public void Should_install_a_package_in_the_lib_directory() { var packageDir = Path.Combine(Scenario.get_top_level(), "lib", Configuration.PackageNames); @@ -2395,20 +2395,20 @@ public void should_install_a_package_in_the_lib_directory() } [Fact] - public void should_install_the_expected_version_of_the_package() + public void Should_install_the_expected_version_of_the_package() { var packageFile = Path.Combine(Scenario.get_top_level(), "lib", Configuration.PackageNames, Configuration.PackageNames + NuGetConstants.PackageExtension); using (var packageReader = new PackageArchiveReader(packageFile)) { - packageReader.NuspecReader.GetVersion().to_string().ShouldEqual("1.6.0"); + packageReader.NuspecReader.GetVersion().ToStringSafe().ShouldEqual("1.6.0"); } } [Fact] - public void should_contain_a_message_that_it_installed_successfully() + public void Should_contain_a_message_that_it_installed_successfully() { bool expectedMessage = false; - foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).or_empty_list_if_null()) + foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).OrEmpty()) { if (message.Contains("1/1")) expectedMessage = true; } @@ -2417,7 +2417,7 @@ public void should_contain_a_message_that_it_installed_successfully() } [Fact] - public void should_have_a_successful_package_result() + public void Should_have_a_successful_package_result() { foreach (var packageResult in Results) { @@ -2426,7 +2426,7 @@ public void should_have_a_successful_package_result() } [Fact] - public void should_not_have_inconclusive_package_result() + public void Should_not_have_inconclusive_package_result() { foreach (var packageResult in Results) { @@ -2435,7 +2435,7 @@ public void should_not_have_inconclusive_package_result() } [Fact] - public void should_not_have_warning_package_result() + public void Should_not_have_warning_package_result() { foreach (var packageResult in Results) { @@ -2444,7 +2444,7 @@ public void should_not_have_warning_package_result() } } - public class when_force_installing_a_package_that_depends_on_an_unavailable_newer_version_of_an_installed_dependency_forcing_dependencies : ScenariosBase + public class When_force_installing_a_package_that_depends_on_an_unavailable_newer_version_of_an_installed_dependency_forcing_dependencies : ScenariosBase { public override void Context() { @@ -2460,11 +2460,11 @@ public override void Context() public override void Because() { - Results = Service.install_run(Configuration); + Results = Service.Install(Configuration); } [Fact] - public void should_not_install_a_package_in_the_lib_directory() + public void Should_not_install_a_package_in_the_lib_directory() { var packageDir = Path.Combine(Scenario.get_top_level(), "lib", Configuration.PackageNames); @@ -2472,20 +2472,20 @@ public void should_not_install_a_package_in_the_lib_directory() } [Fact] - public void should_not_upgrade_the_dependency() + public void Should_not_upgrade_the_dependency() { var packageFile = Path.Combine(Scenario.get_top_level(), "lib", "isdependency", "isdependency.nupkg"); using (var packageReader = new PackageArchiveReader(packageFile)) { - packageReader.NuspecReader.GetVersion().to_string().ShouldEqual("1.0.0"); + packageReader.NuspecReader.GetVersion().ToStringSafe().ShouldEqual("1.0.0"); } } [Fact] - public void should_contain_a_warning_message_that_it_was_unable_to_install_any_packages() + public void Should_contain_a_warning_message_that_it_was_unable_to_install_any_packages() { bool installedSuccessfully = false; - foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).or_empty_list_if_null()) + foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).OrEmpty()) { if (message.Contains("0/1")) installedSuccessfully = true; } @@ -2494,7 +2494,7 @@ public void should_contain_a_warning_message_that_it_was_unable_to_install_any_p } [Fact] - public void should_not_have_a_successful_package_result() + public void Should_not_have_a_successful_package_result() { foreach (var packageResult in Results) { @@ -2503,7 +2503,7 @@ public void should_not_have_a_successful_package_result() } [Fact] - public void should_not_have_inconclusive_package_result() + public void Should_not_have_inconclusive_package_result() { foreach (var packageResult in Results) { @@ -2512,7 +2512,7 @@ public void should_not_have_inconclusive_package_result() } [Fact] - public void should_not_have_warning_package_result() + public void Should_not_have_warning_package_result() { foreach (var packageResult in Results) { @@ -2521,7 +2521,7 @@ public void should_not_have_warning_package_result() } [Fact] - public void should_have_an_error_package_result() + public void Should_have_an_error_package_result() { bool errorFound = false; @@ -2540,7 +2540,7 @@ public void should_have_an_error_package_result() } [Fact] - public void should_have_expected_error_in_package_result() + public void Should_have_expected_error_in_package_result() { bool errorFound = false; @@ -2559,7 +2559,7 @@ public void should_have_expected_error_in_package_result() } } - public class when_installing_a_package_with_dependencies_on_a_newer_version_of_a_package_than_an_existing_package_has_with_that_dependency : ScenariosBase + public class When_installing_a_package_with_dependencies_on_a_newer_version_of_a_package_than_an_existing_package_has_with_that_dependency : ScenariosBase { public override void Context() { @@ -2575,11 +2575,11 @@ public override void Context() public override void Because() { - Results = Service.install_run(Configuration); + Results = Service.Install(Configuration); } [Fact] - public void should_install_where_install_location_reports() + public void Should_install_where_install_location_reports() { foreach (var packageResult in Results) { @@ -2588,7 +2588,7 @@ public void should_install_where_install_location_reports() } [Fact] - public void should_install_a_package_in_the_lib_directory() + public void Should_install_a_package_in_the_lib_directory() { var packageDir = Path.Combine(Scenario.get_top_level(), "lib", Configuration.PackageNames); @@ -2596,20 +2596,20 @@ public void should_install_a_package_in_the_lib_directory() } [Fact] - public void should_upgrade_the_dependency() + public void Should_upgrade_the_dependency() { var packageFile = Path.Combine(Scenario.get_top_level(), "lib", "isdependency", "isdependency.nupkg"); using (var packageReader = new PackageArchiveReader(packageFile)) { - packageReader.NuspecReader.GetVersion().to_string().ShouldEqual("1.0.1"); + packageReader.NuspecReader.GetVersion().ToStringSafe().ShouldEqual("1.0.1"); } } [Fact] - public void should_contain_a_message_that_it_installed_successfully() + public void Should_contain_a_message_that_it_installed_successfully() { bool expectedMessage = false; - foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).or_empty_list_if_null()) + foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).OrEmpty()) { if (message.Contains("installed 2/2")) expectedMessage = true; } @@ -2618,7 +2618,7 @@ public void should_contain_a_message_that_it_installed_successfully() } [Fact] - public void should_have_a_successful_package_result() + public void Should_have_a_successful_package_result() { foreach (var packageResult in Results) { @@ -2627,7 +2627,7 @@ public void should_have_a_successful_package_result() } [Fact] - public void should_not_have_inconclusive_package_result() + public void Should_not_have_inconclusive_package_result() { foreach (var packageResult in Results) { @@ -2636,7 +2636,7 @@ public void should_not_have_inconclusive_package_result() } [Fact] - public void should_not_have_warning_package_result() + public void Should_not_have_warning_package_result() { foreach (var packageResult in Results) { @@ -2645,7 +2645,7 @@ public void should_not_have_warning_package_result() } } - public class when_installing_a_package_with_dependencies_on_a_newer_version_of_a_package_than_are_allowed_by_an_existing_package_with_that_dependency : ScenariosBase + public class When_installing_a_package_with_dependencies_on_a_newer_version_of_a_package_than_are_allowed_by_an_existing_package_with_that_dependency : ScenariosBase { public override void Context() { @@ -2661,11 +2661,11 @@ public override void Context() public override void Because() { - Results = Service.install_run(Configuration); + Results = Service.Install(Configuration); } [Fact] - public void should_not_install_the_conflicting_package() + public void Should_not_install_the_conflicting_package() { foreach (var packageResult in Results) { @@ -2674,7 +2674,7 @@ public void should_not_install_the_conflicting_package() } [Fact] - public void should_not_install_the_conflicting_package_in_the_lib_directory() + public void Should_not_install_the_conflicting_package_in_the_lib_directory() { var packageDir = Path.Combine(Scenario.get_top_level(), "lib", Configuration.PackageNames); @@ -2682,30 +2682,30 @@ public void should_not_install_the_conflicting_package_in_the_lib_directory() } [Fact] - public void should_not_upgrade_the_minimum_version_dependency() + public void Should_not_upgrade_the_minimum_version_dependency() { var packageFile = Path.Combine(Scenario.get_top_level(), "lib", "isdependency", "isdependency.nupkg"); using (var packageReader = new PackageArchiveReader(packageFile)) { - packageReader.NuspecReader.GetVersion().to_string().ShouldEqual("1.0.0"); + packageReader.NuspecReader.GetVersion().ToStringSafe().ShouldEqual("1.0.0"); } } [Fact] - public void should_not_upgrade_the_exact_version_dependency() + public void Should_not_upgrade_the_exact_version_dependency() { var packageFile = Path.Combine(Scenario.get_top_level(), "lib", "isexactversiondependency", "isexactversiondependency.nupkg"); using (var packageReader = new PackageArchiveReader(packageFile)) { - packageReader.NuspecReader.GetVersion().to_string().ShouldEqual("1.0.0"); + packageReader.NuspecReader.GetVersion().ToStringSafe().ShouldEqual("1.0.0"); } } [Fact] - public void should_contain_a_message_that_it_was_unable_to_install_any_packages() + public void Should_contain_a_message_that_it_was_unable_to_install_any_packages() { bool expectedMessage = false; - foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).or_empty_list_if_null()) + foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).OrEmpty()) { if (message.Contains("installed 0/1")) expectedMessage = true; } @@ -2714,7 +2714,7 @@ public void should_contain_a_message_that_it_was_unable_to_install_any_packages( } [Fact] - public void should_not_have_a_successful_package_result() + public void Should_not_have_a_successful_package_result() { foreach (var packageResult in Results) { @@ -2723,7 +2723,7 @@ public void should_not_have_a_successful_package_result() } [Fact] - public void should_not_have_inconclusive_package_result() + public void Should_not_have_inconclusive_package_result() { foreach (var packageResult in Results) { @@ -2732,7 +2732,7 @@ public void should_not_have_inconclusive_package_result() } [Fact] - public void should_not_have_warning_package_result() + public void Should_not_have_warning_package_result() { foreach (var packageResult in Results) { @@ -2741,7 +2741,7 @@ public void should_not_have_warning_package_result() } [Fact] - public void should_have_an_error_package_result() + public void Should_have_an_error_package_result() { bool errorFound = false; @@ -2760,7 +2760,7 @@ public void should_have_an_error_package_result() } } - public class when_installing_a_package_with_dependencies_on_an_older_version_of_a_package_than_is_already_installed : ScenariosBase + public class When_installing_a_package_with_dependencies_on_an_older_version_of_a_package_than_is_already_installed : ScenariosBase { public override void Context() { @@ -2782,11 +2782,11 @@ public override void Context() public override void Because() { - Results = Service.install_run(Configuration); + Results = Service.Install(Configuration); } [Fact] - public void should_not_install_the_conflicting_package_in_the_lib_directory() + public void Should_not_install_the_conflicting_package_in_the_lib_directory() { var packageDir = Path.Combine(Scenario.get_top_level(), "lib", Configuration.PackageNames); @@ -2794,20 +2794,20 @@ public void should_not_install_the_conflicting_package_in_the_lib_directory() } [Fact] - public void should_not_downgrade_the_exact_version_dependency() + public void Should_not_downgrade_the_exact_version_dependency() { var packageFile = Path.Combine(Scenario.get_top_level(), "lib", "isexactversiondependency", "isexactversiondependency.nupkg"); using (var packageReader = new PackageArchiveReader(packageFile)) { - packageReader.NuspecReader.GetVersion().to_string().ShouldEqual("2.0.0"); + packageReader.NuspecReader.GetVersion().ToStringSafe().ShouldEqual("2.0.0"); } } [Fact] - public void should_contain_a_message_that_it_was_unable_to_install_any_packages() + public void Should_contain_a_message_that_it_was_unable_to_install_any_packages() { bool expectedMessage = false; - foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).or_empty_list_if_null()) + foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).OrEmpty()) { if (message.Contains("installed 0/1")) expectedMessage = true; } @@ -2816,7 +2816,7 @@ public void should_contain_a_message_that_it_was_unable_to_install_any_packages( } [Fact] - public void should_not_have_a_successful_package_result() + public void Should_not_have_a_successful_package_result() { foreach (var packageResult in Results) { @@ -2825,7 +2825,7 @@ public void should_not_have_a_successful_package_result() } [Fact] - public void should_not_have_inconclusive_package_result() + public void Should_not_have_inconclusive_package_result() { foreach (var packageResult in Results) { @@ -2834,7 +2834,7 @@ public void should_not_have_inconclusive_package_result() } [Fact] - public void should_not_have_warning_package_result() + public void Should_not_have_warning_package_result() { foreach (var packageResult in Results) { @@ -2843,7 +2843,7 @@ public void should_not_have_warning_package_result() } [Fact] - public void should_have_an_error_package_result() + public void Should_have_an_error_package_result() { bool errorFound = false; @@ -2862,7 +2862,7 @@ public void should_have_an_error_package_result() } } - public class when_installing_a_package_with_a_dependent_package_that_also_depends_on_a_less_constrained_but_still_valid_dependency_of_the_same_package : ScenariosBase + public class When_installing_a_package_with_a_dependent_package_that_also_depends_on_a_less_constrained_but_still_valid_dependency_of_the_same_package : ScenariosBase { public override void Context() { @@ -2875,7 +2875,7 @@ public override void Context() public override void Because() { - Results = Service.install_run(Configuration); + Results = Service.Install(Configuration); } /* @@ -2886,7 +2886,7 @@ public override void Because() */ [Fact] - public void should_install_where_install_location_reports() + public void Should_install_where_install_location_reports() { foreach (var packageResult in Results) { @@ -2895,7 +2895,7 @@ public void should_install_where_install_location_reports() } [Fact] - public void should_install_a_package_in_the_lib_directory() + public void Should_install_a_package_in_the_lib_directory() { var packageDir = Path.Combine(Scenario.get_top_level(), "lib", Configuration.PackageNames); @@ -2903,7 +2903,7 @@ public void should_install_a_package_in_the_lib_directory() } [Fact] - public void should_install_the_dependency_in_the_lib_directory() + public void Should_install_the_dependency_in_the_lib_directory() { var packageDir = Path.Combine(Scenario.get_top_level(), "lib", "childdependencywithlooserversiondependency"); @@ -2911,30 +2911,30 @@ public void should_install_the_dependency_in_the_lib_directory() } [Fact] - public void should_install_the_expected_version_of_the_dependency() + public void Should_install_the_expected_version_of_the_dependency() { var packageFile = Path.Combine(Scenario.get_top_level(), "lib", "childdependencywithlooserversiondependency", "childdependencywithlooserversiondependency.nupkg"); using (var packageReader = new PackageArchiveReader(packageFile)) { - packageReader.NuspecReader.GetVersion().to_string().ShouldEqual("1.0.0"); + packageReader.NuspecReader.GetVersion().ToStringSafe().ShouldEqual("1.0.0"); } } [Fact] - public void should_install_the_expected_version_of_the_constrained_dependency() + public void Should_install_the_expected_version_of_the_constrained_dependency() { var packageFile = Path.Combine(Scenario.get_top_level(), "lib", "isexactversiondependency", "isexactversiondependency.nupkg"); using (var packageReader = new PackageArchiveReader(packageFile)) { - packageReader.NuspecReader.GetVersion().to_string().ShouldEqual("1.0.0"); + packageReader.NuspecReader.GetVersion().ToStringSafe().ShouldEqual("1.0.0"); } } [Fact] - public void should_contain_a_message_that_everything_installed_successfully() + public void Should_contain_a_message_that_everything_installed_successfully() { bool expectedMessage = false; - foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).or_empty_list_if_null()) + foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).OrEmpty()) { if (message.Contains("3/3")) expectedMessage = true; } @@ -2943,7 +2943,7 @@ public void should_contain_a_message_that_everything_installed_successfully() } [Fact] - public void should_have_a_successful_package_result() + public void Should_have_a_successful_package_result() { foreach (var packageResult in Results) { @@ -2952,7 +2952,7 @@ public void should_have_a_successful_package_result() } [Fact] - public void should_not_have_inconclusive_package_result() + public void Should_not_have_inconclusive_package_result() { foreach (var packageResult in Results) { @@ -2961,7 +2961,7 @@ public void should_not_have_inconclusive_package_result() } [Fact] - public void should_not_have_warning_package_result() + public void Should_not_have_warning_package_result() { foreach (var packageResult in Results) { @@ -2970,21 +2970,21 @@ public void should_not_have_warning_package_result() } } - public class when_installing_a_package_from_a_nupkg_file : ScenariosBase + public class When_installing_a_package_from_a_nupkg_file : ScenariosBase { private Exception _exception; public override void Context() { base.Context(); - Configuration.PackageNames = Configuration.Input = "{0}{1}installpackage.1.0.0.nupkg".format_with(Configuration.Sources, Path.DirectorySeparatorChar); + Configuration.PackageNames = Configuration.Input = "{0}{1}installpackage.1.0.0.nupkg".FormatWith(Configuration.Sources, Path.DirectorySeparatorChar); } public override void Because() { try { - Results = Service.install_run(Configuration); + Results = Service.Install(Configuration); } catch (Exception ex) { @@ -2993,27 +2993,27 @@ public override void Because() } [Fact] - public void should_have_thrown_exception_when_installing() + public void Should_have_thrown_exception_when_installing() { _exception.ShouldBeType(); } [Fact] - public void should_have_outputted_expected_exception_message() + public void Should_have_outputted_expected_exception_message() { // We use a string builder here to ensure that the same line endings are used. var expectedMessage = new StringBuilder("Package name cannot be a path to a file on a remote, or local file system.") .AppendLine() .AppendLine() .AppendLine("To install a local, or remote file, you may use:") - .AppendLine(" choco install installpackage --version=\"1.0.0\" --source=\"{0}\"".format_with(Configuration.Sources)) + .AppendLine(" choco install installpackage --version=\"1.0.0\" --source=\"{0}\"".FormatWith(Configuration.Sources)) .ToString(); _exception.Message.ShouldEqual(expectedMessage); } [Fact] - public void should_not_install_the_package_in_the_lib_directory() + public void Should_not_install_the_package_in_the_lib_directory() { var packageDir = Path.Combine(Scenario.get_top_level(), "lib", "installpackage"); @@ -3021,7 +3021,7 @@ public void should_not_install_the_package_in_the_lib_directory() } [Fact] - public void should_not_install_the_package_in_the_lib_bad_directory() + public void Should_not_install_the_package_in_the_lib_bad_directory() { var packageDir = Path.Combine(Scenario.get_top_level(), "lib-bad", "installpackage"); @@ -3029,7 +3029,7 @@ public void should_not_install_the_package_in_the_lib_bad_directory() } [Fact] - public void should_not_install_the_package_in_the_lib_backup_directory() + public void Should_not_install_the_package_in_the_lib_backup_directory() { var packageDir = Path.Combine(Scenario.get_top_level(), "lib-bkp", "installpackage"); @@ -3037,21 +3037,21 @@ public void should_not_install_the_package_in_the_lib_backup_directory() } } - public class when_installing_a_package_from_a_prerelease_nupkg_file : ScenariosBase + public class When_installing_a_package_from_a_prerelease_nupkg_file : ScenariosBase { private Exception _exception; public override void Context() { base.Context(); - Configuration.PackageNames = Configuration.Input = "{0}{1}installpackage.0.56-alpha-0544.nupkg".format_with(Configuration.Sources, Path.DirectorySeparatorChar); + Configuration.PackageNames = Configuration.Input = "{0}{1}installpackage.0.56-alpha-0544.nupkg".FormatWith(Configuration.Sources, Path.DirectorySeparatorChar); } public override void Because() { try { - Results = Service.install_run(Configuration); + Results = Service.Install(Configuration); } catch (Exception ex) { @@ -3060,27 +3060,27 @@ public override void Because() } [Fact] - public void should_have_thrown_exception_when_installing() + public void Should_have_thrown_exception_when_installing() { _exception.ShouldBeType(); } [Fact] - public void should_have_outputted_expected_exception_message() + public void Should_have_outputted_expected_exception_message() { // We use a string builder here to ensure that the same line endings are used. var expectedMessage = new StringBuilder("Package name cannot be a path to a file on a remote, or local file system.") .AppendLine() .AppendLine() .AppendLine("To install a local, or remote file, you may use:") - .AppendLine(" choco install installpackage --version=\"0.56.0-alpha-0544\" --prerelease --source=\"{0}\"".format_with(Configuration.Sources)) + .AppendLine(" choco install installpackage --version=\"0.56.0-alpha-0544\" --prerelease --source=\"{0}\"".FormatWith(Configuration.Sources)) .ToString(); _exception.Message.ShouldEqual(expectedMessage); } [Fact] - public void should_not_install_the_package_in_the_lib_directory() + public void Should_not_install_the_package_in_the_lib_directory() { var packageDir = Path.Combine(Scenario.get_top_level(), "lib", "installpackage"); @@ -3088,7 +3088,7 @@ public void should_not_install_the_package_in_the_lib_directory() } [Fact] - public void should_not_install_the_package_in_the_lib_bad_directory() + public void Should_not_install_the_package_in_the_lib_bad_directory() { var packageDir = Path.Combine(Scenario.get_top_level(), "lib-bad", "installpackage"); @@ -3096,7 +3096,7 @@ public void should_not_install_the_package_in_the_lib_bad_directory() } [Fact] - public void should_not_install_the_package_in_the_lib_backup_directory() + public void Should_not_install_the_package_in_the_lib_backup_directory() { var packageDir = Path.Combine(Scenario.get_top_level(), "lib-bkp", "installpackage"); @@ -3105,7 +3105,7 @@ public void should_not_install_the_package_in_the_lib_backup_directory() } [Categories.Unc] - public class when_installing_a_package_from_a_nupkg_file_and_unc_path : ScenariosBase + public class When_installing_a_package_from_a_nupkg_file_and_unc_path : ScenariosBase { private Exception _exception; @@ -3114,14 +3114,14 @@ public override void Context() base.Context(); Configuration.Sources = UNCHelper.convert_local_folder_path_to_ip_based_unc_path(Configuration.Sources); - Configuration.PackageNames = Configuration.Input = "{0}{1}installpackage.1.0.0.nupkg".format_with(Configuration.Sources, Path.DirectorySeparatorChar); + Configuration.PackageNames = Configuration.Input = "{0}{1}installpackage.1.0.0.nupkg".FormatWith(Configuration.Sources, Path.DirectorySeparatorChar); } public override void Because() { try { - Results = Service.install_run(Configuration); + Results = Service.Install(Configuration); } catch (Exception ex) { @@ -3130,27 +3130,27 @@ public override void Because() } [Fact] - public void should_have_thrown_exception_when_installing() + public void Should_have_thrown_exception_when_installing() { _exception.ShouldBeType(); } [Fact] - public void should_have_outputted_expected_exception_message() + public void Should_have_outputted_expected_exception_message() { // We use a string builder here to ensure that the same line endings are used. var expectedMessage = new StringBuilder("Package name cannot be a path to a file on a UNC location.") .AppendLine() .AppendLine() .AppendLine("To install a file in a UNC location, you may use:") - .AppendLine(" choco install installpackage --version=\"1.0.0\" --source=\"{0}\"".format_with(Configuration.Sources)) + .AppendLine(" choco install installpackage --version=\"1.0.0\" --source=\"{0}\"".FormatWith(Configuration.Sources)) .ToString(); _exception.Message.ShouldEqual(expectedMessage); } [Fact] - public void should_not_install_the_package_in_the_lib_directory() + public void Should_not_install_the_package_in_the_lib_directory() { var packageDir = Path.Combine(Scenario.get_top_level(), "lib", "installpackage"); @@ -3158,7 +3158,7 @@ public void should_not_install_the_package_in_the_lib_directory() } [Fact] - public void should_not_install_the_package_in_the_lib_bad_directory() + public void Should_not_install_the_package_in_the_lib_bad_directory() { var packageDir = Path.Combine(Scenario.get_top_level(), "lib-bad", "installpackage"); @@ -3166,7 +3166,7 @@ public void should_not_install_the_package_in_the_lib_bad_directory() } [Fact] - public void should_not_install_the_package_in_the_lib_backup_directory() + public void Should_not_install_the_package_in_the_lib_backup_directory() { var packageDir = Path.Combine(Scenario.get_top_level(), "lib-bkp", "installpackage"); @@ -3174,7 +3174,7 @@ public void should_not_install_the_package_in_the_lib_backup_directory() } } - public class when_installing_a_package_from_a_remote_nupkg_file : ScenariosBase + public class When_installing_a_package_from_a_remote_nupkg_file : ScenariosBase { private Exception _exception; @@ -3189,7 +3189,7 @@ public override void Because() { try { - Results = Service.install_run(Configuration); + Results = Service.Install(Configuration); } catch (Exception ex) { @@ -3198,19 +3198,19 @@ public override void Because() } [Fact] - public void should_have_thrown_exception_when_installing() + public void Should_have_thrown_exception_when_installing() { _exception.ShouldBeType(); } [Fact] - public void should_have_outputted_expected_exception_message() + public void Should_have_outputted_expected_exception_message() { _exception.Message.ShouldEqual("Package name cannot point directly to a local, or remote file. Please use the --source argument and point it to a local file directory, UNC directory path or a NuGet feed instead."); } [Fact] - public void should_not_install_the_package_in_the_lib_directory() + public void Should_not_install_the_package_in_the_lib_directory() { var packageDir = Path.Combine(Scenario.get_top_level(), "lib", "installpackage"); @@ -3218,7 +3218,7 @@ public void should_not_install_the_package_in_the_lib_directory() } [Fact] - public void should_not_install_the_package_in_the_lib_bad_directory() + public void Should_not_install_the_package_in_the_lib_bad_directory() { var packageDir = Path.Combine(Scenario.get_top_level(), "lib-bad", "installpackage"); @@ -3226,7 +3226,7 @@ public void should_not_install_the_package_in_the_lib_bad_directory() } [Fact] - public void should_not_install_the_package_in_the_lib_backup_directory() + public void Should_not_install_the_package_in_the_lib_backup_directory() { var packageDir = Path.Combine(Scenario.get_top_level(), "lib-bkp", "installpackage"); @@ -3234,7 +3234,7 @@ public void should_not_install_the_package_in_the_lib_backup_directory() } } - public class when_installing_a_package_from_a_manifest_file : ScenariosBase + public class When_installing_a_package_from_a_manifest_file : ScenariosBase { private Exception _exception; @@ -3242,14 +3242,14 @@ public override void Context() { base.Context(); - Configuration.PackageNames = Configuration.Input = "{0}{1}installpackage.nuspec".format_with(Configuration.Sources, Path.DirectorySeparatorChar); + Configuration.PackageNames = Configuration.Input = "{0}{1}installpackage.nuspec".FormatWith(Configuration.Sources, Path.DirectorySeparatorChar); } public override void Because() { try { - Results = Service.install_run(Configuration); + Results = Service.Install(Configuration); } catch (Exception ex) { @@ -3258,19 +3258,19 @@ public override void Because() } [Fact] - public void should_have_thrown_exception_when_installing() + public void Should_have_thrown_exception_when_installing() { _exception.ShouldBeType(); } [Fact] - public void should_have_outputted_expected_exception_message() + public void Should_have_outputted_expected_exception_message() { _exception.Message.ShouldEqual("Package name cannot point directly to a package manifest file. Please create a package by running 'choco pack' on the .nuspec file first."); } [Fact] - public void should_not_install_the_package_in_the_lib_directory() + public void Should_not_install_the_package_in_the_lib_directory() { var packageDir = Path.Combine(Scenario.get_top_level(), "lib", "installpackage"); @@ -3278,7 +3278,7 @@ public void should_not_install_the_package_in_the_lib_directory() } [Fact] - public void should_not_install_the_package_in_the_lib_bad_directory() + public void Should_not_install_the_package_in_the_lib_bad_directory() { var packageDir = Path.Combine(Scenario.get_top_level(), "lib-bad", "installpackage"); @@ -3286,7 +3286,7 @@ public void should_not_install_the_package_in_the_lib_bad_directory() } [Fact] - public void should_not_install_the_package_in_the_lib_backup_directory() + public void Should_not_install_the_package_in_the_lib_backup_directory() { var packageDir = Path.Combine(Scenario.get_top_level(), "lib-bkp", "installpackage"); @@ -3294,7 +3294,7 @@ public void should_not_install_the_package_in_the_lib_backup_directory() } } - public class when_installing_a_package_with_config_transforms : ScenariosBase + public class When_installing_a_package_with_config_transforms : ScenariosBase { private PackageResult packageResult; private string _xmlFilePath = string.Empty; @@ -3311,27 +3311,27 @@ public override void Context() public override void Because() { - Results = Service.install_run(Configuration); + Results = Service.Install(Configuration); packageResult = Results.FirstOrDefault().Value; var xmlDocument = new XPathDocument(_xmlFilePath); _xPathNavigator = xmlDocument.CreateNavigator(); } [Fact] - public void should_install_the_expected_version_of_the_package() + public void Should_install_the_expected_version_of_the_package() { var packageFile = Path.Combine(Scenario.get_top_level(), "lib", Configuration.PackageNames, Configuration.PackageNames + NuGetConstants.PackageExtension); using (var packageReader = new PackageArchiveReader(packageFile)) { - packageReader.NuspecReader.GetVersion().to_string().ShouldEqual("1.0.0"); + packageReader.NuspecReader.GetVersion().ToStringSafe().ShouldEqual("1.0.0"); } } [Fact] - public void should_contain_a_warning_message_that_it_installed_successfully() + public void Should_contain_a_warning_message_that_it_installed_successfully() { bool installedSuccessfully = false; - foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).or_empty_list_if_null()) + foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).OrEmpty()) { if (message.Contains("1/1")) installedSuccessfully = true; } @@ -3340,49 +3340,49 @@ public void should_contain_a_warning_message_that_it_installed_successfully() } [Fact] - public void should_have_a_successful_package_result() + public void Should_have_a_successful_package_result() { packageResult.Success.ShouldBeTrue(); } [Fact] - public void should_not_have_inconclusive_package_result() + public void Should_not_have_inconclusive_package_result() { packageResult.Inconclusive.ShouldBeFalse(); } [Fact] - public void should_not_have_warning_package_result() + public void Should_not_have_warning_package_result() { packageResult.Warning.ShouldBeFalse(); } [Fact] - public void should_have_a_version_of_one_dot_zero_dot_zero() + public void Should_have_a_version_of_one_dot_zero_dot_zero() { packageResult.Version.ShouldEqual("1.0.0"); } [Fact] - public void should_not_change_the_test_value_in_the_config_due_to_XDT_InsertIfMissing() + public void Should_not_change_the_test_value_in_the_config_due_to_XDT_InsertIfMissing() { - _xPathNavigator.SelectSingleNode("//configuration/appSettings/add[@key='test']/@value").TypedValue.to_string().ShouldEqual("default 1.0.0"); + _xPathNavigator.SelectSingleNode("//configuration/appSettings/add[@key='test']/@value").TypedValue.ToStringSafe().ShouldEqual("default 1.0.0"); } [Fact] - public void should_change_the_testReplace_value_in_the_config_due_to_XDT_Replace() + public void Should_change_the_testReplace_value_in_the_config_due_to_XDT_Replace() { - _xPathNavigator.SelectSingleNode("//configuration/appSettings/add[@key='testReplace']/@value").TypedValue.to_string().ShouldEqual("1.0.0"); + _xPathNavigator.SelectSingleNode("//configuration/appSettings/add[@key='testReplace']/@value").TypedValue.ToStringSafe().ShouldEqual("1.0.0"); } [Fact] - public void should_add_the_insert_value_in_the_config_due_to_XDT_InsertIfMissing() + public void Should_add_the_insert_value_in_the_config_due_to_XDT_InsertIfMissing() { - _xPathNavigator.SelectSingleNode("//configuration/appSettings/add[@key='insert']/@value").TypedValue.to_string().ShouldEqual("1.0.0"); + _xPathNavigator.SelectSingleNode("//configuration/appSettings/add[@key='insert']/@value").TypedValue.ToStringSafe().ShouldEqual("1.0.0"); } } - public class when_installing_a_package_with_no_sources_enabled : ScenariosBase + public class When_installing_a_package_with_no_sources_enabled : ScenariosBase { public override void Context() { @@ -3392,23 +3392,23 @@ public override void Context() public override void Because() { - Results = Service.install_run(Configuration); + Results = Service.Install(Configuration); } [Fact] - public void should_have_no_sources_enabled_result() + public void Should_have_no_sources_enabled_result() { - MockLogger.contains_message("Installation was NOT successful. There are no sources enabled for", LogLevel.Error).ShouldBeTrue(); + MockLogger.ContainsMessage("Installation was NOT successful. There are no sources enabled for", LogLevel.Error).ShouldBeTrue(); } [Fact] - public void should_not_install_any_packages() + public void Should_not_install_any_packages() { Results.Count().ShouldEqual(0); } } - public class when_installing_a_hook_package : ScenariosBase + public class When_installing_a_hook_package : ScenariosBase { public override void Context() { @@ -3421,12 +3421,12 @@ public override void Context() public override void Because() { - Results = Service.install_run(Configuration); + Results = Service.Install(Configuration); _packageResult = Results.FirstOrDefault().Value; } [Fact] - public void should_install_the_package_in_the_lib_directory() + public void Should_install_the_package_in_the_lib_directory() { var packageDir = Path.Combine(Scenario.get_top_level(), "lib", Configuration.PackageNames); @@ -3434,17 +3434,17 @@ public void should_install_the_package_in_the_lib_directory() } [Fact] - public void should_install_the_expected_version_of_the_package() + public void Should_install_the_expected_version_of_the_package() { var packageFile = Path.Combine(Scenario.get_top_level(), "lib", Configuration.PackageNames, Configuration.PackageNames + NuGetConstants.PackageExtension); using (var packageReader = new PackageArchiveReader(packageFile)) { - packageReader.NuspecReader.GetVersion().to_string().ShouldEqual("1.0.0"); + packageReader.NuspecReader.GetVersion().ToStringSafe().ShouldEqual("1.0.0"); } } [Fact] - public void should_not_create_an_extensions_folder_for_the_package() + public void Should_not_create_an_extensions_folder_for_the_package() { var extensionsDirectory = Path.Combine(Scenario.get_top_level(), "extensions", Configuration.PackageNames); @@ -3452,7 +3452,7 @@ public void should_not_create_an_extensions_folder_for_the_package() } [Fact] - public void should_create_a_hooks_folder_for_the_package() + public void Should_create_a_hooks_folder_for_the_package() { var hooksDirectory = Path.Combine(Scenario.get_top_level(), "hooks", Configuration.PackageNames.Replace(".hook", string.Empty)); @@ -3460,7 +3460,7 @@ public void should_create_a_hooks_folder_for_the_package() } [Fact] - public void should_install_hook_scripts_to_folder() + public void Should_install_hook_scripts_to_folder() { var hookScripts = new List { "pre-install-all.ps1", "post-install-all.ps1", "pre-upgrade-all.ps1", "post-upgrade-all.ps1", "pre-uninstall-all.ps1", "post-uninstall-all.ps1" }; foreach (string scriptName in hookScripts) @@ -3471,10 +3471,10 @@ public void should_install_hook_scripts_to_folder() } [Fact] - public void should_contain_a_warning_message_that_it_installed_successfully() + public void Should_contain_a_warning_message_that_it_installed_successfully() { bool installedSuccessfully = false; - foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).or_empty_list_if_null()) + foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).OrEmpty()) { if (message.Contains("1/1")) installedSuccessfully = true; } @@ -3483,38 +3483,38 @@ public void should_contain_a_warning_message_that_it_installed_successfully() } [Fact] - public void should_have_a_successful_package_result() + public void Should_have_a_successful_package_result() { _packageResult.Success.ShouldBeTrue(); } [Fact] - public void should_not_have_inconclusive_package_result() + public void Should_not_have_inconclusive_package_result() { _packageResult.Inconclusive.ShouldBeFalse(); } [Fact] - public void should_not_have_warning_package_result() + public void Should_not_have_warning_package_result() { _packageResult.Warning.ShouldBeFalse(); } [Fact] - public void config_should_match_package_result_name() + public void Config_should_match_package_result_name() { _packageResult.Name.ShouldEqual(Configuration.PackageNames); } [Fact] - public void should_have_a_version_of_one_dot_zero_dot_zero() + public void Should_have_a_version_of_one_dot_zero_dot_zero() { _packageResult.Version.ShouldEqual("1.0.0"); } } - public class when_installing_a_package_happy_path_with_hook_scripts : ScenariosBase + public class When_installing_a_package_happy_path_with_hook_scripts : ScenariosBase { private PackageResult _packageResult; @@ -3528,18 +3528,18 @@ public override void Context() public override void Because() { - Results = Service.install_run(Configuration); + Results = Service.Install(Configuration); _packageResult = Results.FirstOrDefault().Value; } [Fact] - public void should_install_where_install_location_reports() + public void Should_install_where_install_location_reports() { DirectoryAssert.Exists(_packageResult.InstallLocation); } [Fact] - public void should_install_the_package_in_the_lib_directory() + public void Should_install_the_package_in_the_lib_directory() { var packageDir = Path.Combine(Scenario.get_top_level(), "lib", Configuration.PackageNames); @@ -3547,19 +3547,19 @@ public void should_install_the_package_in_the_lib_directory() } [Fact] - public void should_install_the_expected_version_of_the_package() + public void Should_install_the_expected_version_of_the_package() { var packageFile = Path.Combine(Scenario.get_top_level(), "lib", Configuration.PackageNames, Configuration.PackageNames + NuGetConstants.PackageExtension); using (var packageReader = new PackageArchiveReader(packageFile)) { - packageReader.NuspecReader.GetVersion().to_string().ShouldEqual("1.0.0"); + packageReader.NuspecReader.GetVersion().ToStringSafe().ShouldEqual("1.0.0"); } } [Fact] [WindowsOnly] [Platform(Exclude = "Mono")] - public void should_create_a_shim_for_console_in_the_bin_directory() + public void Should_create_a_shim_for_console_in_the_bin_directory() { var shimfile = Path.Combine(Scenario.get_top_level(), "bin", "console.exe"); @@ -3569,7 +3569,7 @@ public void should_create_a_shim_for_console_in_the_bin_directory() [Fact] [WindowsOnly] [Platform(Exclude = "Mono")] - public void should_create_a_shim_for_graphical_in_the_bin_directory() + public void Should_create_a_shim_for_graphical_in_the_bin_directory() { var shimfile = Path.Combine(Scenario.get_top_level(), "bin", "graphical.exe"); @@ -3577,7 +3577,7 @@ public void should_create_a_shim_for_graphical_in_the_bin_directory() } [Fact] - public void should_not_create_a_shim_for_ignored_executable_in_the_bin_directory() + public void Should_not_create_a_shim_for_ignored_executable_in_the_bin_directory() { var shimfile = Path.Combine(Scenario.get_top_level(), "bin", "not.installed.exe"); @@ -3585,7 +3585,7 @@ public void should_not_create_a_shim_for_ignored_executable_in_the_bin_directory } [Fact] - public void should_not_create_a_shim_for_mismatched_case_ignored_executable_in_the_bin_directory() + public void Should_not_create_a_shim_for_mismatched_case_ignored_executable_in_the_bin_directory() { var shimfile = Path.Combine(Scenario.get_top_level(), "bin", "casemismatch.exe"); @@ -3593,7 +3593,7 @@ public void should_not_create_a_shim_for_mismatched_case_ignored_executable_in_t } [Fact] - public void should_not_create_an_extensions_folder_for_the_package() + public void Should_not_create_an_extensions_folder_for_the_package() { var extensionsDirectory = Path.Combine(Scenario.get_top_level(), "extensions", Configuration.PackageNames); @@ -3601,7 +3601,7 @@ public void should_not_create_an_extensions_folder_for_the_package() } [Fact] - public void should_not_create_an_hooks_folder_for_the_package() + public void Should_not_create_an_hooks_folder_for_the_package() { var hooksDirectory = Path.Combine(Scenario.get_top_level(), "hooks", Configuration.PackageNames); @@ -3611,12 +3611,12 @@ public void should_not_create_an_hooks_folder_for_the_package() [Fact] [WindowsOnly] [Platform(Exclude = "Mono")] - public void should_have_a_console_shim_that_is_set_for_non_gui_access() + public void Should_have_a_console_shim_that_is_set_for_non_gui_access() { var messages = new List(); var shimfile = Path.Combine(Scenario.get_top_level(), "bin", "console.exe"); - CommandExecutor.execute( + CommandExecutor.Execute( shimfile, "--shimgen-noop", 10, @@ -3626,7 +3626,7 @@ public void should_have_a_console_shim_that_is_set_for_non_gui_access() var messageFound = false; - foreach (var message in messages.or_empty_list_if_null()) + foreach (var message in messages.OrEmpty()) { if (string.IsNullOrWhiteSpace(message)) continue; if (message.Contains("is gui? False")) messageFound = true; @@ -3638,12 +3638,12 @@ public void should_have_a_console_shim_that_is_set_for_non_gui_access() [Fact] [WindowsOnly] [Platform(Exclude = "Mono")] - public void should_have_a_graphical_shim_that_is_set_for_gui_access() + public void Should_have_a_graphical_shim_that_is_set_for_gui_access() { var messages = new List(); var shimfile = Path.Combine(Scenario.get_top_level(), "bin", "graphical.exe"); - CommandExecutor.execute( + CommandExecutor.Execute( shimfile, "--shimgen-noop", 10, @@ -3653,7 +3653,7 @@ public void should_have_a_graphical_shim_that_is_set_for_gui_access() var messageFound = false; - foreach (var message in messages.or_empty_list_if_null()) + foreach (var message in messages.OrEmpty()) { if (string.IsNullOrWhiteSpace(message)) continue; if (message.Contains("is gui? True")) messageFound = true; @@ -3663,10 +3663,10 @@ public void should_have_a_graphical_shim_that_is_set_for_gui_access() } [Fact] - public void should_contain_a_warning_message_that_it_installed_successfully() + public void Should_contain_a_warning_message_that_it_installed_successfully() { bool installedSuccessfully = false; - foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).or_empty_list_if_null()) + foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).OrEmpty()) { if (message.Contains("1/1")) installedSuccessfully = true; } @@ -3675,31 +3675,31 @@ public void should_contain_a_warning_message_that_it_installed_successfully() } [Fact] - public void should_have_a_successful_package_result() + public void Should_have_a_successful_package_result() { _packageResult.Success.ShouldBeTrue(); } [Fact] - public void should_not_have_inconclusive_package_result() + public void Should_not_have_inconclusive_package_result() { _packageResult.Inconclusive.ShouldBeFalse(); } [Fact] - public void should_not_have_warning_package_result() + public void Should_not_have_warning_package_result() { _packageResult.Warning.ShouldBeFalse(); } [Fact] - public void config_should_match_package_result_name() + public void Config_should_match_package_result_name() { _packageResult.Name.ShouldEqual(Configuration.PackageNames); } [Fact] - public void should_have_a_version_of_one_dot_zero_dot_zero() + public void Should_have_a_version_of_one_dot_zero_dot_zero() { _packageResult.Version.ShouldEqual("1.0.0"); } @@ -3707,69 +3707,69 @@ public void should_have_a_version_of_one_dot_zero_dot_zero() [Fact] [WindowsOnly] [Platform(Exclude = "Mono")] - public void should_have_executed_chocolateyInstall_script() + public void Should_have_executed_chocolateyInstall_script() { - MockLogger.contains_message("installpackage v1.0.0 has been installed", LogLevel.Info).ShouldBeTrue(); + MockLogger.ContainsMessage("installpackage v1.0.0 has been installed", LogLevel.Info).ShouldBeTrue(); } [Fact] [WindowsOnly] [Platform(Exclude = "Mono")] - public void should_have_executed_pre_all_hook_script() + public void Should_have_executed_pre_all_hook_script() { - MockLogger.contains_message("pre-install-all.ps1 hook ran for installpackage 1.0.0", LogLevel.Info).ShouldBeTrue(); + MockLogger.ContainsMessage("pre-install-all.ps1 hook ran for installpackage 1.0.0", LogLevel.Info).ShouldBeTrue(); } [Fact] [WindowsOnly] [Platform(Exclude = "Mono")] - public void should_have_executed_post_all_hook_script() + public void Should_have_executed_post_all_hook_script() { - MockLogger.contains_message("post-install-all.ps1 hook ran for installpackage 1.0.0", LogLevel.Info).ShouldBeTrue(); + MockLogger.ContainsMessage("post-install-all.ps1 hook ran for installpackage 1.0.0", LogLevel.Info).ShouldBeTrue(); } [Fact] [WindowsOnly] [Platform(Exclude = "Mono")] - public void should_have_executed_pre_installpackage_hook_script() + public void Should_have_executed_pre_installpackage_hook_script() { - MockLogger.contains_message("pre-install-installpackage.ps1 hook ran for installpackage 1.0.0", LogLevel.Info).ShouldBeTrue(); + MockLogger.ContainsMessage("pre-install-installpackage.ps1 hook ran for installpackage 1.0.0", LogLevel.Info).ShouldBeTrue(); } [Fact] [WindowsOnly] [Platform(Exclude = "Mono")] - public void should_have_executed_post_installpackage_hook_script() + public void Should_have_executed_post_installpackage_hook_script() { - MockLogger.contains_message("post-install-installpackage.ps1 hook ran for installpackage 1.0.0", LogLevel.Info).ShouldBeTrue(); + MockLogger.ContainsMessage("post-install-installpackage.ps1 hook ran for installpackage 1.0.0", LogLevel.Info).ShouldBeTrue(); } [Fact] [WindowsOnly] [Platform(Exclude = "Mono")] - public void should_not_have_executed_uninstall_hook_script() + public void Should_not_have_executed_uninstall_hook_script() { - MockLogger.contains_message("post-uninstall-all.ps1 hook ran for installpackage 1.0.0", LogLevel.Info).ShouldBeFalse(); + MockLogger.ContainsMessage("post-uninstall-all.ps1 hook ran for installpackage 1.0.0", LogLevel.Info).ShouldBeFalse(); } [Fact] [WindowsOnly] [Platform(Exclude = "Mono")] - public void should_not_have_executed_upgradepackage_hook_script() + public void Should_not_have_executed_upgradepackage_hook_script() { - MockLogger.contains_message("pre-install-upgradepackage.ps1 hook ran for installpackage 1.0.0", LogLevel.Info).ShouldBeFalse(); + MockLogger.ContainsMessage("pre-install-upgradepackage.ps1 hook ran for installpackage 1.0.0", LogLevel.Info).ShouldBeFalse(); } [Fact] [WindowsOnly] [Platform(Exclude = "Mono")] - public void should_not_have_executed_beforemodify_hook_script() + public void Should_not_have_executed_beforemodify_hook_script() { - MockLogger.contains_message("pre-beforemodify-all.ps1 hook ran for installpackage 1.0.0", LogLevel.Info).ShouldBeFalse(); + MockLogger.ContainsMessage("pre-beforemodify-all.ps1 hook ran for installpackage 1.0.0", LogLevel.Info).ShouldBeFalse(); } } - public class when_installing_a_portable_package_happy_path_with_hook_scripts : ScenariosBase + public class When_installing_a_portable_package_happy_path_with_hook_scripts : ScenariosBase { private PackageResult _packageResult; @@ -3784,18 +3784,18 @@ public override void Context() public override void Because() { - Results = Service.install_run(Configuration); + Results = Service.Install(Configuration); _packageResult = Results.FirstOrDefault().Value; } [Fact] - public void should_install_where_install_location_reports() + public void Should_install_where_install_location_reports() { DirectoryAssert.Exists(_packageResult.InstallLocation); } [Fact] - public void should_install_the_package_in_the_lib_directory() + public void Should_install_the_package_in_the_lib_directory() { var packageDir = Path.Combine(Scenario.get_top_level(), "lib", Configuration.PackageNames); @@ -3803,19 +3803,19 @@ public void should_install_the_package_in_the_lib_directory() } [Fact] - public void should_install_the_expected_version_of_the_package() + public void Should_install_the_expected_version_of_the_package() { var packageFile = Path.Combine(Scenario.get_top_level(), "lib", Configuration.PackageNames, Configuration.PackageNames + NuGetConstants.PackageExtension); using (var packageReader = new PackageArchiveReader(packageFile)) { - packageReader.NuspecReader.GetVersion().to_string().ShouldEqual("1.0.0"); + packageReader.NuspecReader.GetVersion().ToStringSafe().ShouldEqual("1.0.0"); } } [Fact] [WindowsOnly] [Platform(Exclude = "Mono")] - public void should_create_a_shim_for_console_in_the_bin_directory() + public void Should_create_a_shim_for_console_in_the_bin_directory() { var shimfile = Path.Combine(Scenario.get_top_level(), "bin", "console.exe"); @@ -3825,7 +3825,7 @@ public void should_create_a_shim_for_console_in_the_bin_directory() [Fact] [WindowsOnly] [Platform(Exclude = "Mono")] - public void should_create_a_shim_for_graphical_in_the_bin_directory() + public void Should_create_a_shim_for_graphical_in_the_bin_directory() { var shimfile = Path.Combine(Scenario.get_top_level(), "bin", "graphical.exe"); @@ -3833,7 +3833,7 @@ public void should_create_a_shim_for_graphical_in_the_bin_directory() } [Fact] - public void should_not_create_a_shim_for_ignored_executable_in_the_bin_directory() + public void Should_not_create_a_shim_for_ignored_executable_in_the_bin_directory() { var shimfile = Path.Combine(Scenario.get_top_level(), "bin", "not.installed.exe"); @@ -3841,7 +3841,7 @@ public void should_not_create_a_shim_for_ignored_executable_in_the_bin_directory } [Fact] - public void should_not_create_a_shim_for_mismatched_case_ignored_executable_in_the_bin_directory() + public void Should_not_create_a_shim_for_mismatched_case_ignored_executable_in_the_bin_directory() { var shimfile = Path.Combine(Scenario.get_top_level(), "bin", "casemismatch.exe"); @@ -3849,7 +3849,7 @@ public void should_not_create_a_shim_for_mismatched_case_ignored_executable_in_t } [Fact] - public void should_not_create_an_extensions_folder_for_the_package() + public void Should_not_create_an_extensions_folder_for_the_package() { var extensionsDirectory = Path.Combine(Scenario.get_top_level(), "extensions", Configuration.PackageNames); @@ -3857,7 +3857,7 @@ public void should_not_create_an_extensions_folder_for_the_package() } [Fact] - public void should_not_create_an_hooks_folder_for_the_package() + public void Should_not_create_an_hooks_folder_for_the_package() { var hooksDirectory = Path.Combine(Scenario.get_top_level(), "hooks", Configuration.PackageNames); @@ -3867,12 +3867,12 @@ public void should_not_create_an_hooks_folder_for_the_package() [Fact] [WindowsOnly] [Platform(Exclude = "Mono")] - public void should_have_a_console_shim_that_is_set_for_non_gui_access() + public void Should_have_a_console_shim_that_is_set_for_non_gui_access() { var messages = new List(); var shimfile = Path.Combine(Scenario.get_top_level(), "bin", "console.exe"); - CommandExecutor.execute( + CommandExecutor.Execute( shimfile, "--shimgen-noop", 10, @@ -3882,7 +3882,7 @@ public void should_have_a_console_shim_that_is_set_for_non_gui_access() var messageFound = false; - foreach (var message in messages.or_empty_list_if_null()) + foreach (var message in messages.OrEmpty()) { if (string.IsNullOrWhiteSpace(message)) continue; if (message.Contains("is gui? False")) messageFound = true; @@ -3894,12 +3894,12 @@ public void should_have_a_console_shim_that_is_set_for_non_gui_access() [Fact] [WindowsOnly] [Platform(Exclude = "Mono")] - public void should_have_a_graphical_shim_that_is_set_for_gui_access() + public void Should_have_a_graphical_shim_that_is_set_for_gui_access() { var messages = new List(); var shimfile = Path.Combine(Scenario.get_top_level(), "bin", "graphical.exe"); - CommandExecutor.execute( + CommandExecutor.Execute( shimfile, "--shimgen-noop", 10, @@ -3909,7 +3909,7 @@ public void should_have_a_graphical_shim_that_is_set_for_gui_access() var messageFound = false; - foreach (var message in messages.or_empty_list_if_null()) + foreach (var message in messages.OrEmpty()) { if (string.IsNullOrWhiteSpace(message)) continue; if (message.Contains("is gui? True")) messageFound = true; @@ -3919,10 +3919,10 @@ public void should_have_a_graphical_shim_that_is_set_for_gui_access() } [Fact] - public void should_contain_a_warning_message_that_it_installed_successfully() + public void Should_contain_a_warning_message_that_it_installed_successfully() { bool installedSuccessfully = false; - foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).or_empty_list_if_null()) + foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).OrEmpty()) { if (message.Contains("1/1")) installedSuccessfully = true; } @@ -3931,31 +3931,31 @@ public void should_contain_a_warning_message_that_it_installed_successfully() } [Fact] - public void should_have_a_successful_package_result() + public void Should_have_a_successful_package_result() { _packageResult.Success.ShouldBeTrue(); } [Fact] - public void should_not_have_inconclusive_package_result() + public void Should_not_have_inconclusive_package_result() { _packageResult.Inconclusive.ShouldBeFalse(); } [Fact] - public void should_not_have_warning_package_result() + public void Should_not_have_warning_package_result() { _packageResult.Warning.ShouldBeFalse(); } [Fact] - public void config_should_match_package_result_name() + public void Config_should_match_package_result_name() { _packageResult.Name.ShouldEqual(Configuration.PackageNames); } [Fact] - public void should_have_a_version_of_one_dot_zero_dot_zero() + public void Should_have_a_version_of_one_dot_zero_dot_zero() { _packageResult.Version.ShouldEqual("1.0.0"); } @@ -3963,54 +3963,54 @@ public void should_have_a_version_of_one_dot_zero_dot_zero() [Fact] [WindowsOnly] [Platform(Exclude = "Mono")] - public void should_not_have_executed_chocolateyInstall_script() + public void Should_not_have_executed_chocolateyInstall_script() { - MockLogger.contains_message("portablepackage v1.0.0 has been installed", LogLevel.Info).ShouldBeFalse(); + MockLogger.ContainsMessage("portablepackage v1.0.0 has been installed", LogLevel.Info).ShouldBeFalse(); } [Fact] [WindowsOnly] [Platform(Exclude = "Mono")] - public void should_have_executed_pre_all_hook_script() + public void Should_have_executed_pre_all_hook_script() { - MockLogger.contains_message("pre-install-all.ps1 hook ran for portablepackage 1.0.0", LogLevel.Info).ShouldBeTrue(); + MockLogger.ContainsMessage("pre-install-all.ps1 hook ran for portablepackage 1.0.0", LogLevel.Info).ShouldBeTrue(); } [Fact] [WindowsOnly] [Platform(Exclude = "Mono")] - public void should_have_executed_post_all_hook_script() + public void Should_have_executed_post_all_hook_script() { - MockLogger.contains_message("post-install-all.ps1 hook ran for portablepackage 1.0.0", LogLevel.Info).ShouldBeTrue(); + MockLogger.ContainsMessage("post-install-all.ps1 hook ran for portablepackage 1.0.0", LogLevel.Info).ShouldBeTrue(); } [Fact] [WindowsOnly] [Platform(Exclude = "Mono")] - public void should_not_have_executed_uninstall_hook_script() + public void Should_not_have_executed_uninstall_hook_script() { - MockLogger.contains_message("post-uninstall-all.ps1 hook ran for portablepackage 1.0.0", LogLevel.Info).ShouldBeFalse(); + MockLogger.ContainsMessage("post-uninstall-all.ps1 hook ran for portablepackage 1.0.0", LogLevel.Info).ShouldBeFalse(); } [Fact] [WindowsOnly] [Platform(Exclude = "Mono")] - public void should_not_have_executed_upgradepackage_hook_script() + public void Should_not_have_executed_upgradepackage_hook_script() { - MockLogger.contains_message("pre-install-upgradepackage.ps1 hook ran for portablepackage 1.0.0", LogLevel.Info).ShouldBeFalse(); + MockLogger.ContainsMessage("pre-install-upgradepackage.ps1 hook ran for portablepackage 1.0.0", LogLevel.Info).ShouldBeFalse(); } [Fact] [WindowsOnly] [Platform(Exclude = "Mono")] - public void should_not_have_executed_beforemodify_hook_script() + public void Should_not_have_executed_beforemodify_hook_script() { - MockLogger.contains_message("pre-beforemodify-all.ps1 hook ran for portablepackage 1.0.0", LogLevel.Info).ShouldBeFalse(); + MockLogger.ContainsMessage("pre-beforemodify-all.ps1 hook ran for portablepackage 1.0.0", LogLevel.Info).ShouldBeFalse(); } } [Categories.SourcePriority] - public class when_installing_package_from_lower_priority_source_with_version_specified : ScenariosBase + public class When_installing_package_from_lower_priority_source_with_version_specified : ScenariosBase { private PackageResult packageResult; public override void Context() @@ -4025,19 +4025,19 @@ public override void Context() public override void Because() { - MockLogger.reset(); - Results = Service.install_run(Configuration); + MockLogger.Reset(); + Results = Service.Install(Configuration); packageResult = Results.Select(r => r.Value).FirstOrDefault(); } [Fact] - public void should_install_where_install_location_reports() + public void Should_install_where_install_location_reports() { DirectoryAssert.Exists(packageResult.InstallLocation); } [Fact] - public void should_install_the_package_in_the_lib_directory() + public void Should_install_the_package_in_the_lib_directory() { var packageDir = Path.Combine(Scenario.get_top_level(), "lib", Configuration.PackageNames); @@ -4045,7 +4045,7 @@ public void should_install_the_package_in_the_lib_directory() } [Fact] - public void should_install_the_expected_version_of_the_package() + public void Should_install_the_expected_version_of_the_package() { var packageDirectory = Path.Combine(Scenario.get_top_level(), "lib", Configuration.PackageNames); @@ -4056,7 +4056,7 @@ public void should_install_the_expected_version_of_the_package() } [Fact] - public void should_not_create_an_extensions_folder_for_the_package() + public void Should_not_create_an_extensions_folder_for_the_package() { var extensionsDirectory = Path.Combine(Scenario.get_top_level(), "extensions", Configuration.PackageNames); @@ -4064,7 +4064,7 @@ public void should_not_create_an_extensions_folder_for_the_package() } [Fact] - public void should_not_create_an_hooks_folder_for_the_package() + public void Should_not_create_an_hooks_folder_for_the_package() { var hooksDirectory = Path.Combine(Scenario.get_top_level(), "hooks", Configuration.PackageNames); @@ -4072,10 +4072,10 @@ public void should_not_create_an_hooks_folder_for_the_package() } [Fact] - public void should_contain_a_warning_message_that_it_installed_successfully() + public void Should_contain_a_warning_message_that_it_installed_successfully() { bool installedSuccessfully = false; - foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).or_empty_list_if_null()) + foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).OrEmpty()) { if (message.Contains("1/1")) installedSuccessfully = true; } @@ -4084,31 +4084,31 @@ public void should_contain_a_warning_message_that_it_installed_successfully() } [Fact] - public void should_have_a_successful_package_result() + public void Should_have_a_successful_package_result() { packageResult.Success.ShouldBeTrue(); } [Fact] - public void should_not_have_inconclusive_package_result() + public void Should_not_have_inconclusive_package_result() { packageResult.Inconclusive.ShouldBeFalse(); } [Fact] - public void should_not_have_warning_package_result() + public void Should_not_have_warning_package_result() { packageResult.Warning.ShouldBeFalse(); } [Fact] - public void config_should_match_package_result_name() + public void Config_should_match_package_result_name() { packageResult.Name.ShouldEqual(Configuration.PackageNames); } [Fact] - public void should_have_a_version_of_two_dot_zero_dot_zero() + public void Should_have_a_version_of_two_dot_zero_dot_zero() { packageResult.Version.ShouldEqual("2.0.0"); } @@ -4116,14 +4116,14 @@ public void should_have_a_version_of_two_dot_zero_dot_zero() [Fact] [WindowsOnly] [Platform(Exclude = "Mono")] - public void should_have_reported_package_installed() + public void Should_have_reported_package_installed() { - MockLogger.contains_message("isdependency 2.0.0 Installed", LogLevel.Info).ShouldBeTrue(); + MockLogger.ContainsMessage("isdependency 2.0.0 Installed", LogLevel.Info).ShouldBeTrue(); } } [Categories.SourcePriority] - public class when_installing_non_existing_package_from_priority_source : ScenariosBase + public class When_installing_non_existing_package_from_priority_source : ScenariosBase { public override void Context() { @@ -4135,12 +4135,12 @@ public override void Context() public override void Because() { - MockLogger.reset(); - Results = Service.install_run(Configuration); + MockLogger.Reset(); + Results = Service.Install(Configuration); } [Fact] - public void should_not_report_success() + public void Should_not_report_success() { foreach (var packageResult in Results) { @@ -4149,7 +4149,7 @@ public void should_not_report_success() } [Fact] - public void should_not_install_a_package_in_the_lib_directory() + public void Should_not_install_a_package_in_the_lib_directory() { var packageDir = Path.Combine(Scenario.get_top_level(), "lib", Configuration.PackageNames); @@ -4157,7 +4157,7 @@ public void should_not_install_a_package_in_the_lib_directory() } [Fact] - public void should_not_have_inconclusive_package_result() + public void Should_not_have_inconclusive_package_result() { foreach (var packageResult in Results) { @@ -4166,7 +4166,7 @@ public void should_not_have_inconclusive_package_result() } [Fact] - public void should_not_have_warning_package_results() + public void Should_not_have_warning_package_results() { foreach (var packageResult in Results) { @@ -4175,7 +4175,7 @@ public void should_not_have_warning_package_results() } [Fact] - public void should_report_package_not_found() + public void Should_report_package_not_found() { foreach (var packageResult in Results) { @@ -4187,7 +4187,7 @@ public void should_report_package_not_found() } [Categories.SourcePriority] - public class when_installing_new_package_from_priority_source_with_repository_optimization : ScenariosBase + public class When_installing_new_package_from_priority_source_with_repository_optimization : ScenariosBase { public override void Context() { @@ -4205,12 +4205,12 @@ public override void Context() public override void Because() { - MockLogger.reset(); - Results = Service.install_run(Configuration); + MockLogger.Reset(); + Results = Service.Install(Configuration); } [Fact] - public void should_install_where_install_location_reports() + public void Should_install_where_install_location_reports() { foreach (var packageResult in Results) { @@ -4219,7 +4219,7 @@ public void should_install_where_install_location_reports() } [Fact] - public void should_install_a_package_in_the_lib_directory() + public void Should_install_a_package_in_the_lib_directory() { var packageDir = Path.Combine(Scenario.get_top_level(), "lib", Configuration.PackageNames); @@ -4227,7 +4227,7 @@ public void should_install_a_package_in_the_lib_directory() } [Fact] - public void should_install_lower_version_of_package() + public void Should_install_lower_version_of_package() { foreach (var packageResult in Results) { @@ -4236,7 +4236,7 @@ public void should_install_lower_version_of_package() } [Fact] - public void should_have_installed_expected_version_in_lib_directory() + public void Should_have_installed_expected_version_in_lib_directory() { var installedPath = Path.Combine(Scenario.get_top_level(), "lib", Configuration.PackageNames); @@ -4249,7 +4249,7 @@ public void should_have_installed_expected_version_in_lib_directory() } [Fact] - public void should_not_have_inconclusive_package_results() + public void Should_not_have_inconclusive_package_results() { foreach (var packageResult in Results) { @@ -4258,7 +4258,7 @@ public void should_not_have_inconclusive_package_results() } [Fact] - public void should_not_have_warning_package_results() + public void Should_not_have_warning_package_results() { foreach (var packageResult in Results) { @@ -4267,7 +4267,7 @@ public void should_not_have_warning_package_results() } [Fact] - public void should_have_success_package_results() + public void Should_have_success_package_results() { foreach (var packageResult in Results) { @@ -4277,7 +4277,7 @@ public void should_have_success_package_results() } [Categories.SourcePriority] - public class when_installing_new_package_from_priority_source : ScenariosBase + public class When_installing_new_package_from_priority_source : ScenariosBase { public override void Context() { @@ -4293,12 +4293,12 @@ public override void Context() public override void Because() { - MockLogger.reset(); - Results = Service.install_run(Configuration); + MockLogger.Reset(); + Results = Service.Install(Configuration); } [Fact] - public void should_install_where_install_location_reports() + public void Should_install_where_install_location_reports() { foreach (var packageResult in Results) { @@ -4307,14 +4307,14 @@ public void should_install_where_install_location_reports() } [Fact] - public void should_install_a_package_in_the_lib_directory() + public void Should_install_a_package_in_the_lib_directory() { var packageDir = Path.Combine(Scenario.get_top_level(), "lib", Configuration.PackageNames); DirectoryAssert.Exists(packageDir); } [Fact] - public void should_have_installed_expected_version_in_lib_directory() + public void Should_have_installed_expected_version_in_lib_directory() { var packageFolder = Path.Combine(Scenario.get_top_level(), "lib", Configuration.PackageNames, Configuration.PackageNames + NuGetConstants.PackageExtension); @@ -4325,7 +4325,7 @@ public void should_have_installed_expected_version_in_lib_directory() } [Fact] - public void should_install_lower_version_of_package() + public void Should_install_lower_version_of_package() { foreach (var packageResult in Results) { @@ -4334,7 +4334,7 @@ public void should_install_lower_version_of_package() } [Fact] - public void should_not_have_inconclusive_package_results() + public void Should_not_have_inconclusive_package_results() { foreach (var packageResult in Results) { @@ -4343,7 +4343,7 @@ public void should_not_have_inconclusive_package_results() } [Fact] - public void should_not_have_warning_package_results() + public void Should_not_have_warning_package_results() { foreach (var packageResult in Results) { @@ -4352,7 +4352,7 @@ public void should_not_have_warning_package_results() } [Fact] - public void should_have_success_package_results() + public void Should_have_success_package_results() { foreach (var packageResult in Results) { @@ -4362,7 +4362,7 @@ public void should_have_success_package_results() } [Categories.SourcePriority] - public class when_installing_package_with_dependencies_on_different_priority_sources : ScenariosBase + public class When_installing_package_with_dependencies_on_different_priority_sources : ScenariosBase { public static IEnumerable ExpectedInstallations { @@ -4400,12 +4400,12 @@ public override void Context() public override void Because() { - MockLogger.reset(); - Results = Service.install_run(Configuration); + MockLogger.Reset(); + Results = Service.Install(Configuration); } [Fact] - public void should_install_where_install_location_reports() + public void Should_install_where_install_location_reports() { foreach (var packageResult in Results) { @@ -4414,14 +4414,14 @@ public void should_install_where_install_location_reports() } [TestCaseSource(nameof(ExpectedInstallations))] - public void should_install_hasdependency_package_to_lib_directory(string name) + public void Should_install_hasdependency_package_to_lib_directory(string name) { var expectedPath = Path.Combine(Scenario.get_top_level(), "lib", name); DirectoryAssert.Exists(expectedPath); } [TestCaseSource(nameof(ExpectedPackageVersions))] - public void should_instal_expected_package_version(string name, string version) + public void Should_instal_expected_package_version(string name, string version) { var path = Path.Combine(Scenario.get_top_level(), "lib", name); @@ -4432,14 +4432,14 @@ public void should_instal_expected_package_version(string name, string version) } [TestCaseSource(nameof(ExpectedPackageVersions))] - public void should_report_installed_version_of_package(string name, string version) + public void Should_report_installed_version_of_package(string name, string version) { var package = Results.First(r => r.Key == name); package.Value.Version.ShouldEqual(version); } [Fact] - public void should_not_have_inconclusive_package_results() + public void Should_not_have_inconclusive_package_results() { foreach (var packageResult in Results) { @@ -4448,7 +4448,7 @@ public void should_not_have_inconclusive_package_results() } [Fact] - public void should_not_have_warning_package_results() + public void Should_not_have_warning_package_results() { foreach (var packageResult in Results) { @@ -4457,7 +4457,7 @@ public void should_not_have_warning_package_results() } [Fact] - public void should_have_success_package_results() + public void Should_have_success_package_results() { foreach (var packageResult in Results) { @@ -4466,7 +4466,7 @@ public void should_have_success_package_results() } } - public class when_installing_a_package_with_an_uppercase_id : ScenariosBase + public class When_installing_a_package_with_an_uppercase_id : ScenariosBase { private PackageResult _packageResult; @@ -4479,18 +4479,18 @@ public override void Context() public override void Because() { - Results = Service.install_run(Configuration); + Results = Service.Install(Configuration); _packageResult = Results.FirstOrDefault().Value; } [Fact] - public void should_install_where_install_location_reports() + public void Should_install_where_install_location_reports() { DirectoryAssert.Exists(_packageResult.InstallLocation); } [Fact] - public void should_install_the_package_in_the_lib_directory() + public void Should_install_the_package_in_the_lib_directory() { var packageDir = Path.Combine(Scenario.get_top_level(), "lib", Configuration.PackageNames); @@ -4498,24 +4498,24 @@ public void should_install_the_package_in_the_lib_directory() } [Fact] - public void should_have_the_correct_casing_for_the_nuspec() + public void Should_have_the_correct_casing_for_the_nuspec() { var nuspecFile = Path.Combine(Scenario.get_top_level(), "lib", Configuration.PackageNames, Configuration.PackageNames + NuGetConstants.ManifestExtension); FileAssert.Exists(nuspecFile); } [Fact] - public void should_install_the_expected_version_of_the_package() + public void Should_install_the_expected_version_of_the_package() { var packageFile = Path.Combine(Scenario.get_top_level(), "lib", Configuration.PackageNames, Configuration.PackageNames + NuGetConstants.PackageExtension); using (var packageReader = new PackageArchiveReader(packageFile)) { - packageReader.NuspecReader.GetVersion().to_string().ShouldEqual("1.0.0"); + packageReader.NuspecReader.GetVersion().ToStringSafe().ShouldEqual("1.0.0"); } } [Fact] - public void should_not_create_an_extensions_folder_for_the_package() + public void Should_not_create_an_extensions_folder_for_the_package() { var extensionsDirectory = Path.Combine(Scenario.get_top_level(), "extensions", Configuration.PackageNames); @@ -4523,7 +4523,7 @@ public void should_not_create_an_extensions_folder_for_the_package() } [Fact] - public void should_not_create_an_hooks_folder_for_the_package() + public void Should_not_create_an_hooks_folder_for_the_package() { var hooksDirectory = Path.Combine(Scenario.get_top_level(), "hooks", Configuration.PackageNames); @@ -4531,10 +4531,10 @@ public void should_not_create_an_hooks_folder_for_the_package() } [Fact] - public void should_contain_a_warning_message_that_it_installed_successfully() + public void Should_contain_a_warning_message_that_it_installed_successfully() { bool installedSuccessfully = false; - foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).or_empty_list_if_null()) + foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).OrEmpty()) { if (message.Contains("1/1")) installedSuccessfully = true; } @@ -4543,31 +4543,31 @@ public void should_contain_a_warning_message_that_it_installed_successfully() } [Fact] - public void should_have_a_successful_package_result() + public void Should_have_a_successful_package_result() { _packageResult.Success.ShouldBeTrue(); } [Fact] - public void should_not_have_inconclusive_package_result() + public void Should_not_have_inconclusive_package_result() { _packageResult.Inconclusive.ShouldBeFalse(); } [Fact] - public void should_not_have_warning_package_result() + public void Should_not_have_warning_package_result() { _packageResult.Warning.ShouldBeFalse(); } [Fact] - public void config_should_match_package_result_name() + public void Config_should_match_package_result_name() { _packageResult.Name.ShouldEqual(Configuration.PackageNames); } [Fact] - public void should_have_a_version_of_one_dot_zero_dot_zero() + public void Should_have_a_version_of_one_dot_zero_dot_zero() { _packageResult.Version.ShouldEqual("1.0.0"); } @@ -4575,13 +4575,13 @@ public void should_have_a_version_of_one_dot_zero_dot_zero() [Fact] [WindowsOnly] [Platform(Exclude = "Mono")] - public void should_have_executed_chocolateyInstall_script() + public void Should_have_executed_chocolateyInstall_script() { - MockLogger.contains_message("UpperCase 1.0.0 Installed", LogLevel.Info).ShouldBeTrue(); + MockLogger.ContainsMessage("UpperCase 1.0.0 Installed", LogLevel.Info).ShouldBeTrue(); } } - public class when_installing_a_package_with_unsupported_metadata_elements : ScenariosBase + public class When_installing_a_package_with_unsupported_metadata_elements : ScenariosBase { private PackageResult _packageResult; @@ -4594,18 +4594,18 @@ public override void Context() public override void Because() { - Results = Service.install_run(Configuration); + Results = Service.Install(Configuration); _packageResult = Results.FirstOrDefault().Value; } [Fact] - public void should_install_where_install_location_reports() + public void Should_install_where_install_location_reports() { DirectoryAssert.Exists(_packageResult.InstallLocation); } [Fact] - public void should_install_the_package_in_the_lib_directory() + public void Should_install_the_package_in_the_lib_directory() { var packageDir = Path.Combine(Scenario.get_top_level(), "lib", Configuration.PackageNames); @@ -4613,17 +4613,17 @@ public void should_install_the_package_in_the_lib_directory() } [Fact] - public void should_install_the_expected_version_of_the_package() + public void Should_install_the_expected_version_of_the_package() { var packageFile = Path.Combine(Scenario.get_top_level(), "lib", Configuration.PackageNames, Configuration.PackageNames + NuGetConstants.PackageExtension); using (var packageReader = new PackageArchiveReader(packageFile)) { - packageReader.NuspecReader.GetVersion().to_string().ShouldEqual("1.0.0"); + packageReader.NuspecReader.GetVersion().ToStringSafe().ShouldEqual("1.0.0"); } } [Fact] - public void should_not_create_an_extensions_folder_for_the_package() + public void Should_not_create_an_extensions_folder_for_the_package() { var extensionsDirectory = Path.Combine(Scenario.get_top_level(), "extensions", Configuration.PackageNames); @@ -4631,7 +4631,7 @@ public void should_not_create_an_extensions_folder_for_the_package() } [Fact] - public void should_not_create_an_hooks_folder_for_the_package() + public void Should_not_create_an_hooks_folder_for_the_package() { var hooksDirectory = Path.Combine(Scenario.get_top_level(), "hooks", Configuration.PackageNames); @@ -4639,10 +4639,10 @@ public void should_not_create_an_hooks_folder_for_the_package() } [Fact] - public void should_contain_a_warning_message_that_it_installed_successfully() + public void Should_contain_a_warning_message_that_it_installed_successfully() { bool installedSuccessfully = false; - foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).or_empty_list_if_null()) + foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).OrEmpty()) { if (message.Contains("1/1")) installedSuccessfully = true; } @@ -4651,10 +4651,10 @@ public void should_contain_a_warning_message_that_it_installed_successfully() } [Fact] - public void should_contain_a_warning_message_about_unsupported_elements() + public void Should_contain_a_warning_message_about_unsupported_elements() { bool upgradeMessage = false; - foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).or_empty_list_if_null()) + foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).OrEmpty()) { if (message.Contains("Issues found with nuspec elements")) upgradeMessage = true; } @@ -4662,31 +4662,31 @@ public void should_contain_a_warning_message_about_unsupported_elements() } [Fact] - public void should_have_a_successful_package_result() + public void Should_have_a_successful_package_result() { _packageResult.Success.ShouldBeTrue(); } [Fact] - public void should_not_have_inconclusive_package_result() + public void Should_not_have_inconclusive_package_result() { _packageResult.Inconclusive.ShouldBeFalse(); } [Fact] - public void should_have_warning_package_result() + public void Should_have_warning_package_result() { _packageResult.Warning.ShouldBeTrue(); } [Fact] - public void config_should_match_package_result_name() + public void Config_should_match_package_result_name() { _packageResult.Name.ShouldEqual(Configuration.PackageNames); } [Fact] - public void should_have_a_version_of_one_dot_zero_dot_zero() + public void Should_have_a_version_of_one_dot_zero_dot_zero() { _packageResult.Version.ShouldEqual("1.0.0"); } @@ -4694,13 +4694,13 @@ public void should_have_a_version_of_one_dot_zero_dot_zero() [Fact] [WindowsOnly] [Platform(Exclude = "Mono")] - public void should_have_executed_chocolateyInstall_script() + public void Should_have_executed_chocolateyInstall_script() { - MockLogger.contains_message("unsupportedelements 1.0.0 Installed", LogLevel.Info).ShouldBeTrue(); + MockLogger.ContainsMessage("unsupportedelements 1.0.0 Installed", LogLevel.Info).ShouldBeTrue(); } } - public class when_installing_a_package_with_non_normalized_version : ScenariosBase + public class When_installing_a_package_with_non_normalized_version : ScenariosBase { private PackageResult _packageResult; @@ -4716,18 +4716,18 @@ public override void Context() public override void Because() { - Results = Service.install_run(Configuration); + Results = Service.Install(Configuration); _packageResult = Results.FirstOrDefault().Value; } [Fact] - public void should_install_where_install_location_reports() + public void Should_install_where_install_location_reports() { DirectoryAssert.Exists(_packageResult.InstallLocation); } [Fact] - public void should_install_the_package_in_the_lib_directory() + public void Should_install_the_package_in_the_lib_directory() { var packageDir = Path.Combine(Scenario.get_top_level(), "lib", Configuration.PackageNames); @@ -4735,17 +4735,17 @@ public void should_install_the_package_in_the_lib_directory() } [Fact] - public void should_install_the_expected_version_of_the_package() + public void Should_install_the_expected_version_of_the_package() { var packageFile = Path.Combine(Scenario.get_top_level(), "lib", Configuration.PackageNames, Configuration.PackageNames + NuGetConstants.PackageExtension); using (var packageReader = new PackageArchiveReader(packageFile)) { - packageReader.NuspecReader.GetVersion().to_string().ShouldEqual(NonNormalizedVersion); + packageReader.NuspecReader.GetVersion().ToStringSafe().ShouldEqual(NonNormalizedVersion); } } [Fact] - public void should_not_create_an_extensions_folder_for_the_package() + public void Should_not_create_an_extensions_folder_for_the_package() { var extensionsDirectory = Path.Combine(Scenario.get_top_level(), "extensions", Configuration.PackageNames); @@ -4753,7 +4753,7 @@ public void should_not_create_an_extensions_folder_for_the_package() } [Fact] - public void should_not_create_an_hooks_folder_for_the_package() + public void Should_not_create_an_hooks_folder_for_the_package() { var hooksDirectory = Path.Combine(Scenario.get_top_level(), "hooks", Configuration.PackageNames); @@ -4761,10 +4761,10 @@ public void should_not_create_an_hooks_folder_for_the_package() } [Fact] - public void should_contain_a_warning_message_that_it_installed_successfully() + public void Should_contain_a_warning_message_that_it_installed_successfully() { bool installedSuccessfully = false; - foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).or_empty_list_if_null()) + foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).OrEmpty()) { if (message.Contains("1/1")) installedSuccessfully = true; } @@ -4773,31 +4773,31 @@ public void should_contain_a_warning_message_that_it_installed_successfully() } [Fact] - public void should_have_a_successful_package_result() + public void Should_have_a_successful_package_result() { _packageResult.Success.ShouldBeTrue(); } [Fact] - public void should_not_have_inconclusive_package_result() + public void Should_not_have_inconclusive_package_result() { _packageResult.Inconclusive.ShouldBeFalse(); } [Fact] - public void should_not_have_warning_package_result() + public void Should_not_have_warning_package_result() { _packageResult.Warning.ShouldBeFalse(); } [Fact] - public void config_should_match_package_result_name() + public void Config_should_match_package_result_name() { _packageResult.Name.ShouldEqual(Configuration.PackageNames); } [Fact] - public void result_should_have_the_correct_version() + public void Result_should_have_the_correct_version() { _packageResult.Version.ShouldEqual(NonNormalizedVersion); } @@ -4805,17 +4805,17 @@ public void result_should_have_the_correct_version() [Fact] [WindowsOnly] [Platform(Exclude = "Mono")] - public void should_have_executed_chocolateyInstall_script() + public void Should_have_executed_chocolateyInstall_script() { - var message = "installpackage v{0} has been installed".format_with(NonNormalizedVersion); + var message = "installpackage v{0} has been installed".FormatWith(NonNormalizedVersion); - MockLogger.contains_message(message, LogLevel.Info).ShouldBeTrue(); + MockLogger.ContainsMessage(message, LogLevel.Info).ShouldBeTrue(); } [Fact] [WindowsOnly] [Platform(Exclude = "Mono")] - public void should_create_a_shim_for_console_in_the_bin_directory() + public void Should_create_a_shim_for_console_in_the_bin_directory() { var shimfile = Path.Combine(Scenario.get_top_level(), "bin", "console.exe"); @@ -4825,7 +4825,7 @@ public void should_create_a_shim_for_console_in_the_bin_directory() [Fact] [WindowsOnly] [Platform(Exclude = "Mono")] - public void should_create_a_shim_for_graphical_in_the_bin_directory() + public void Should_create_a_shim_for_graphical_in_the_bin_directory() { var shimfile = Path.Combine(Scenario.get_top_level(), "bin", "graphical.exe"); @@ -4833,7 +4833,7 @@ public void should_create_a_shim_for_graphical_in_the_bin_directory() } [Fact] - public void should_not_create_a_shim_for_ignored_executable_in_the_bin_directory() + public void Should_not_create_a_shim_for_ignored_executable_in_the_bin_directory() { var shimfile = Path.Combine(Scenario.get_top_level(), "bin", "not.installed.exe"); @@ -4841,7 +4841,7 @@ public void should_not_create_a_shim_for_ignored_executable_in_the_bin_directory } [Fact] - public void should_not_create_a_shim_for_mismatched_case_ignored_executable_in_the_bin_directory() + public void Should_not_create_a_shim_for_mismatched_case_ignored_executable_in_the_bin_directory() { var shimfile = Path.Combine(Scenario.get_top_level(), "bin", "casemismatch.exe"); @@ -4851,12 +4851,12 @@ public void should_not_create_a_shim_for_mismatched_case_ignored_executable_in_t [Fact] [WindowsOnly] [Platform(Exclude = "Mono")] - public void should_have_a_console_shim_that_is_set_for_non_gui_access() + public void Should_have_a_console_shim_that_is_set_for_non_gui_access() { var messages = new List(); var shimfile = Path.Combine(Scenario.get_top_level(), "bin", "console.exe"); - CommandExecutor.execute( + CommandExecutor.Execute( shimfile, "--shimgen-noop", 10, @@ -4866,7 +4866,7 @@ public void should_have_a_console_shim_that_is_set_for_non_gui_access() var messageFound = false; - foreach (var message in messages.or_empty_list_if_null()) + foreach (var message in messages.OrEmpty()) { if (string.IsNullOrWhiteSpace(message)) continue; if (message.Contains("is gui? False")) messageFound = true; @@ -4878,12 +4878,12 @@ public void should_have_a_console_shim_that_is_set_for_non_gui_access() [Fact] [WindowsOnly] [Platform(Exclude = "Mono")] - public void should_have_a_graphical_shim_that_is_set_for_gui_access() + public void Should_have_a_graphical_shim_that_is_set_for_gui_access() { var messages = new List(); var shimfile = Path.Combine(Scenario.get_top_level(), "bin", "graphical.exe"); - CommandExecutor.execute( + CommandExecutor.Execute( shimfile, "--shimgen-noop", 10, @@ -4893,7 +4893,7 @@ public void should_have_a_graphical_shim_that_is_set_for_gui_access() var messageFound = false; - foreach (var message in messages.or_empty_list_if_null()) + foreach (var message in messages.OrEmpty()) { if (string.IsNullOrWhiteSpace(message)) continue; if (message.Contains("is gui? True")) messageFound = true; @@ -4903,7 +4903,7 @@ public void should_have_a_graphical_shim_that_is_set_for_gui_access() } } - public class when_installing_a_package_specifying_normalized_version : when_installing_a_package_with_non_normalized_version + public class When_installing_a_package_specifying_normalized_version : When_installing_a_package_with_non_normalized_version { protected override string NormalizedVersion => "2.2.0"; protected override string NonNormalizedVersion => "2.02.0.0"; @@ -4915,7 +4915,7 @@ public override void Context() } } - public class when_installing_a_package_specifying_non_normalized_version : when_installing_a_package_with_non_normalized_version + public class When_installing_a_package_specifying_non_normalized_version : When_installing_a_package_with_non_normalized_version { protected override string NormalizedVersion => "2.2.0"; protected override string NonNormalizedVersion => "2.02.0.0"; @@ -4927,13 +4927,13 @@ public override void Context() } } - public class when_installing_a_package_with_multiple_leading_zeros : when_installing_a_package_with_non_normalized_version + public class When_installing_a_package_with_multiple_leading_zeros : When_installing_a_package_with_non_normalized_version { protected override string NormalizedVersion => "4.4.5.1"; protected override string NonNormalizedVersion => "0004.0004.00005.01"; } - public class when_installing_a_package_with_multiple_leading_zeros_specifying_normalized_version : when_installing_a_package_with_non_normalized_version + public class When_installing_a_package_with_multiple_leading_zeros_specifying_normalized_version : When_installing_a_package_with_non_normalized_version { protected override string NormalizedVersion => "4.4.5.1" ; protected override string NonNormalizedVersion => "0004.0004.00005.01"; @@ -4945,7 +4945,7 @@ public override void Context() } } - public class when_installing_a_package_with_multiple_leading_zeros_specifying_non_normalized_version : when_installing_a_package_with_non_normalized_version + public class When_installing_a_package_with_multiple_leading_zeros_specifying_non_normalized_version : When_installing_a_package_with_non_normalized_version { protected override string NormalizedVersion => "4.4.5.1"; protected override string NonNormalizedVersion => "0004.0004.00005.01"; @@ -4956,8 +4956,8 @@ public override void Context() Configuration.Version = NonNormalizedVersion; } } - - public class when_installing_a_package_that_requires_updating_a_dependency : ScenariosBase + + public class When_installing_a_package_that_requires_updating_a_dependency : ScenariosBase { private const string TargetPackageName = "hasdependencywithbeforemodify"; private const string DependencyName = "isdependencywithbeforemodify"; @@ -4966,8 +4966,8 @@ public override void Context() { base.Context(); - Scenario.add_packages_to_source_location(Configuration, "{0}.*".format_with(TargetPackageName) + NuGetConstants.PackageExtension); - Scenario.add_packages_to_source_location(Configuration, "{0}.*".format_with(DependencyName) + NuGetConstants.PackageExtension); + Scenario.add_packages_to_source_location(Configuration, "{0}.*".FormatWith(TargetPackageName) + NuGetConstants.PackageExtension); + Scenario.add_packages_to_source_location(Configuration, "{0}.*".FormatWith(DependencyName) + NuGetConstants.PackageExtension); Scenario.install_package(Configuration, DependencyName, "1.0.0"); Configuration.PackageNames = Configuration.Input = TargetPackageName; @@ -4975,61 +4975,61 @@ public override void Context() public override void Because() { - Results = Service.install_run(Configuration); + Results = Service.Install(Configuration); } [Fact] - public void should_install_the_package() + public void Should_install_the_package() { - var packageFile = Path.Combine(Scenario.get_top_level(), "lib", TargetPackageName, "{0}.nupkg".format_with(TargetPackageName)); + var packageFile = Path.Combine(Scenario.get_top_level(), "lib", TargetPackageName, "{0}.nupkg".FormatWith(TargetPackageName)); using (var packageReader = new PackageArchiveReader(packageFile)) { - packageReader.NuspecReader.GetVersion().to_string().ShouldEqual("2.0.0"); + packageReader.NuspecReader.GetVersion().ToStringSafe().ShouldEqual("2.0.0"); } } [Fact] - public void should_upgrade_the_minimum_version_dependency() + public void Should_upgrade_the_minimum_version_dependency() { - var packageFile = Path.Combine(Scenario.get_top_level(), "lib", DependencyName, "{0}.nupkg".format_with(DependencyName)); + var packageFile = Path.Combine(Scenario.get_top_level(), "lib", DependencyName, "{0}.nupkg".FormatWith(DependencyName)); using (var packageReader = new PackageArchiveReader(packageFile)) { - packageReader.NuspecReader.GetVersion().to_string().ShouldEqual("2.0.0"); + packageReader.NuspecReader.GetVersion().ToStringSafe().ShouldEqual("2.0.0"); } } [Fact] - public void should_contain_a_message_that_everything_installed_successfully() + public void Should_contain_a_message_that_everything_installed_successfully() { - MockLogger.contains_message("installed 2/2", LogLevel.Warn).ShouldBeTrue(); + MockLogger.ContainsMessage("installed 2/2", LogLevel.Warn).ShouldBeTrue(); } - + [Fact] [WindowsOnly] [Platform(Exclude = "Mono")] - public void should_not_run_target_package_beforeModify_for_upgraded_version() + public void Should_not_run_target_package_beforeModify_for_upgraded_version() { - MockLogger.contains_message("Ran BeforeModify: {0} {1}".format_with(TargetPackageName, "2.0.0"), LogLevel.Info).ShouldBeFalse(); + MockLogger.ContainsMessage("Ran BeforeModify: {0} {1}".FormatWith(TargetPackageName, "2.0.0"), LogLevel.Info).ShouldBeFalse(); } [Fact] [WindowsOnly] [Platform(Exclude = "Mono")] - public void should_run_already_installed_dependency_package_beforeModify() + public void Should_run_already_installed_dependency_package_beforeModify() { - MockLogger.contains_message("Ran BeforeModify: {0} {1}".format_with(DependencyName, "1.0.0"), LogLevel.Info).ShouldBeTrue(); + MockLogger.ContainsMessage("Ran BeforeModify: {0} {1}".FormatWith(DependencyName, "1.0.0"), LogLevel.Info).ShouldBeTrue(); } [Fact] [WindowsOnly] [Platform(Exclude = "Mono")] - public void should_not_run_dependency_package_beforeModify_for_upgraded_version() + public void Should_not_run_dependency_package_beforeModify_for_upgraded_version() { - MockLogger.contains_message("Ran BeforeModify: {0} {1}".format_with(DependencyName, "2.0.0"), LogLevel.Info).ShouldBeFalse(); + MockLogger.ContainsMessage("Ran BeforeModify: {0} {1}".FormatWith(DependencyName, "2.0.0"), LogLevel.Info).ShouldBeFalse(); } [Fact] - public void should_have_a_successful_package_result() + public void Should_have_a_successful_package_result() { foreach (var packageResult in Results) { @@ -5038,7 +5038,7 @@ public void should_have_a_successful_package_result() } [Fact] - public void should_not_have_inconclusive_package_result() + public void Should_not_have_inconclusive_package_result() { foreach (var packageResult in Results) { @@ -5047,7 +5047,7 @@ public void should_not_have_inconclusive_package_result() } [Fact] - public void should_not_have_warning_package_result() + public void Should_not_have_warning_package_result() { foreach (var packageResult in Results) { diff --git a/src/chocolatey.tests.integration/scenarios/ListScenarios.cs b/src/chocolatey.tests.integration/scenarios/ListScenarios.cs index 61a5848bfd..fdb6c4c284 100644 --- a/src/chocolatey.tests.integration/scenarios/ListScenarios.cs +++ b/src/chocolatey.tests.integration/scenarios/ListScenarios.cs @@ -1,4 +1,4 @@ -// Copyright © 2023-Present Chocolatey Software, Inc +// Copyright © 2023-Present Chocolatey Software, Inc // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -46,7 +46,7 @@ public override void Context() } } - public class when_listing_local_packages : ScenariosBase + public class When_listing_local_packages : ScenariosBase { public override void Context() { @@ -55,39 +55,39 @@ public override void Context() public override void Because() { - MockLogger.reset(); - Results = Service.list_run(Configuration).ToList(); + MockLogger.Reset(); + Results = Service.List(Configuration).ToList(); } [Fact] - public void should_contain_packages_and_versions_with_a_space_between_them() + public void Should_contain_packages_and_versions_with_a_space_between_them() { - MockLogger.contains_message("upgradepackage 1.0.0").ShouldBeTrue(userMessage: "Warnings: " + string.Join("\n", MockLogger.Messages["Info"])); + MockLogger.ContainsMessage("upgradepackage 1.0.0").ShouldBeTrue(userMessage: "Warnings: " + string.Join("\n", MockLogger.Messages["Info"])); } [Fact] - public void should_not_contain_packages_and_versions_with_a_pipe_between_them() + public void Should_not_contain_packages_and_versions_with_a_pipe_between_them() { - MockLogger.contains_message("upgradepackage|1.0.0").ShouldBeFalse(); + MockLogger.ContainsMessage("upgradepackage|1.0.0").ShouldBeFalse(); } [Fact] - public void should_contain_a_summary() + public void Should_contain_a_summary() { - MockLogger.contains_message("packages installed").ShouldBeTrue(); + MockLogger.ContainsMessage("packages installed").ShouldBeTrue(); } [Fact] - public void should_contain_debugging_messages() + public void Should_contain_debugging_messages() { - MockLogger.contains_message("Searching for package information", LogLevel.Debug).ShouldBeTrue(); - MockLogger.contains_message("Running list with the following filter", LogLevel.Debug).ShouldBeTrue(); - MockLogger.contains_message("Start of List", LogLevel.Debug).ShouldBeTrue(); - MockLogger.contains_message("End of List", LogLevel.Debug).ShouldBeTrue(); + MockLogger.ContainsMessage("Searching for package information", LogLevel.Debug).ShouldBeTrue(); + MockLogger.ContainsMessage("Running list with the following filter", LogLevel.Debug).ShouldBeTrue(); + MockLogger.ContainsMessage("Start of List", LogLevel.Debug).ShouldBeTrue(); + MockLogger.ContainsMessage("End of List", LogLevel.Debug).ShouldBeTrue(); } } - public class when_listing_local_packages_with_id_only : ScenariosBase + public class When_listing_local_packages_with_id_only : ScenariosBase { public override void Context() { @@ -97,24 +97,24 @@ public override void Context() public override void Because() { - MockLogger.reset(); - Results = Service.list_run(Configuration).ToList(); + MockLogger.Reset(); + Results = Service.List(Configuration).ToList(); } [Fact] - public void should_contain_package_name() + public void Should_contain_package_name() { - MockLogger.contains_message("upgradepackage").ShouldBeTrue(); + MockLogger.ContainsMessage("upgradepackage").ShouldBeTrue(); } [Fact] - public void should_not_contain_any_version_number() + public void Should_not_contain_any_version_number() { - MockLogger.contains_message(".0").ShouldBeFalse(); + MockLogger.ContainsMessage(".0").ShouldBeFalse(); } } - public class when_listing_local_packages_limiting_output : ScenariosBase + public class When_listing_local_packages_limiting_output : ScenariosBase { public override void Context() { @@ -125,46 +125,46 @@ public override void Context() public override void Because() { - MockLogger.reset(); - Results = Service.list_run(Configuration).ToList(); + MockLogger.Reset(); + Results = Service.List(Configuration).ToList(); } [Fact] - public void should_contain_packages_and_versions_with_a_pipe_between_them() + public void Should_contain_packages_and_versions_with_a_pipe_between_them() { - MockLogger.contains_message("upgradepackage|1.0.0").ShouldBeTrue(); + MockLogger.ContainsMessage("upgradepackage|1.0.0").ShouldBeTrue(); } [Fact] - public void should_only_have_messages_related_to_package_information() + public void Should_only_have_messages_related_to_package_information() { - var count = MockLogger.Messages.SelectMany(messageLevel => messageLevel.Value.or_empty_list_if_null()).Count(); + var count = MockLogger.MessagesFor(LogLevel.Info).OrEmpty().Count(); count.ShouldEqual(2); } [Fact] - public void should_not_contain_packages_and_versions_with_a_space_between_them() + public void Should_not_contain_packages_and_versions_with_a_space_between_them() { - MockLogger.contains_message("upgradepackage 1.0.0").ShouldBeFalse(); + MockLogger.ContainsMessage("upgradepackage 1.0.0").ShouldBeFalse(); } [Fact] - public void should_not_contain_a_summary() + public void Should_not_contain_a_summary() { - MockLogger.contains_message("packages installed").ShouldBeFalse(); + MockLogger.ContainsMessage("packages installed").ShouldBeFalse(); } [Fact] - public void should_not_contain_debugging_messages() + public void Should_not_contain_debugging_messages() { - MockLogger.contains_message("Searching for package information", LogLevel.Debug).ShouldBeFalse(); - MockLogger.contains_message("Running list with the following filter", LogLevel.Debug).ShouldBeFalse(); - MockLogger.contains_message("Start of List", LogLevel.Debug).ShouldBeFalse(); - MockLogger.contains_message("End of List", LogLevel.Debug).ShouldBeFalse(); + MockLogger.ContainsMessage("Searching for package information", LogLevel.Debug).ShouldBeFalse(); + MockLogger.ContainsMessage("Running list with the following filter", LogLevel.Debug).ShouldBeFalse(); + MockLogger.ContainsMessage("Start of List", LogLevel.Debug).ShouldBeFalse(); + MockLogger.ContainsMessage("End of List", LogLevel.Debug).ShouldBeFalse(); } } - public class when_listing_local_packages_limiting_output_with_id_only : ScenariosBase + public class When_listing_local_packages_limiting_output_with_id_only : ScenariosBase { public override void Context() { @@ -176,30 +176,30 @@ public override void Context() public override void Because() { - MockLogger.reset(); - Results = Service.list_run(Configuration).ToList(); + MockLogger.Reset(); + Results = Service.List(Configuration).ToList(); } [Fact] - public void should_contain_packages_id() + public void Should_contain_packages_id() { - MockLogger.contains_message("upgradepackage").ShouldBeTrue(); + MockLogger.ContainsMessage("upgradepackage").ShouldBeTrue(); } [Fact] - public void should_not_contain_any_version_number() + public void Should_not_contain_any_version_number() { - MockLogger.contains_message(".0").ShouldBeFalse(); + MockLogger.ContainsMessage(".0").ShouldBeFalse(); } [Fact] - public void should_not_contain_pipe() + public void Should_not_contain_pipe() { - MockLogger.contains_message("|").ShouldBeFalse(); + MockLogger.ContainsMessage("|").ShouldBeFalse(); } } - public class when_listing_local_packages_with_uppercase_id_package_installed : ScenariosBase + public class When_listing_local_packages_with_uppercase_id_package_installed : ScenariosBase { public override void Context() { @@ -210,41 +210,41 @@ public override void Context() public override void Because() { - MockLogger.reset(); - Results = Service.list_run(Configuration).ToList(); + MockLogger.Reset(); + Results = Service.List(Configuration).ToList(); } [Fact] - public void should_contain_packages_and_versions_with_a_space_between_them() + public void Should_contain_packages_and_versions_with_a_space_between_them() { - MockLogger.contains_message("upgradepackage 1.0.0").ShouldBeTrue(); + MockLogger.ContainsMessage("upgradepackage 1.0.0").ShouldBeTrue(); } [Fact] - public void should_contain_uppercase_id_package() + public void Should_contain_uppercase_id_package() { - MockLogger.contains_message("UpperCase 1.1.0").ShouldBeTrue(); + MockLogger.ContainsMessage("UpperCase 1.1.0").ShouldBeTrue(); } [Fact] - public void should_not_contain_packages_and_versions_with_a_pipe_between_them() + public void Should_not_contain_packages_and_versions_with_a_pipe_between_them() { - MockLogger.contains_message("upgradepackage|1.0.0").ShouldBeFalse(); + MockLogger.ContainsMessage("upgradepackage|1.0.0").ShouldBeFalse(); } [Fact] - public void should_contain_a_summary() + public void Should_contain_a_summary() { - MockLogger.contains_message("packages installed").ShouldBeTrue(); + MockLogger.ContainsMessage("packages installed").ShouldBeTrue(); } [Fact] - public void should_contain_debugging_messages() + public void Should_contain_debugging_messages() { - MockLogger.contains_message("Searching for package information", LogLevel.Debug).ShouldBeTrue(); - MockLogger.contains_message("Running list with the following filter", LogLevel.Debug).ShouldBeTrue(); - MockLogger.contains_message("Start of List", LogLevel.Debug).ShouldBeTrue(); - MockLogger.contains_message("End of List", LogLevel.Debug).ShouldBeTrue(); + MockLogger.ContainsMessage("Searching for package information", LogLevel.Debug).ShouldBeTrue(); + MockLogger.ContainsMessage("Running list with the following filter", LogLevel.Debug).ShouldBeTrue(); + MockLogger.ContainsMessage("Start of List", LogLevel.Debug).ShouldBeTrue(); + MockLogger.ContainsMessage("End of List", LogLevel.Debug).ShouldBeTrue(); } } } diff --git a/src/chocolatey.tests.integration/scenarios/PackScenarios.cs b/src/chocolatey.tests.integration/scenarios/PackScenarios.cs index aecc02166a..196927d302 100644 --- a/src/chocolatey.tests.integration/scenarios/PackScenarios.cs +++ b/src/chocolatey.tests.integration/scenarios/PackScenarios.cs @@ -53,8 +53,8 @@ public override void BeforeEachSpec() Scenario.reset(Configuration); Service = NUnitSetup.Container.GetInstance(); - MockLogger.reset(); - ServiceAct = () => Service.pack_run(Configuration); + MockLogger.Reset(); + ServiceAct = () => Service.Pack(Configuration); } protected void AddFile(string fileName, string fileContent) @@ -64,10 +64,10 @@ protected void AddFile(string fileName, string fileContent) } [Categories.ExceptionHandling] - public class when_invalid_data_is_used_in_nuspec_file : ScenariosInvalidBase + public class When_invalid_data_is_used_in_nuspec_file : ScenariosInvalidBase { [Fact] - public void should_throw_xml_exception_on_empty_nuspec_file() + public void Should_throw_xml_exception_on_empty_nuspec_file() { AddFile("myPackage.nuspec", string.Empty); @@ -76,7 +76,7 @@ public void should_throw_xml_exception_on_empty_nuspec_file() [TestCase("")] [TestCase("invalid_version")] - public void should_throw_invalid_data_exception_on_invalid_version(string version) + public void Should_throw_invalid_data_exception_on_invalid_version(string version) { AddFile("myPackage.nuspec", @" @@ -94,7 +94,7 @@ public void should_throw_invalid_data_exception_on_invalid_version(string versio false -".format_with(version)); +".FormatWith(version)); ServiceAct.ShouldThrow(); } @@ -151,7 +151,7 @@ public override void AfterObservations() } [Fact] - public void generated_package_should_be_in_current_directory() + public void Generated_package_should_be_in_current_directory() { var infos = MockLogger.MessagesFor(LogLevel.Info); infos.Count.ShouldEqual(2); @@ -162,7 +162,7 @@ public void generated_package_should_be_in_current_directory() } [Fact] - public void generated_package_should_include_expected_version_in_nuspec() + public void Generated_package_should_include_expected_version_in_nuspec() { using (var packageReader = new PackageArchiveReader(PackagePath)) { @@ -173,7 +173,7 @@ public void generated_package_should_include_expected_version_in_nuspec() } [Fact] - public void sources_should_be_set_to_current_directory() + public void Sources_should_be_set_to_current_directory() { if (string.IsNullOrEmpty(ExpectedSubDirectory)) { @@ -191,31 +191,31 @@ protected virtual string GetNuspecContent() } } - public class when_packing_without_specifying_an_output_directory : ScenariosBase + public class When_packing_without_specifying_an_output_directory : ScenariosBase { protected override string ExpectedNuspecVersion => "0.1.0"; public override void Because() { - MockLogger.reset(); - Service.pack_run(Configuration); + MockLogger.Reset(); + Service.Pack(Configuration); } } - public class when_packing_with_an_output_directory : ScenariosBase + public class When_packing_with_an_output_directory : ScenariosBase { protected override string ExpectedNuspecVersion => "0.1.0"; protected override string ExpectedSubDirectory => "PackageOutput"; public override void Because() { - MockLogger.reset(); - Service.pack_run(Configuration); + MockLogger.Reset(); + Service.Pack(Configuration); } } [Categories.LegacySemVer] - public class when_packing_with_only_major_minor_version : ScenariosBase + public class When_packing_with_only_major_minor_version : ScenariosBase { protected override string PackagePath => Path.Combine("PackageOutput", "test-package.0.3.0.nupkg"); protected override string ExpectedNuspecVersion => "0.3.0"; @@ -223,8 +223,8 @@ public class when_packing_with_only_major_minor_version : ScenariosBase public override void Because() { - MockLogger.reset(); - Service.pack_run(Configuration); + MockLogger.Reset(); + Service.Pack(Configuration); } protected override string GetNuspecContent() @@ -234,15 +234,15 @@ protected override string GetNuspecContent() } [Categories.LegacySemVer] - public class when_packing_with_full_4_part_versioning_scheme : ScenariosBase + public class When_packing_with_full_4_part_versioning_scheme : ScenariosBase { protected override string ExpectedNuspecVersion => "0.5.0.5"; protected override string ExpectedSubDirectory => "PackageOutput"; public override void Because() { - MockLogger.reset(); - Service.pack_run(Configuration); + MockLogger.Reset(); + Service.Pack(Configuration); } protected override string GetNuspecContent() @@ -252,7 +252,7 @@ protected override string GetNuspecContent() } [Categories.SemVer20] - public class when_packaging_with_build_metadata : ScenariosBase + public class When_packaging_with_build_metadata : ScenariosBase { protected override string ExpectedNuspecVersion => "0.1.0+build.543"; protected override string ExpectedPathVersion => "0.1.0"; @@ -260,8 +260,8 @@ public class when_packaging_with_build_metadata : ScenariosBase public override void Because() { - MockLogger.reset(); - Service.pack_run(Configuration); + MockLogger.Reset(); + Service.Pack(Configuration); } protected override string GetNuspecContent() @@ -271,7 +271,7 @@ protected override string GetNuspecContent() } [Categories.SemVer20] - public class when_packaging_with_semver_20_pre_release_tag : ScenariosBase + public class When_packaging_with_semver_20_pre_release_tag : ScenariosBase { protected override string ExpectedNuspecVersion => "0.1.0-rc.5+build.999"; protected override string ExpectedPathVersion => "0.1.0-rc.5"; @@ -279,8 +279,8 @@ public class when_packaging_with_semver_20_pre_release_tag : ScenariosBase public override void Because() { - MockLogger.reset(); - Service.pack_run(Configuration); + MockLogger.Reset(); + Service.Pack(Configuration); } protected override string GetNuspecContent() @@ -290,15 +290,15 @@ protected override string GetNuspecContent() } [Categories.LegacySemVer] - public class when_packaging_with_legacy_pre_release_tag : ScenariosBase + public class When_packaging_with_legacy_pre_release_tag : ScenariosBase { protected override string ExpectedNuspecVersion => "0.1.0-rc-5"; protected override string ExpectedSubDirectory => "PackageOutput"; public override void Because() { - MockLogger.reset(); - Service.pack_run(Configuration); + MockLogger.Reset(); + Service.Pack(Configuration); } protected override string GetNuspecContent() @@ -308,7 +308,7 @@ protected override string GetNuspecContent() } [Categories.SemVer20] - public class when_packaging_with_four_part_version_with_trailing_zero : ScenariosBase + public class When_packaging_with_four_part_version_with_trailing_zero : ScenariosBase { private string _originalVersion = "0.1.0.0"; protected override string ExpectedNuspecVersion => "0.1.0"; @@ -316,18 +316,18 @@ public class when_packaging_with_four_part_version_with_trailing_zero : Scenario public override void Because() { - MockLogger.reset(); - Service.pack_run(Configuration); + MockLogger.Reset(); + Service.Pack(Configuration); } protected override string GetNuspecContent() { - return NuspecContentWithFormatableVersion.format_with(_originalVersion); + return NuspecContentWithFormatableVersion.FormatWith(_originalVersion); } } [Categories.SemVer20] - public class when_packaging_with_leading_zeros_four_part : ScenariosBase + public class When_packaging_with_leading_zeros_four_part : ScenariosBase { private string _originalVersion = "01.02.03.04"; protected override string ExpectedNuspecVersion => "1.2.3.4"; @@ -335,18 +335,18 @@ public class when_packaging_with_leading_zeros_four_part : ScenariosBase public override void Because() { - MockLogger.reset(); - Service.pack_run(Configuration); + MockLogger.Reset(); + Service.Pack(Configuration); } protected override string GetNuspecContent() { - return NuspecContentWithFormatableVersion.format_with(_originalVersion); + return NuspecContentWithFormatableVersion.FormatWith(_originalVersion); } } [Categories.SemVer20] - public class when_packaging_with_leading_zeros_three_part : ScenariosBase + public class When_packaging_with_leading_zeros_three_part : ScenariosBase { private string _originalVersion = "01.02.04"; protected override string ExpectedNuspecVersion => "1.2.4"; @@ -354,18 +354,18 @@ public class when_packaging_with_leading_zeros_three_part : ScenariosBase public override void Because() { - MockLogger.reset(); - Service.pack_run(Configuration); + MockLogger.Reset(); + Service.Pack(Configuration); } protected override string GetNuspecContent() { - return NuspecContentWithFormatableVersion.format_with(_originalVersion); + return NuspecContentWithFormatableVersion.FormatWith(_originalVersion); } } [Categories.SemVer20] - public class when_packaging_with_leading_zeros_two_part : ScenariosBase + public class When_packaging_with_leading_zeros_two_part : ScenariosBase { private string _originalVersion = "01.02"; protected override string ExpectedNuspecVersion => "1.2.0"; @@ -373,18 +373,18 @@ public class when_packaging_with_leading_zeros_two_part : ScenariosBase public override void Because() { - MockLogger.reset(); - Service.pack_run(Configuration); + MockLogger.Reset(); + Service.Pack(Configuration); } protected override string GetNuspecContent() { - return NuspecContentWithFormatableVersion.format_with(_originalVersion); + return NuspecContentWithFormatableVersion.FormatWith(_originalVersion); } } [Categories.SemVer20] - public class when_packaging_with_multiple_leading_zeros : ScenariosBase + public class When_packaging_with_multiple_leading_zeros : ScenariosBase { private string _originalVersion = "0001.0002.0003"; protected override string ExpectedNuspecVersion => "1.2.3"; @@ -392,17 +392,17 @@ public class when_packaging_with_multiple_leading_zeros : ScenariosBase public override void Because() { - MockLogger.reset(); - Service.pack_run(Configuration); + MockLogger.Reset(); + Service.Pack(Configuration); } protected override string GetNuspecContent() { - return NuspecContentWithFormatableVersion.format_with(_originalVersion); + return NuspecContentWithFormatableVersion.FormatWith(_originalVersion); } } - public class when_packing_with_properties : ScenariosBase + public class When_packing_with_properties : ScenariosBase { protected override string ExpectedNuspecVersion => "0.1.0"; @@ -418,12 +418,12 @@ public override void Context() public override void Because() { - MockLogger.reset(); - Service.pack_run(Configuration); + MockLogger.Reset(); + Service.Pack(Configuration); } [Fact] - public void property_settings_should_be_logged_as_debug_messages() + public void Property_settings_should_be_logged_as_debug_messages() { var messages = MockLogger.MessagesFor(LogLevel.Debug); messages.Count.ShouldEqual(2); @@ -432,10 +432,10 @@ public void property_settings_should_be_logged_as_debug_messages() } } - public class when_packing_with_unsupported_elements : ScenariosInvalidBase + public class When_packing_with_unsupported_elements : ScenariosInvalidBase { [Fact] - public void should_throw_exception_on_all_unsupported_elements() + public void Should_throw_exception_on_all_unsupported_elements() { AddFile("myPackage.nuspec", NuspecContentWithAllUnsupportedElements); @@ -443,7 +443,7 @@ public void should_throw_exception_on_all_unsupported_elements() } [Fact] - public void should_throw_exception_on_serviceable_element() + public void Should_throw_exception_on_serviceable_element() { AddFile("myPackage.nuspec", NuspecContentWithServiceableElement); @@ -451,7 +451,7 @@ public void should_throw_exception_on_serviceable_element() } [Fact] - public void should_throw_exception_on_license_element() + public void Should_throw_exception_on_license_element() { AddFile("myPackage.nuspec", NuspecContentWithLicenseElement); @@ -459,7 +459,7 @@ public void should_throw_exception_on_license_element() } [Fact] - public void should_throw_exception_on_repository_element() + public void Should_throw_exception_on_repository_element() { AddFile("myPackage.nuspec", NuspecContentWithRepositoryElement); @@ -467,7 +467,7 @@ public void should_throw_exception_on_repository_element() } [Fact] - public void should_throw_exception_on_package_types_element() + public void Should_throw_exception_on_package_types_element() { AddFile("myPackage.nuspec", NuspecContentWithPackageTypesElement); @@ -475,7 +475,7 @@ public void should_throw_exception_on_package_types_element() } [Fact] - public void should_throw_exception_on_framework_references_element() + public void Should_throw_exception_on_framework_references_element() { AddFile("myPackage.nuspec", NuspecContentWithFrameWorkReferencesElement); @@ -483,7 +483,7 @@ public void should_throw_exception_on_framework_references_element() } [Fact] - public void should_throw_exception_on_readme_element() + public void Should_throw_exception_on_readme_element() { AddFile("myPackage.nuspec", NuspecContentWithReadmeElement); @@ -491,7 +491,7 @@ public void should_throw_exception_on_readme_element() } [Fact] - public void should_throw_exception_on_icon_element() + public void Should_throw_exception_on_icon_element() { AddFile("myPackage.nuspec", NuspecContentWithIconElement); @@ -499,6 +499,27 @@ public void should_throw_exception_on_icon_element() } } + public class When_packing_with_min_client_version : ScenariosBase + { + protected override string ExpectedNuspecVersion => "0.1.0"; + protected override string ExpectedSubDirectory => "PackageOutput"; + + // This high version is to ensure that pack does not throw, even if the min client version is well + // above both the Chocolatey and NuGet assembly versions. + private string _minClientVersion = "100.0.0"; + + public override void Because() + { + MockLogger.Reset(); + Service.Pack(Configuration); + } + + protected override string GetNuspecContent() + { + return NuspecContentWithFormatableMinClientVersion.FormatWith(_minClientVersion); + } + } + private const string NuspecContent = @" @@ -916,5 +937,28 @@ public void should_throw_exception_on_icon_element() "; + + private const string NuspecContentWithFormatableMinClientVersion = @" + + + test-package + Test Package + 0.1.0 + package author + package owner + A brief summary + A big description + test admin + + http://apache.org/2 + false + + + + + + + +"; } } diff --git a/src/chocolatey.tests.integration/scenarios/PinScenarios.cs b/src/chocolatey.tests.integration/scenarios/PinScenarios.cs index 7c17f7a6f6..38cdbc9b1d 100644 --- a/src/chocolatey.tests.integration/scenarios/PinScenarios.cs +++ b/src/chocolatey.tests.integration/scenarios/PinScenarios.cs @@ -56,7 +56,7 @@ public override void Context() (c) => { var attributes = c.GetType().GetCustomAttributes(typeof(CommandForAttribute), false); - return attributes.Cast().Any(attribute => attribute.CommandName.is_equal_to(Configuration.CommandName)); + return attributes.Cast().Any(attribute => attribute.CommandName.IsEqualTo(Configuration.CommandName)); }).FirstOrDefault() as ChocolateyPinCommand; Configuration.Sources = ApplicationParameters.PackagesLocation; @@ -66,235 +66,235 @@ public override void Context() } } - public class when_listing_pins_with_no_pins : ScenariosBase + public class When_listing_pins_with_no_pins : ScenariosBase { public override void Context() { base.Context(); - Configuration.PinCommand.Command = PinCommandType.list; + Configuration.PinCommand.Command = PinCommandType.List; } public override void Because() { - MockLogger.reset(); - Service.run(Configuration); + MockLogger.Reset(); + Service.Run(Configuration); } [Fact] - public void should_not_contain_list_results() + public void Should_not_contain_list_results() { - MockLogger.contains_message("upgradepackage 1.0.0", LogLevel.Info).ShouldBeFalse(); - MockLogger.contains_message("upgradepackage 1.0.0", LogLevel.Warn).ShouldBeFalse(); - MockLogger.contains_message("upgradepackage 1.0.0", LogLevel.Error).ShouldBeFalse(); + MockLogger.ContainsMessage("upgradepackage 1.0.0", LogLevel.Info).ShouldBeFalse(); + MockLogger.ContainsMessage("upgradepackage 1.0.0", LogLevel.Warn).ShouldBeFalse(); + MockLogger.ContainsMessage("upgradepackage 1.0.0", LogLevel.Error).ShouldBeFalse(); } [Fact] - public void should_not_contain_any_pins_by_default() + public void Should_not_contain_any_pins_by_default() { - MockLogger.contains_message("upgradepackage|1.0.0").ShouldBeFalse(); + MockLogger.ContainsMessage("upgradepackage|1.0.0").ShouldBeFalse(); } } - public class when_listing_pins_with_an_existing_pin : ScenariosBase + public class When_listing_pins_with_an_existing_pin : ScenariosBase { public override void Context() { base.Context(); - Configuration.PinCommand.Command = PinCommandType.add; + Configuration.PinCommand.Command = PinCommandType.Add; Configuration.PinCommand.Name = "upgradepackage"; - Service.run(Configuration); - Configuration.PinCommand.Command = PinCommandType.list; + Service.Run(Configuration); + Configuration.PinCommand.Command = PinCommandType.List; } public override void Because() { - MockLogger.reset(); - Service.run(Configuration); + MockLogger.Reset(); + Service.Run(Configuration); } [Fact] - public void should_not_contain_list_results() + public void Should_not_contain_list_results() { - MockLogger.contains_message("upgradepackage 1.0.0", LogLevel.Info).ShouldBeFalse(); - MockLogger.contains_message("upgradepackage 1.0.0", LogLevel.Warn).ShouldBeFalse(); - MockLogger.contains_message("upgradepackage 1.0.0", LogLevel.Error).ShouldBeFalse(); + MockLogger.ContainsMessage("upgradepackage 1.0.0", LogLevel.Info).ShouldBeFalse(); + MockLogger.ContainsMessage("upgradepackage 1.0.0", LogLevel.Warn).ShouldBeFalse(); + MockLogger.ContainsMessage("upgradepackage 1.0.0", LogLevel.Error).ShouldBeFalse(); } [Fact] - public void should_contain_existing_pin_messages() + public void Should_contain_existing_pin_messages() { - MockLogger.contains_message("upgradepackage|1.0.0").ShouldBeTrue(); + MockLogger.ContainsMessage("upgradepackage|1.0.0").ShouldBeTrue(); } } - public class when_listing_pins_with_existing_pins : ScenariosBase + public class When_listing_pins_with_existing_pins : ScenariosBase { public override void Context() { base.Context(); - Configuration.PinCommand.Command = PinCommandType.add; + Configuration.PinCommand.Command = PinCommandType.Add; Configuration.PinCommand.Name = "upgradepackage"; - Service.run(Configuration); + Service.Run(Configuration); Configuration.PinCommand.Name = "installpackage"; - Service.run(Configuration); - Configuration.PinCommand.Command = PinCommandType.list; + Service.Run(Configuration); + Configuration.PinCommand.Command = PinCommandType.List; } public override void Because() { - MockLogger.reset(); - Service.run(Configuration); + MockLogger.Reset(); + Service.Run(Configuration); } [Fact] - public void should_not_contain_list_results() + public void Should_not_contain_list_results() { - MockLogger.contains_message("upgradepackage 1.0.0", LogLevel.Info).ShouldBeFalse(); - MockLogger.contains_message("upgradepackage 1.0.0", LogLevel.Warn).ShouldBeFalse(); - MockLogger.contains_message("upgradepackage 1.0.0", LogLevel.Error).ShouldBeFalse(); + MockLogger.ContainsMessage("upgradepackage 1.0.0", LogLevel.Info).ShouldBeFalse(); + MockLogger.ContainsMessage("upgradepackage 1.0.0", LogLevel.Warn).ShouldBeFalse(); + MockLogger.ContainsMessage("upgradepackage 1.0.0", LogLevel.Error).ShouldBeFalse(); } [Fact] - public void should_contain_a_pin_message_for_each_existing_pin() + public void Should_contain_a_pin_message_for_each_existing_pin() { - MockLogger.contains_message("installpackage|1.0.0").ShouldBeTrue(); - MockLogger.contains_message("upgradepackage|1.0.0").ShouldBeTrue(); + MockLogger.ContainsMessage("installpackage|1.0.0").ShouldBeTrue(); + MockLogger.ContainsMessage("upgradepackage|1.0.0").ShouldBeTrue(); } } - public class when_setting_a_pin_for_an_installed_package : ScenariosBase + public class When_setting_a_pin_for_an_installed_package : ScenariosBase { public override void Context() { base.Context(); - Configuration.PinCommand.Command = PinCommandType.add; + Configuration.PinCommand.Command = PinCommandType.Add; Configuration.PinCommand.Name = "upgradepackage"; } public override void Because() { - MockLogger.reset(); - Service.run(Configuration); + MockLogger.Reset(); + Service.Run(Configuration); } [Fact] - public void should_contain_success_message() + public void Should_contain_success_message() { - MockLogger.contains_message("Successfully added a pin for upgradepackage").ShouldBeTrue(); + MockLogger.ContainsMessage("Successfully added a pin for upgradepackage").ShouldBeTrue(); } } - public class when_setting_a_pin_for_an_already_pinned_package : ScenariosBase + public class When_setting_a_pin_for_an_already_pinned_package : ScenariosBase { public override void Context() { base.Context(); - Configuration.PinCommand.Command = PinCommandType.add; + Configuration.PinCommand.Command = PinCommandType.Add; Configuration.PinCommand.Name = "upgradepackage"; - Service.run(Configuration); + Service.Run(Configuration); } public override void Because() { - MockLogger.reset(); - Service.run(Configuration); + MockLogger.Reset(); + Service.Run(Configuration); } [Fact] - public void should_contain_nothing_to_do_message() + public void Should_contain_nothing_to_do_message() { - MockLogger.contains_message("Nothing to change. Pin already set or removed.").ShouldBeTrue(); + MockLogger.ContainsMessage("Nothing to change. Pin already set or removed.").ShouldBeTrue(); } } - public class when_setting_a_pin_for_a_non_installed_package : ScenariosBase + public class When_setting_a_pin_for_a_non_installed_package : ScenariosBase { public override void Context() { base.Context(); - Configuration.PinCommand.Command = PinCommandType.add; + Configuration.PinCommand.Command = PinCommandType.Add; Configuration.PinCommand.Name = "whatisthis"; } public override void Because() { - MockLogger.reset(); + MockLogger.Reset(); } [Fact] - public void should_throw_an_error_about_not_finding_the_package() + public void Should_throw_an_error_about_not_finding_the_package() { - Assert.That(() => Service.run(Configuration), + Assert.That(() => Service.Run(Configuration), Throws.TypeOf() .And.Message.EqualTo("Unable to find package named 'whatisthis' to pin. Please check to ensure it is installed.")); } } - public class when_removing_a_pin_for_a_pinned_package : ScenariosBase + public class When_removing_a_pin_for_a_pinned_package : ScenariosBase { public override void Context() { base.Context(); - Configuration.PinCommand.Command = PinCommandType.add; + Configuration.PinCommand.Command = PinCommandType.Add; Configuration.PinCommand.Name = "upgradepackage"; - Service.run(Configuration); + Service.Run(Configuration); - Configuration.PinCommand.Command = PinCommandType.remove; + Configuration.PinCommand.Command = PinCommandType.Remove; } public override void Because() { - MockLogger.reset(); - Service.run(Configuration); + MockLogger.Reset(); + Service.Run(Configuration); } [Fact] - public void should_contain_success_message() + public void Should_contain_success_message() { - MockLogger.contains_message("Successfully removed a pin for upgradepackage").ShouldBeTrue(); + MockLogger.ContainsMessage("Successfully removed a pin for upgradepackage").ShouldBeTrue(); } } - public class when_removing_a_pin_for_an_unpinned_package : ScenariosBase + public class When_removing_a_pin_for_an_unpinned_package : ScenariosBase { public override void Context() { base.Context(); - Configuration.PinCommand.Command = PinCommandType.remove; + Configuration.PinCommand.Command = PinCommandType.Remove; Configuration.PinCommand.Name = "upgradepackage"; } public override void Because() { - MockLogger.reset(); - Service.run(Configuration); + MockLogger.Reset(); + Service.Run(Configuration); } [Fact] - public void should_contain_nothing_to_do_message() + public void Should_contain_nothing_to_do_message() { - MockLogger.contains_message("Nothing to change. Pin already set or removed.").ShouldBeTrue(); + MockLogger.ContainsMessage("Nothing to change. Pin already set or removed.").ShouldBeTrue(); } } - public class when_removing_a_pin_for_a_non_installed_package : ScenariosBase + public class When_removing_a_pin_for_a_non_installed_package : ScenariosBase { public override void Context() { base.Context(); - Configuration.PinCommand.Command = PinCommandType.remove; + Configuration.PinCommand.Command = PinCommandType.Remove; Configuration.PinCommand.Name = "whatisthis"; } public override void Because() { - MockLogger.reset(); + MockLogger.Reset(); } [Fact] - public void should_throw_an_error_about_not_finding_the_package() + public void Should_throw_an_error_about_not_finding_the_package() { - Assert.That(() => Service.run(Configuration), + Assert.That(() => Service.Run(Configuration), Throws.TypeOf() .And.Message.EqualTo("Unable to find package named 'whatisthis' to pin. Please check to ensure it is installed.")); } diff --git a/src/chocolatey.tests.integration/scenarios/SearchScenarios.cs b/src/chocolatey.tests.integration/scenarios/SearchScenarios.cs index ded60d60c5..78828b5203 100644 --- a/src/chocolatey.tests.integration/scenarios/SearchScenarios.cs +++ b/src/chocolatey.tests.integration/scenarios/SearchScenarios.cs @@ -48,7 +48,7 @@ public override void Context() } [Categories.SourcePriority] - public class when_searching_packages_with_source_priority : ScenariosBase + public class When_searching_packages_with_source_priority : ScenariosBase { public override void Context() { @@ -67,12 +67,12 @@ public override void Context() public override void Because() { - MockLogger.reset(); - Results = Service.list_run(Configuration).ToList(); + MockLogger.Reset(); + Results = Service.List(Configuration).ToList(); } [Fact] - public void should_only_pick_up_package_from_highest_priority() + public void Should_only_pick_up_package_from_highest_priority() { Results.Count.ShouldEqual(1); Results[0].Name.ShouldEqual("upgradepackage"); @@ -81,7 +81,7 @@ public void should_only_pick_up_package_from_highest_priority() } [Categories.SourcePriority] - public class when_searching_packages_with_source_priority_and_pre_release : ScenariosBase + public class When_searching_packages_with_source_priority_and_pre_release : ScenariosBase { public override void Context() { @@ -104,12 +104,12 @@ public override void Context() public override void Because() { - MockLogger.reset(); - Results = Service.list_run(Configuration).ToList(); + MockLogger.Reset(); + Results = Service.List(Configuration).ToList(); } [Fact] - public void should_only_pick_up_package_from_highest_priority() + public void Should_only_pick_up_package_from_highest_priority() { Results.Count.ShouldEqual(2); Results[0].Name.ShouldEqual("upgradepackage"); @@ -120,7 +120,7 @@ public void should_only_pick_up_package_from_highest_priority() } [Categories.SourcePriority] - public class when_searching_packages_with_source_priority_and_different_package_in_different_feed : ScenariosBase + public class When_searching_packages_with_source_priority_and_different_package_in_different_feed : ScenariosBase { public override void Context() { @@ -144,12 +144,12 @@ public override void Context() public override void Because() { - MockLogger.reset(); - Results = Service.list_run(Configuration).ToList(); + MockLogger.Reset(); + Results = Service.List(Configuration).ToList(); } [Fact] - public void should_pick_up_packages_from_all_feeds_except_those_with_same_name() + public void Should_pick_up_packages_from_all_feeds_except_those_with_same_name() { Results.Count.ShouldEqual(4); Results[0].Name.ShouldEqual("conflictingdependency"); @@ -163,51 +163,51 @@ public void should_pick_up_packages_from_all_feeds_except_those_with_same_name() } } - public class when_searching_packages_with_no_filter_happy_path : ScenariosBase + public class When_searching_packages_with_no_filter_happy_path : ScenariosBase { public override void Because() { - MockLogger.reset(); - Results = Service.list_run(Configuration).ToList(); + MockLogger.Reset(); + Results = Service.List(Configuration).ToList(); } [Fact] [WindowsOnly] [Platform(Exclude = "Mono")] - public void should_list_available_packages_only_once() + public void Should_list_available_packages_only_once() { - MockLogger.contains_message_count("upgradepackage").ShouldEqual(1); + MockLogger.ContainsMessageCount("upgradepackage").ShouldEqual(1); } [Fact] - public void should_contain_packages_and_versions_with_a_space_between_them() + public void Should_contain_packages_and_versions_with_a_space_between_them() { - MockLogger.contains_message("upgradepackage 1.1.0").ShouldBeTrue(); + MockLogger.ContainsMessage("upgradepackage 1.1.0").ShouldBeTrue(); } [Fact] - public void should_not_contain_packages_and_versions_with_a_pipe_between_them() + public void Should_not_contain_packages_and_versions_with_a_pipe_between_them() { - MockLogger.contains_message("upgradepackage|1.1.0").ShouldBeFalse(); + MockLogger.ContainsMessage("upgradepackage|1.1.0").ShouldBeFalse(); } [Fact] - public void should_contain_a_summary() + public void Should_contain_a_summary() { - MockLogger.contains_message("packages found").ShouldBeTrue(); + MockLogger.ContainsMessage("packages found").ShouldBeTrue(); } [Fact] - public void should_contain_debugging_messages() + public void Should_contain_debugging_messages() { - MockLogger.contains_message("Searching for package information", LogLevel.Debug).ShouldBeTrue(); - MockLogger.contains_message("Running list with the following filter", LogLevel.Debug).ShouldBeTrue(); - MockLogger.contains_message("Start of List", LogLevel.Debug).ShouldBeTrue(); - MockLogger.contains_message("End of List", LogLevel.Debug).ShouldBeTrue(); + MockLogger.ContainsMessage("Searching for package information", LogLevel.Debug).ShouldBeTrue(); + MockLogger.ContainsMessage("Running list with the following filter", LogLevel.Debug).ShouldBeTrue(); + MockLogger.ContainsMessage("Start of List", LogLevel.Debug).ShouldBeTrue(); + MockLogger.ContainsMessage("End of List", LogLevel.Debug).ShouldBeTrue(); } } - public class when_searching_for_a_particular_package : ScenariosBase + public class When_searching_for_a_particular_package : ScenariosBase { public override void Context() { @@ -217,39 +217,39 @@ public override void Context() public override void Because() { - MockLogger.reset(); - Results = Service.list_run(Configuration).ToList(); + MockLogger.Reset(); + Results = Service.List(Configuration).ToList(); } [Fact] - public void should_contain_packages_and_versions_with_a_space_between_them() + public void Should_contain_packages_and_versions_with_a_space_between_them() { - MockLogger.contains_message("upgradepackage 1.1.0").ShouldBeTrue(); + MockLogger.ContainsMessage("upgradepackage 1.1.0").ShouldBeTrue(); } [Fact] - public void should_not_contain_packages_that_do_not_match() + public void Should_not_contain_packages_that_do_not_match() { - MockLogger.contains_message("installpackage").ShouldBeFalse(); + MockLogger.ContainsMessage("installpackage").ShouldBeFalse(); } [Fact] - public void should_contain_a_summary() + public void Should_contain_a_summary() { - MockLogger.contains_message("packages found").ShouldBeTrue(); + MockLogger.ContainsMessage("packages found").ShouldBeTrue(); } [Fact] - public void should_contain_debugging_messages() + public void Should_contain_debugging_messages() { - MockLogger.contains_message("Searching for package information", LogLevel.Debug).ShouldBeTrue(); - MockLogger.contains_message("Running list with the following filter", LogLevel.Debug).ShouldBeTrue(); - MockLogger.contains_message("Start of List", LogLevel.Debug).ShouldBeTrue(); - MockLogger.contains_message("End of List", LogLevel.Debug).ShouldBeTrue(); + MockLogger.ContainsMessage("Searching for package information", LogLevel.Debug).ShouldBeTrue(); + MockLogger.ContainsMessage("Running list with the following filter", LogLevel.Debug).ShouldBeTrue(); + MockLogger.ContainsMessage("Start of List", LogLevel.Debug).ShouldBeTrue(); + MockLogger.ContainsMessage("End of List", LogLevel.Debug).ShouldBeTrue(); } } - public class when_searching_all_available_packages : ScenariosBase + public class When_searching_all_available_packages : ScenariosBase { public override void Context() { @@ -259,46 +259,46 @@ public override void Context() public override void Because() { - MockLogger.reset(); - Results = Service.list_run(Configuration).ToList(); + MockLogger.Reset(); + Results = Service.List(Configuration).ToList(); } [Fact] - public void should_list_available_packages_as_many_times_as_they_show_on_the_feed() + public void Should_list_available_packages_as_many_times_as_they_show_on_the_feed() { - MockLogger.contains_message_count("upgradepackage").ShouldNotEqual(0); - MockLogger.contains_message_count("upgradepackage").ShouldNotEqual(1); + MockLogger.ContainsMessageCount("upgradepackage").ShouldNotEqual(0); + MockLogger.ContainsMessageCount("upgradepackage").ShouldNotEqual(1); } [Fact] - public void should_contain_packages_and_versions_with_a_space_between_them() + public void Should_contain_packages_and_versions_with_a_space_between_them() { - MockLogger.contains_message("upgradepackage 1.1.0").ShouldBeTrue(); + MockLogger.ContainsMessage("upgradepackage 1.1.0").ShouldBeTrue(); } [Fact] - public void should_not_contain_packages_and_versions_with_a_pipe_between_them() + public void Should_not_contain_packages_and_versions_with_a_pipe_between_them() { - MockLogger.contains_message("upgradepackage|1.1.0").ShouldBeFalse(); + MockLogger.ContainsMessage("upgradepackage|1.1.0").ShouldBeFalse(); } [Fact] - public void should_contain_a_summary() + public void Should_contain_a_summary() { - MockLogger.contains_message("packages found").ShouldBeTrue(); + MockLogger.ContainsMessage("packages found").ShouldBeTrue(); } [Fact] - public void should_contain_debugging_messages() + public void Should_contain_debugging_messages() { - MockLogger.contains_message("Searching for package information", LogLevel.Debug).ShouldBeTrue(); - MockLogger.contains_message("Running list with the following filter", LogLevel.Debug).ShouldBeTrue(); - MockLogger.contains_message("Start of List", LogLevel.Debug).ShouldBeTrue(); - MockLogger.contains_message("End of List", LogLevel.Debug).ShouldBeTrue(); + MockLogger.ContainsMessage("Searching for package information", LogLevel.Debug).ShouldBeTrue(); + MockLogger.ContainsMessage("Running list with the following filter", LogLevel.Debug).ShouldBeTrue(); + MockLogger.ContainsMessage("Start of List", LogLevel.Debug).ShouldBeTrue(); + MockLogger.ContainsMessage("End of List", LogLevel.Debug).ShouldBeTrue(); } } - public class when_searching_packages_with_verbose : ScenariosBase + public class When_searching_packages_with_verbose : ScenariosBase { public override void Context() { @@ -308,57 +308,57 @@ public override void Context() public override void Because() { - MockLogger.reset(); - Results = Service.list_run(Configuration).ToList(); + MockLogger.Reset(); + Results = Service.List(Configuration).ToList(); } [Fact] - public void should_contain_packages_and_versions_with_a_space_between_them() + public void Should_contain_packages_and_versions_with_a_space_between_them() { - MockLogger.contains_message("upgradepackage 1.1.0").ShouldBeTrue(); + MockLogger.ContainsMessage("upgradepackage 1.1.0").ShouldBeTrue(); } [Fact] - public void should_contain_description() + public void Should_contain_description() { - MockLogger.contains_message("Description: ").ShouldBeTrue(); + MockLogger.ContainsMessage("Description: ").ShouldBeTrue(); } [Fact] - public void should_contain_tags() + public void Should_contain_tags() { - MockLogger.contains_message("Tags: ").ShouldBeTrue(); + MockLogger.ContainsMessage("Tags: ").ShouldBeTrue(); } [Fact] - public void should_contain_download_counts() + public void Should_contain_download_counts() { - MockLogger.contains_message("Number of Downloads: ").ShouldBeTrue(); + MockLogger.ContainsMessage("Number of Downloads: ").ShouldBeTrue(); } [Fact] - public void should_not_contain_packages_and_versions_with_a_pipe_between_them() + public void Should_not_contain_packages_and_versions_with_a_pipe_between_them() { - MockLogger.contains_message("upgradepackage|1.1.0").ShouldBeFalse(); + MockLogger.ContainsMessage("upgradepackage|1.1.0").ShouldBeFalse(); } [Fact] - public void should_contain_a_summary() + public void Should_contain_a_summary() { - MockLogger.contains_message("packages found").ShouldBeTrue(); + MockLogger.ContainsMessage("packages found").ShouldBeTrue(); } [Fact] - public void should_contain_debugging_messages() + public void Should_contain_debugging_messages() { - MockLogger.contains_message("Searching for package information", LogLevel.Debug).ShouldBeTrue(); - MockLogger.contains_message("Running list with the following filter", LogLevel.Debug).ShouldBeTrue(); - MockLogger.contains_message("Start of List", LogLevel.Debug).ShouldBeTrue(); - MockLogger.contains_message("End of List", LogLevel.Debug).ShouldBeTrue(); + MockLogger.ContainsMessage("Searching for package information", LogLevel.Debug).ShouldBeTrue(); + MockLogger.ContainsMessage("Running list with the following filter", LogLevel.Debug).ShouldBeTrue(); + MockLogger.ContainsMessage("Start of List", LogLevel.Debug).ShouldBeTrue(); + MockLogger.ContainsMessage("End of List", LogLevel.Debug).ShouldBeTrue(); } } - public class when_listing_packages_with_no_sources_enabled : ScenariosBase + public class When_listing_packages_with_no_sources_enabled : ScenariosBase { public override void Context() { @@ -368,24 +368,24 @@ public override void Context() public override void Because() { - MockLogger.reset(); - Results = Service.list_run(Configuration).ToList(); + MockLogger.Reset(); + Results = Service.List(Configuration).ToList(); } [Fact] - public void should_have_no_sources_enabled_result() + public void Should_have_no_sources_enabled_result() { - MockLogger.contains_message("Unable to search for packages when there are no sources enabled for", LogLevel.Error).ShouldBeTrue(); + MockLogger.ContainsMessage("Unable to search for packages when there are no sources enabled for", LogLevel.Error).ShouldBeTrue(); } [Fact] - public void should_not_list_any_packages() + public void Should_not_list_any_packages() { Results.Count().ShouldEqual(0); } } - public class when_searching_for_an_exact_package : ScenariosBase + public class When_searching_for_an_exact_package : ScenariosBase { public override void Context() { @@ -400,51 +400,51 @@ public override void Context() public override void Because() { - MockLogger.reset(); - Results = Service.list_run(Configuration).ToList(); + MockLogger.Reset(); + Results = Service.List(Configuration).ToList(); } [Fact] - public void should_not_error() + public void Should_not_error() { // nothing necessary here } [Fact] - public void should_find_exactly_one_result() + public void Should_find_exactly_one_result() { Results.Count.ShouldEqual(1); } [Fact] - public void should_contain_packages_and_versions_with_a_space_between_them() + public void Should_contain_packages_and_versions_with_a_space_between_them() { - MockLogger.contains_message("exactpackage 1.0.0").ShouldBeTrue(); + MockLogger.ContainsMessage("exactpackage 1.0.0").ShouldBeTrue(); } [Fact] - public void should_not_contain_packages_that_do_not_match() + public void Should_not_contain_packages_that_do_not_match() { - MockLogger.contains_message("exactpackage.dontfind").ShouldBeFalse(); + MockLogger.ContainsMessage("exactpackage.dontfind").ShouldBeFalse(); } [Fact] - public void should_contain_a_summary() + public void Should_contain_a_summary() { - MockLogger.contains_message("packages found").ShouldBeTrue(); + MockLogger.ContainsMessage("packages found").ShouldBeTrue(); } [Fact] - public void should_contain_debugging_messages() + public void Should_contain_debugging_messages() { - MockLogger.contains_message("Searching for package information", LogLevel.Debug).ShouldBeTrue(); - MockLogger.contains_message("Running list with the following filter", LogLevel.Debug).ShouldBeTrue(); - MockLogger.contains_message("Start of List", LogLevel.Debug).ShouldBeTrue(); - MockLogger.contains_message("End of List", LogLevel.Debug).ShouldBeTrue(); + MockLogger.ContainsMessage("Searching for package information", LogLevel.Debug).ShouldBeTrue(); + MockLogger.ContainsMessage("Running list with the following filter", LogLevel.Debug).ShouldBeTrue(); + MockLogger.ContainsMessage("Start of List", LogLevel.Debug).ShouldBeTrue(); + MockLogger.ContainsMessage("End of List", LogLevel.Debug).ShouldBeTrue(); } } - public class when_searching_for_an_exact_package_with_zero_results : ScenariosBase + public class When_searching_for_an_exact_package_with_zero_results : ScenariosBase { public override void Context() { @@ -459,47 +459,47 @@ public override void Context() public override void Because() { - MockLogger.reset(); - Results = Service.list_run(Configuration).ToList(); + MockLogger.Reset(); + Results = Service.List(Configuration).ToList(); } [Fact] - public void should_not_error() + public void Should_not_error() { // nothing necessary here } [Fact] - public void should_not_have_any_results() + public void Should_not_have_any_results() { Results.Count.ShouldEqual(0); } [Fact] - public void should_not_contain_packages_that_do_not_match() + public void Should_not_contain_packages_that_do_not_match() { - MockLogger.contains_message("exactpackage.dontfind").ShouldBeFalse(); + MockLogger.ContainsMessage("exactpackage.dontfind").ShouldBeFalse(); } [Fact] - public void should_contain_a_summary() + public void Should_contain_a_summary() { - MockLogger.contains_message("packages found").ShouldBeTrue(); + MockLogger.ContainsMessage("packages found").ShouldBeTrue(); } [Fact] - public void should_contain_debugging_messages() + public void Should_contain_debugging_messages() { - MockLogger.contains_message("Searching for package information", LogLevel.Debug).ShouldBeTrue(); - MockLogger.contains_message("Running list with the following filter", LogLevel.Debug).ShouldBeTrue(); - MockLogger.contains_message("Start of List", LogLevel.Debug).ShouldBeTrue(); - MockLogger.contains_message("End of List", LogLevel.Debug).ShouldBeTrue(); + MockLogger.ContainsMessage("Searching for package information", LogLevel.Debug).ShouldBeTrue(); + MockLogger.ContainsMessage("Running list with the following filter", LogLevel.Debug).ShouldBeTrue(); + MockLogger.ContainsMessage("Start of List", LogLevel.Debug).ShouldBeTrue(); + MockLogger.ContainsMessage("End of List", LogLevel.Debug).ShouldBeTrue(); } } - public class when_searching_for_all_packages_with_exact_id : ScenariosBase + public class When_searching_for_all_packages_with_exact_id : ScenariosBase { public override void Context() { @@ -515,38 +515,38 @@ public override void Context() public override void Because() { - MockLogger.reset(); - Results = Service.list_run(Configuration).ToList(); + MockLogger.Reset(); + Results = Service.List(Configuration).ToList(); } [Fact] - public void should_not_error() + public void Should_not_error() { // nothing necessary here } [Fact] - public void should_find_two_results() + public void Should_find_two_results() { Results.Count.ShouldEqual(2); } [Fact] - public void should_find_only_packages_with_exact_id() + public void Should_find_only_packages_with_exact_id() { Results[0].PackageMetadata.Id.ShouldEqual("exactpackage"); Results[1].PackageMetadata.Id.ShouldEqual("exactpackage"); } [Fact] - public void should_find_all_non_prerelease_versions_in_descending_order() + public void Should_find_all_non_prerelease_versions_in_descending_order() { Results[0].PackageMetadata.Version.ToNormalizedString().ShouldEqual("1.0.0"); Results[1].PackageMetadata.Version.ToNormalizedString().ShouldEqual("0.9.0"); } } - public class when_searching_for_all_packages_including_prerelease_with_exact_id : ScenariosBase + public class When_searching_for_all_packages_including_prerelease_with_exact_id : ScenariosBase { public override void Context() { @@ -563,24 +563,24 @@ public override void Context() public override void Because() { - MockLogger.reset(); - Results = Service.list_run(Configuration).ToList(); + MockLogger.Reset(); + Results = Service.List(Configuration).ToList(); } [Fact] - public void should_not_error() + public void Should_not_error() { // nothing necessary here } [Fact] - public void should_find_three_results() + public void Should_find_three_results() { Results.Count.ShouldEqual(3); } [Fact] - public void should_find_only_packages_with_exact_id() + public void Should_find_only_packages_with_exact_id() { Results[0].PackageMetadata.Id.ShouldEqual("exactpackage"); Results[1].PackageMetadata.Id.ShouldEqual("exactpackage"); @@ -588,7 +588,7 @@ public void should_find_only_packages_with_exact_id() } [Fact] - public void should_find_all_versions_in_descending_order() + public void Should_find_all_versions_in_descending_order() { Results[0].PackageMetadata.Version.ToNormalizedString().ShouldEqual("1.0.0"); Results[1].PackageMetadata.Version.ToNormalizedString().ShouldEqual("1.0.0-beta1"); diff --git a/src/chocolatey.tests.integration/scenarios/UninstallScenarios.cs b/src/chocolatey.tests.integration/scenarios/UninstallScenarios.cs index e2c3511279..cfa932c664 100644 --- a/src/chocolatey.tests.integration/scenarios/UninstallScenarios.cs +++ b/src/chocolatey.tests.integration/scenarios/UninstallScenarios.cs @@ -59,7 +59,7 @@ public override void Context() } } - public class when_noop_uninstalling_a_package : ScenariosBase + public class When_noop_uninstalling_a_package : ScenariosBase { public override void Context() { @@ -69,11 +69,11 @@ public override void Context() public override void Because() { - Service.uninstall_noop(Configuration); + Service.UninstallDryRun(Configuration); } [Fact] - public void should_not_uninstall_a_package_from_the_lib_directory() + public void Should_not_uninstall_a_package_from_the_lib_directory() { var packageDir = Path.Combine(Scenario.get_top_level(), "lib", Configuration.PackageNames); @@ -81,10 +81,10 @@ public void should_not_uninstall_a_package_from_the_lib_directory() } [Fact] - public void should_contain_a_message_that_it_would_have_uninstalled_a_package() + public void Should_contain_a_message_that_it_would_have_uninstalled_a_package() { bool expectedMessage = false; - foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).or_empty_list_if_null()) + foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).OrEmpty()) { if (message.Contains("Would have uninstalled installpackage v1.0.0")) expectedMessage = true; } @@ -95,21 +95,21 @@ public void should_contain_a_message_that_it_would_have_uninstalled_a_package() [Fact] [WindowsOnly] [Platform(Exclude = "Mono")] - public void should_contain_a_message_that_it_would_have_run_a_powershell_script() + public void Should_contain_a_message_that_it_would_have_run_a_powershell_script() { - MockLogger.contains_message("chocolateyuninstall.ps1").ShouldBeTrue(); + MockLogger.ContainsMessage("chocolateyuninstall.ps1").ShouldBeTrue(); } [Fact] [WindowsOnly] [Platform(Exclude = "Mono")] - public void should_contain_a_message_that_it_would_have_run_powershell_modification_script() + public void Should_contain_a_message_that_it_would_have_run_powershell_modification_script() { - MockLogger.contains_message("chocolateyBeforeModify.ps1").ShouldBeTrue(); + MockLogger.ContainsMessage("chocolateyBeforeModify.ps1").ShouldBeTrue(); } } - public class when_noop_uninstalling_a_package_that_does_not_exist : ScenariosBase + public class When_noop_uninstalling_a_package_that_does_not_exist : ScenariosBase { public override void Context() { @@ -120,14 +120,14 @@ public override void Context() public override void Because() { - Service.uninstall_noop(Configuration); + Service.UninstallDryRun(Configuration); } [Fact] - public void should_contain_a_message_that_it_was_unable_to_find_package() + public void Should_contain_a_message_that_it_was_unable_to_find_package() { bool expectedMessage = false; - foreach (var message in MockLogger.MessagesFor(LogLevel.Error).or_empty_list_if_null()) + foreach (var message in MockLogger.MessagesFor(LogLevel.Error).OrEmpty()) { if (message.Contains("somethingnonexisting is not installed. Cannot uninstall a non-existent package")) expectedMessage = true; } @@ -136,18 +136,18 @@ public void should_contain_a_message_that_it_was_unable_to_find_package() } } - public class when_uninstalling_a_package_happy_path : ScenariosBase + public class When_uninstalling_a_package_happy_path : ScenariosBase { private PackageResult packageResult; public override void Because() { - Results = Service.uninstall_run(Configuration); + Results = Service.Uninstall(Configuration); packageResult = Results.FirstOrDefault().Value; } [Fact] - public void should_remove_the_package_from_the_lib_directory() + public void Should_remove_the_package_from_the_lib_directory() { var packageDir = Path.Combine(Scenario.get_top_level(), "lib", Configuration.PackageNames); @@ -155,7 +155,7 @@ public void should_remove_the_package_from_the_lib_directory() } [Fact] - public void should_delete_the_rollback() + public void Should_delete_the_rollback() { var packageDir = Path.Combine(Scenario.get_top_level(), "lib-bkp", Configuration.PackageNames); @@ -165,7 +165,7 @@ public void should_delete_the_rollback() [Fact] [WindowsOnly] [Platform(Exclude = "Mono")] - public void should_delete_a_shim_for_console_in_the_bin_directory() + public void Should_delete_a_shim_for_console_in_the_bin_directory() { var shimfile = Path.Combine(Scenario.get_top_level(), "bin", "console.exe"); @@ -175,7 +175,7 @@ public void should_delete_a_shim_for_console_in_the_bin_directory() [Fact] [WindowsOnly] [Platform(Exclude = "Mono")] - public void should_delete_a_shim_for_graphical_in_the_bin_directory() + public void Should_delete_a_shim_for_graphical_in_the_bin_directory() { var shimfile = Path.Combine(Scenario.get_top_level(), "bin", "graphical.exe"); @@ -183,7 +183,7 @@ public void should_delete_a_shim_for_graphical_in_the_bin_directory() } [Fact] - public void should_delete_any_files_created_during_the_install() + public void Should_delete_any_files_created_during_the_install() { var generatedFile = Path.Combine(Scenario.get_top_level(), "lib", Configuration.PackageNames, "simplefile.txt"); @@ -191,10 +191,10 @@ public void should_delete_any_files_created_during_the_install() } [Fact] - public void should_contain_a_warning_message_that_it_uninstalled_successfully() + public void Should_contain_a_warning_message_that_it_uninstalled_successfully() { bool installedSuccessfully = false; - foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).or_empty_list_if_null()) + foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).OrEmpty()) { if (message.Contains("1/1")) installedSuccessfully = true; } @@ -203,25 +203,25 @@ public void should_contain_a_warning_message_that_it_uninstalled_successfully() } [Fact] - public void should_have_a_successful_package_result() + public void Should_have_a_successful_package_result() { packageResult.Success.ShouldBeTrue(); } [Fact] - public void should_not_have_inconclusive_package_result() + public void Should_not_have_inconclusive_package_result() { packageResult.Inconclusive.ShouldBeFalse(); } [Fact] - public void should_not_have_warning_package_result() + public void Should_not_have_warning_package_result() { packageResult.Warning.ShouldBeFalse(); } [Fact] - public void config_should_match_package_result_name() + public void Config_should_match_package_result_name() { packageResult.Name.ShouldEqual(Configuration.PackageNames); } @@ -229,21 +229,21 @@ public void config_should_match_package_result_name() [Fact] [WindowsOnly] [Platform(Exclude = "Mono")] - public void should_have_executed_chocolateyBeforeModify_script() + public void Should_have_executed_chocolateyBeforeModify_script() { - MockLogger.contains_message("installpackage 1.0.0 Before Modification", LogLevel.Info).ShouldBeTrue(); + MockLogger.ContainsMessage("installpackage 1.0.0 Before Modification", LogLevel.Info).ShouldBeTrue(); } [Fact] [WindowsOnly] [Platform(Exclude = "Mono")] - public void should_have_executed_chocolateyUninstall_script() + public void Should_have_executed_chocolateyUninstall_script() { - MockLogger.contains_message("installpackage 1.0.0 Uninstalled", LogLevel.Info).ShouldBeTrue(); + MockLogger.ContainsMessage("installpackage 1.0.0 Uninstalled", LogLevel.Info).ShouldBeTrue(); } } - public class when_force_uninstalling_a_package : ScenariosBase + public class When_force_uninstalling_a_package : ScenariosBase { private PackageResult packageResult; @@ -255,12 +255,12 @@ public override void Context() public override void Because() { - Results = Service.uninstall_run(Configuration); + Results = Service.Uninstall(Configuration); packageResult = Results.FirstOrDefault().Value; } [Fact] - public void should_remove_the_package_from_the_lib_directory() + public void Should_remove_the_package_from_the_lib_directory() { var packageDir = Path.Combine(Scenario.get_top_level(), "lib", Configuration.PackageNames); @@ -268,7 +268,7 @@ public void should_remove_the_package_from_the_lib_directory() } [Fact] - public void should_delete_the_rollback() + public void Should_delete_the_rollback() { var packageDir = Path.Combine(Scenario.get_top_level(), "lib-bkp", Configuration.PackageNames); @@ -276,7 +276,7 @@ public void should_delete_the_rollback() } [Fact] - public void should_delete_a_shim_for_console_in_the_bin_directory() + public void Should_delete_a_shim_for_console_in_the_bin_directory() { var shimfile = Path.Combine(Scenario.get_top_level(), "bin", "console.exe"); @@ -284,7 +284,7 @@ public void should_delete_a_shim_for_console_in_the_bin_directory() } [Fact] - public void should_delete_a_shim_for_graphical_in_the_bin_directory() + public void Should_delete_a_shim_for_graphical_in_the_bin_directory() { var shimfile = Path.Combine(Scenario.get_top_level(), "bin", "graphical.exe"); @@ -292,10 +292,10 @@ public void should_delete_a_shim_for_graphical_in_the_bin_directory() } [Fact] - public void should_contain_a_warning_message_that_it_uninstalled_successfully() + public void Should_contain_a_warning_message_that_it_uninstalled_successfully() { bool installedSuccessfully = false; - foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).or_empty_list_if_null()) + foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).OrEmpty()) { if (message.Contains("1/1")) installedSuccessfully = true; } @@ -304,36 +304,36 @@ public void should_contain_a_warning_message_that_it_uninstalled_successfully() } [Fact] - public void should_have_a_successful_package_result() + public void Should_have_a_successful_package_result() { packageResult.Success.ShouldBeTrue(); } [Fact] - public void should_not_have_inconclusive_package_result() + public void Should_not_have_inconclusive_package_result() { packageResult.Inconclusive.ShouldBeFalse(); } [Fact] - public void should_not_have_warning_package_result() + public void Should_not_have_warning_package_result() { packageResult.Warning.ShouldBeFalse(); } [Fact] - public void config_should_match_package_result_name() + public void Config_should_match_package_result_name() { packageResult.Name.ShouldEqual(Configuration.PackageNames); } } - public class when_uninstalling_packages_with_packages_config : ScenariosBase + public class When_uninstalling_packages_with_packages_config : ScenariosBase { public override void Context() { base.Context(); - var packagesConfig = "{0}{1}context{1}testing.packages.config".format_with(Scenario.get_top_level(), Path.DirectorySeparatorChar); + var packagesConfig = "{0}{1}context{1}testing.packages.config".FormatWith(Scenario.get_top_level(), Path.DirectorySeparatorChar); Configuration.PackageNames = Configuration.Input = packagesConfig; } @@ -342,9 +342,9 @@ public override void Because() } [Fact] - public void should_throw_an_error_that_it_is_not_allowed() + public void Should_throw_an_error_that_it_is_not_allowed() { - Action m = () => Service.uninstall_run(Configuration); + Action m = () => Service.Uninstall(Configuration); m.ShouldThrow(); } @@ -352,7 +352,7 @@ public void should_throw_an_error_that_it_is_not_allowed() [WindowsOnly] [Platform(Exclude = "Mono")] - public class when_uninstalling_a_package_with_readonly_files : ScenariosBase + public class When_uninstalling_a_package_with_readonly_files : ScenariosBase { private PackageResult _packageResult; @@ -361,17 +361,17 @@ public override void Context() base.Context(); var fileToSetReadOnly = Path.Combine(Scenario.get_top_level(), "lib", Configuration.PackageNames, "tools", "chocolateyInstall.ps1"); var fileSystem = new DotNetFileSystem(); - fileSystem.ensure_file_attribute_set(fileToSetReadOnly, FileAttributes.ReadOnly); + fileSystem.EnsureFileAttributeSet(fileToSetReadOnly, FileAttributes.ReadOnly); } public override void Because() { - Results = Service.uninstall_run(Configuration); + Results = Service.Uninstall(Configuration); _packageResult = Results.FirstOrDefault().Value; } [Fact] - public void should_uninstall_the_package_from_the_lib_directory() + public void Should_uninstall_the_package_from_the_lib_directory() { var packageDir = Path.Combine(Scenario.get_top_level(), "lib", Configuration.PackageNames); @@ -379,7 +379,7 @@ public void should_uninstall_the_package_from_the_lib_directory() } [Fact] - public void should_delete_the_rollback() + public void Should_delete_the_rollback() { var packageDir = Path.Combine(Scenario.get_top_level(), "lib-bkp", Configuration.PackageNames); @@ -387,10 +387,10 @@ public void should_delete_the_rollback() } [Fact] - public void should_contain_a_message_that_it_uninstalled_successfully() + public void Should_contain_a_message_that_it_uninstalled_successfully() { bool expectedMessage = false; - foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).or_empty_list_if_null()) + foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).OrEmpty()) { if (message.Contains("uninstalled 1/1")) expectedMessage = true; } @@ -399,19 +399,19 @@ public void should_contain_a_message_that_it_uninstalled_successfully() } [Fact] - public void should_have_a_successful_package_result() + public void Should_have_a_successful_package_result() { _packageResult.Success.ShouldBeTrue(); } [Fact] - public void should_not_have_inconclusive_package_result() + public void Should_not_have_inconclusive_package_result() { _packageResult.Inconclusive.ShouldBeFalse(); } [Fact] - public void should_not_have_warning_package_result() + public void Should_not_have_warning_package_result() { _packageResult.Warning.ShouldBeFalse(); } @@ -419,7 +419,7 @@ public void should_not_have_warning_package_result() [WindowsOnly] [Platform(Exclude = "Mono")] - public class when_uninstalling_a_package_with_a_read_and_delete_share_locked_file : ScenariosBase + public class When_uninstalling_a_package_with_a_read_and_delete_share_locked_file : ScenariosBase { private PackageResult _packageResult; @@ -441,22 +441,32 @@ public override void AfterObservations() public override void Because() { - Results = Service.uninstall_run(Configuration); + Results = Service.Uninstall(Configuration); _packageResult = Results.FirstOrDefault().Value; } [Fact] - public void should_uninstall_the_package_from_the_lib_directory() + public void Should_uninstall_the_package_from_the_lib_directory() { var packageDir = Path.Combine(Scenario.get_top_level(), "lib", Configuration.PackageNames); DirectoryAssert.DoesNotExist(packageDir); } - [Fact] - [Pending("Does not work under .Net 4.8, See issue #2690")] - [Broken] - public void should_not_be_able_delete_the_rollback() + // Locking is inconsistent between client and server operating systems in .NET 4.8. + // On a server, if a file is Read and delete locked it can't be deleted, but on client systems it can. + [Fact, Platform(Exclude = "WindowsServer10")] + public void Should_have_deleted_the_rollback() + { + var packageDir = Path.Combine(Scenario.get_top_level(), "lib-bkp", Configuration.PackageNames); + + DirectoryAssert.DoesNotExist(packageDir); + } + + // Locking is inconsistent between client and server operating systems in .NET 4.8. + // On a server, if a file is Read and delete locked it can't be deleted, but on client systems it can. + [Fact, Platform("WindowsServer10")] + public void Should_not_have_deleted_the_rollback_on_server() { var packageDir = Path.Combine(Scenario.get_top_level(), "lib-bkp", Configuration.PackageNames); @@ -464,10 +474,10 @@ public void should_not_be_able_delete_the_rollback() } [Fact] - public void should_contain_a_message_that_it_uninstalled_successfully() + public void Should_contain_a_message_that_it_uninstalled_successfully() { bool expectedMessage = false; - foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).or_empty_list_if_null()) + foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).OrEmpty()) { if (message.Contains("uninstalled 1/1")) expectedMessage = true; } @@ -476,19 +486,19 @@ public void should_contain_a_message_that_it_uninstalled_successfully() } [Fact] - public void should_have_a_successful_package_result() + public void Should_have_a_successful_package_result() { _packageResult.Success.ShouldBeTrue(); } [Fact] - public void should_not_have_inconclusive_package_result() + public void Should_not_have_inconclusive_package_result() { _packageResult.Inconclusive.ShouldBeFalse(); } [Fact] - public void should_not_have_warning_package_result() + public void Should_not_have_warning_package_result() { _packageResult.Warning.ShouldBeFalse(); } @@ -496,7 +506,7 @@ public void should_not_have_warning_package_result() [WindowsOnly] [Platform(Exclude = "Mono")] - public class when_uninstalling_a_package_with_an_exclusively_locked_file : ScenariosBase + public class When_uninstalling_a_package_with_an_exclusively_locked_file : ScenariosBase { private PackageResult _packageResult; @@ -518,12 +528,12 @@ public override void AfterObservations() public override void Because() { - Results = Service.uninstall_run(Configuration); + Results = Service.Uninstall(Configuration); _packageResult = Results.FirstOrDefault().Value; } [Fact] - public void should_not_be_able_to_remove_the_package_from_the_lib_directory() + public void Should_not_be_able_to_remove_the_package_from_the_lib_directory() { var packageDir = Path.Combine(Scenario.get_top_level(), "lib", Configuration.PackageNames); @@ -531,7 +541,7 @@ public void should_not_be_able_to_remove_the_package_from_the_lib_directory() } [Fact] - public void should_delete_the_rollback() + public void Should_delete_the_rollback() { var packageDir = Path.Combine(Scenario.get_top_level(), "lib-bkp", Configuration.PackageNames); @@ -539,18 +549,42 @@ public void should_delete_the_rollback() } [Fact] - public void should_contain_old_files_in_directory() + public void Should_not_contain_old_files_in_directory() { var shimFile = Path.Combine(Scenario.get_top_level(), "lib", Configuration.PackageNames, "tools", "console.exe"); - FileAssert.Exists(shimFile); + FileAssert.DoesNotExist(shimFile); + } + + [Fact] + public void Should_keep_locked_file_in_directory() + { + var lockedFile = Path.Combine(Scenario.get_top_level(), "lib", Configuration.PackageNames, "tools", "chocolateyInstall.ps1"); + + FileAssert.Exists(lockedFile); + } + + [Fact] + public void Should_contain_a_message_about_not_all_files_are_removed() + { + bool expectedMessage = false; + + foreach (var message in MockLogger.MessagesFor(LogLevel.Error).OrEmpty()) + { + if (message.Contains("Unable to delete all existing package files. There will be leftover files requiring manual cleanup")) + { + expectedMessage = true; + } + } + + expectedMessage.ShouldBeTrue(); } [Fact] - public void should_contain_a_message_that_it_was_not_able_to_uninstall() + public void Should_contain_a_message_that_it_was_not_able_to_uninstall() { bool expectedMessage = false; - foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).or_empty_list_if_null()) + foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).OrEmpty()) { if (message.Contains("uninstalled 0/1")) expectedMessage = true; } @@ -559,25 +593,25 @@ public void should_contain_a_message_that_it_was_not_able_to_uninstall() } [Fact] - public void should_not_have_a_successful_package_result() + public void Should_not_have_a_successful_package_result() { _packageResult.Success.ShouldBeFalse(); } [Fact] - public void should_not_have_inconclusive_package_result() + public void Should_not_have_inconclusive_package_result() { _packageResult.Inconclusive.ShouldBeFalse(); } [Fact] - public void should_not_have_warning_package_result() + public void Should_not_have_warning_package_result() { _packageResult.Warning.ShouldBeFalse(); } } - public class when_uninstalling_a_package_with_added_files : ScenariosBase + public class When_uninstalling_a_package_with_added_files : ScenariosBase { private PackageResult packageResult; @@ -590,12 +624,12 @@ public override void Context() public override void Because() { - Results = Service.uninstall_run(Configuration); + Results = Service.Uninstall(Configuration); packageResult = Results.FirstOrDefault().Value; } [Fact] - public void should_keep_the_added_file() + public void Should_keep_the_added_file() { var fileAdded = Path.Combine(Scenario.get_top_level(), "lib", Configuration.PackageNames, "dude.txt"); @@ -603,18 +637,18 @@ public void should_keep_the_added_file() } [Fact] - public void should_delete_everything_but_the_added_file_from_the_package_directory() + public void Should_delete_everything_but_the_added_file_from_the_package_directory() { var files = Directory.GetFiles(Path.Combine(Scenario.get_top_level(), "lib", Configuration.PackageNames)); - foreach (var file in files.or_empty_list_if_null()) + foreach (var file in files.OrEmpty()) { Path.GetFileName(file).ShouldEqual("dude.txt", "Expected files were not deleted."); } } [Fact] - public void should_delete_the_rollback() + public void Should_delete_the_rollback() { var packageDir = Path.Combine(Scenario.get_top_level(), "lib-bkp", Configuration.PackageNames); @@ -624,7 +658,7 @@ public void should_delete_the_rollback() [Fact] [WindowsOnly] [Platform(Exclude = "Mono")] - public void should_delete_a_shim_for_console_in_the_bin_directory() + public void Should_delete_a_shim_for_console_in_the_bin_directory() { var shimfile = Path.Combine(Scenario.get_top_level(), "bin", "console.exe"); @@ -634,7 +668,7 @@ public void should_delete_a_shim_for_console_in_the_bin_directory() [Fact] [WindowsOnly] [Platform(Exclude = "Mono")] - public void should_delete_a_shim_for_graphical_in_the_bin_directory() + public void Should_delete_a_shim_for_graphical_in_the_bin_directory() { var shimfile = Path.Combine(Scenario.get_top_level(), "bin", "graphical.exe"); @@ -642,10 +676,10 @@ public void should_delete_a_shim_for_graphical_in_the_bin_directory() } [Fact] - public void should_contain_a_warning_message_that_it_uninstalled_successfully() + public void Should_contain_a_warning_message_that_it_uninstalled_successfully() { bool installedSuccessfully = false; - foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).or_empty_list_if_null()) + foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).OrEmpty()) { if (message.Contains("1/1")) installedSuccessfully = true; } @@ -654,31 +688,31 @@ public void should_contain_a_warning_message_that_it_uninstalled_successfully() } [Fact] - public void should_have_a_successful_package_result() + public void Should_have_a_successful_package_result() { packageResult.Success.ShouldBeTrue(); } [Fact] - public void should_not_have_inconclusive_package_result() + public void Should_not_have_inconclusive_package_result() { packageResult.Inconclusive.ShouldBeFalse(); } [Fact] - public void should_not_have_warning_package_result() + public void Should_not_have_warning_package_result() { packageResult.Warning.ShouldBeFalse(); } [Fact] - public void config_should_match_package_result_name() + public void Config_should_match_package_result_name() { packageResult.Name.ShouldEqual(Configuration.PackageNames); } } - public class when_uninstalling_a_package_with_changed_files : ScenariosBase + public class When_uninstalling_a_package_with_changed_files : ScenariosBase { private PackageResult packageResult; @@ -691,12 +725,12 @@ public override void Context() public override void Because() { - Results = Service.uninstall_run(Configuration); + Results = Service.Uninstall(Configuration); packageResult = Results.FirstOrDefault().Value; } [Fact] - public void should_keep_the_changed_file() + public void Should_keep_the_changed_file() { var fileChanged = Path.Combine(Scenario.get_top_level(), "lib", Configuration.PackageNames, "tools", "chocolateyinstall.ps1"); @@ -704,18 +738,18 @@ public void should_keep_the_changed_file() } [Fact] - public void should_delete_everything_but_the_changed_file_from_the_package_directory() + public void Should_delete_everything_but_the_changed_file_from_the_package_directory() { var files = Directory.GetFiles(Path.Combine(Scenario.get_top_level(), "lib", Configuration.PackageNames)); - foreach (var file in files.or_empty_list_if_null()) + foreach (var file in files.OrEmpty()) { Path.GetFileName(file).ShouldEqual("chocolateyInstall.ps1", "Expected files were not deleted."); } } [Fact] - public void should_delete_the_rollback() + public void Should_delete_the_rollback() { var packageDir = Path.Combine(Scenario.get_top_level(), "lib-bkp", Configuration.PackageNames); @@ -725,7 +759,7 @@ public void should_delete_the_rollback() [Fact] [WindowsOnly] [Platform(Exclude = "Mono")] - public void should_delete_a_shim_for_console_in_the_bin_directory() + public void Should_delete_a_shim_for_console_in_the_bin_directory() { var shimfile = Path.Combine(Scenario.get_top_level(), "bin", "console.exe"); @@ -735,7 +769,7 @@ public void should_delete_a_shim_for_console_in_the_bin_directory() [Fact] [WindowsOnly] [Platform(Exclude = "Mono")] - public void should_delete_a_shim_for_graphical_in_the_bin_directory() + public void Should_delete_a_shim_for_graphical_in_the_bin_directory() { var shimfile = Path.Combine(Scenario.get_top_level(), "bin", "graphical.exe"); @@ -743,10 +777,10 @@ public void should_delete_a_shim_for_graphical_in_the_bin_directory() } [Fact] - public void should_contain_a_warning_message_that_it_uninstalled_successfully() + public void Should_contain_a_warning_message_that_it_uninstalled_successfully() { bool installedSuccessfully = false; - foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).or_empty_list_if_null()) + foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).OrEmpty()) { if (message.Contains("1/1")) installedSuccessfully = true; } @@ -755,31 +789,31 @@ public void should_contain_a_warning_message_that_it_uninstalled_successfully() } [Fact] - public void should_have_a_successful_package_result() + public void Should_have_a_successful_package_result() { packageResult.Success.ShouldBeTrue(); } [Fact] - public void should_not_have_inconclusive_package_result() + public void Should_not_have_inconclusive_package_result() { packageResult.Inconclusive.ShouldBeFalse(); } [Fact] - public void should_not_have_warning_package_result() + public void Should_not_have_warning_package_result() { packageResult.Warning.ShouldBeFalse(); } [Fact] - public void config_should_match_package_result_name() + public void Config_should_match_package_result_name() { packageResult.Name.ShouldEqual(Configuration.PackageNames); } } - public class when_force_uninstalling_a_package_with_added_and_changed_files : ScenariosBase + public class When_force_uninstalling_a_package_with_added_and_changed_files : ScenariosBase { private PackageResult packageResult; @@ -795,12 +829,12 @@ public override void Context() public override void Because() { - Results = Service.uninstall_run(Configuration); + Results = Service.Uninstall(Configuration); packageResult = Results.FirstOrDefault().Value; } [Fact] - public void should_remove_the_package_from_the_lib_directory() + public void Should_remove_the_package_from_the_lib_directory() { var packageDir = Path.Combine(Scenario.get_top_level(), "lib", Configuration.PackageNames); @@ -808,7 +842,7 @@ public void should_remove_the_package_from_the_lib_directory() } [Fact] - public void should_not_keep_the_added_file() + public void Should_not_keep_the_added_file() { var fileChanged = Path.Combine(Scenario.get_top_level(), "lib", Configuration.PackageNames, "dude.txt"); @@ -816,7 +850,7 @@ public void should_not_keep_the_added_file() } [Fact] - public void should_not_keep_the_changed_file() + public void Should_not_keep_the_changed_file() { var fileChanged = Path.Combine(Scenario.get_top_level(), "lib", Configuration.PackageNames, "tools", "chocolateyinstall.ps1"); @@ -824,7 +858,7 @@ public void should_not_keep_the_changed_file() } [Fact] - public void should_delete_the_rollback() + public void Should_delete_the_rollback() { var packageDir = Path.Combine(Scenario.get_top_level(), "lib-bkp", Configuration.PackageNames); @@ -834,7 +868,7 @@ public void should_delete_the_rollback() [Fact] [WindowsOnly] [Platform(Exclude = "Mono")] - public void should_delete_a_shim_for_console_in_the_bin_directory() + public void Should_delete_a_shim_for_console_in_the_bin_directory() { var shimfile = Path.Combine(Scenario.get_top_level(), "bin", "console.exe"); @@ -844,7 +878,7 @@ public void should_delete_a_shim_for_console_in_the_bin_directory() [Fact] [WindowsOnly] [Platform(Exclude = "Mono")] - public void should_delete_a_shim_for_graphical_in_the_bin_directory() + public void Should_delete_a_shim_for_graphical_in_the_bin_directory() { var shimfile = Path.Combine(Scenario.get_top_level(), "bin", "graphical.exe"); @@ -852,10 +886,10 @@ public void should_delete_a_shim_for_graphical_in_the_bin_directory() } [Fact] - public void should_contain_a_warning_message_that_it_uninstalled_successfully() + public void Should_contain_a_warning_message_that_it_uninstalled_successfully() { bool installedSuccessfully = false; - foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).or_empty_list_if_null()) + foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).OrEmpty()) { if (message.Contains("1/1")) installedSuccessfully = true; } @@ -864,31 +898,31 @@ public void should_contain_a_warning_message_that_it_uninstalled_successfully() } [Fact] - public void should_have_a_successful_package_result() + public void Should_have_a_successful_package_result() { packageResult.Success.ShouldBeTrue(); } [Fact] - public void should_not_have_inconclusive_package_result() + public void Should_not_have_inconclusive_package_result() { packageResult.Inconclusive.ShouldBeFalse(); } [Fact] - public void should_not_have_warning_package_result() + public void Should_not_have_warning_package_result() { packageResult.Warning.ShouldBeFalse(); } [Fact] - public void config_should_match_package_result_name() + public void Config_should_match_package_result_name() { packageResult.Name.ShouldEqual(Configuration.PackageNames); } } - public class when_uninstalling_a_package_that_does_not_exist : ScenariosBase + public class When_uninstalling_a_package_that_does_not_exist : ScenariosBase { private PackageResult packageResult; @@ -900,15 +934,15 @@ public override void Context() public override void Because() { - Results = Service.uninstall_run(Configuration); + Results = Service.Uninstall(Configuration); packageResult = Results.FirstOrDefault().Value; } [Fact] - public void should_contain_a_message_that_it_was_unable_to_find_package() + public void Should_contain_a_message_that_it_was_unable_to_find_package() { bool expectedMessage = false; - foreach (var message in MockLogger.MessagesFor(LogLevel.Error).or_empty_list_if_null()) + foreach (var message in MockLogger.MessagesFor(LogLevel.Error).OrEmpty()) { if (message.Contains("somethingnonexisting is not installed. Cannot uninstall a non-existent package")) expectedMessage = true; } @@ -917,10 +951,10 @@ public void should_contain_a_message_that_it_was_unable_to_find_package() } [Fact] - public void should_contain_a_warning_message_that_it_uninstalled_successfully() + public void Should_contain_a_warning_message_that_it_uninstalled_successfully() { bool installedSuccessfully = false; - foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).or_empty_list_if_null()) + foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).OrEmpty()) { if (message.Contains("0/1")) installedSuccessfully = true; } @@ -929,25 +963,25 @@ public void should_contain_a_warning_message_that_it_uninstalled_successfully() } [Fact] - public void should_not_have_a_successful_package_result() + public void Should_not_have_a_successful_package_result() { packageResult.Success.ShouldBeFalse(); } [Fact] - public void should_not_have_inconclusive_package_result() + public void Should_not_have_inconclusive_package_result() { packageResult.Inconclusive.ShouldBeFalse(); } [Fact] - public void should_not_have_warning_package_result() + public void Should_not_have_warning_package_result() { packageResult.Warning.ShouldBeFalse(); } [Fact] - public void should_have_an_error_package_result() + public void Should_have_an_error_package_result() { bool errorFound = false; foreach (var message in packageResult.Messages) @@ -964,7 +998,7 @@ public void should_have_an_error_package_result() [WindowsOnly] [Platform(Exclude = "Mono")] - public class when_uninstalling_a_package_that_errors : ScenariosBase + public class When_uninstalling_a_package_that_errors : ScenariosBase { private PackageResult packageResult; @@ -976,12 +1010,12 @@ public override void Context() public override void Because() { - Results = Service.uninstall_run(Configuration); + Results = Service.Uninstall(Configuration); packageResult = Results.FirstOrDefault().Value; } [Fact] - public void should_not_remove_package_from_the_lib_directory() + public void Should_not_remove_package_from_the_lib_directory() { var packageDir = Path.Combine(Scenario.get_top_level(), "lib", Configuration.PackageNames); @@ -989,33 +1023,33 @@ public void should_not_remove_package_from_the_lib_directory() } [Fact] - public void should_still_have_the_package_file_in_the_directory() + public void Should_still_have_the_package_file_in_the_directory() { var packageFile = Path.Combine(Scenario.get_top_level(), "lib", Configuration.PackageNames, Configuration.PackageNames + NuGetConstants.PackageExtension); FileAssert.Exists(packageFile); } [Fact] - public void should_not_put_the_package_in_the_lib_bad_directory() + public void Should_put_the_package_in_the_lib_bad_directory() { var packageDir = Path.Combine(Scenario.get_top_level(), "lib-bad", Configuration.PackageNames); - DirectoryAssert.DoesNotExist(packageDir); + DirectoryAssert.Exists(packageDir); } [Fact] - public void should_not_delete_the_rollback() + public void Should_delete_the_rollback() { var packageDir = Path.Combine(Scenario.get_top_level(), "lib-bkp", Configuration.PackageNames); - DirectoryAssert.Exists(packageDir); + DirectoryAssert.DoesNotExist(packageDir); } [Fact] - public void should_contain_a_warning_message_that_it_was_unable_to_install_a_package() + public void Should_contain_a_warning_message_that_it_was_unable_to_install_a_package() { bool installedSuccessfully = false; - foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).or_empty_list_if_null()) + foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).OrEmpty()) { if (message.Contains("0/1")) installedSuccessfully = true; } @@ -1024,25 +1058,25 @@ public void should_contain_a_warning_message_that_it_was_unable_to_install_a_pac } [Fact] - public void should_not_have_a_successful_package_result() + public void Should_not_have_a_successful_package_result() { packageResult.Success.ShouldBeFalse(); } [Fact] - public void should_not_have_inconclusive_package_result() + public void Should_not_have_inconclusive_package_result() { packageResult.Inconclusive.ShouldBeFalse(); } [Fact] - public void should_not_have_warning_package_result() + public void Should_not_have_warning_package_result() { packageResult.Warning.ShouldBeFalse(); } [Fact] - public void should_have_an_error_package_result() + public void Should_have_an_error_package_result() { bool errorFound = false; foreach (var message in packageResult.Messages) @@ -1057,7 +1091,7 @@ public void should_have_an_error_package_result() } [Fact] - public void should_have_expected_error_in_package_result() + public void Should_have_expected_error_in_package_result() { bool errorFound = false; foreach (var message in packageResult.Messages) @@ -1073,7 +1107,7 @@ public void should_have_expected_error_in_package_result() } - public class when_uninstalling_a_hook_package : ScenariosBase + public class When_uninstalling_a_hook_package : ScenariosBase { private PackageResult _packageResult; @@ -1082,17 +1116,17 @@ public override void Context() base.Context(); Configuration.PackageNames = Configuration.Input = "scriptpackage.hook"; Scenario.add_packages_to_source_location(Configuration, Configuration.Input + ".1.0.0" + NuGetConstants.PackageExtension); - Service.install_run(Configuration); + Service.Install(Configuration); } public override void Because() { - Results = Service.uninstall_run(Configuration); + Results = Service.Uninstall(Configuration); _packageResult = Results.FirstOrDefault().Value; } [Fact] - public void should_remove_the_package_from_the_lib_directory() + public void Should_remove_the_package_from_the_lib_directory() { var packageDir = Path.Combine(Scenario.get_top_level(), "lib", Configuration.PackageNames); @@ -1100,7 +1134,7 @@ public void should_remove_the_package_from_the_lib_directory() } [Fact] - public void should_delete_the_rollback() + public void Should_delete_the_rollback() { var packageDir = Path.Combine(Scenario.get_top_level(), "lib-bkp", Configuration.PackageNames); @@ -1108,10 +1142,10 @@ public void should_delete_the_rollback() } [Fact] - public void should_contain_a_warning_message_that_it_uninstalled_successfully() + public void Should_contain_a_warning_message_that_it_uninstalled_successfully() { bool installedSuccessfully = false; - foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).or_empty_list_if_null()) + foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).OrEmpty()) { if (message.Contains("1/1")) installedSuccessfully = true; } @@ -1120,31 +1154,31 @@ public void should_contain_a_warning_message_that_it_uninstalled_successfully() } [Fact] - public void should_have_a_successful_package_result() + public void Should_have_a_successful_package_result() { _packageResult.Success.ShouldBeTrue(); } [Fact] - public void should_not_have_inconclusive_package_result() + public void Should_not_have_inconclusive_package_result() { _packageResult.Inconclusive.ShouldBeFalse(); } [Fact] - public void should_not_have_warning_package_result() + public void Should_not_have_warning_package_result() { _packageResult.Warning.ShouldBeFalse(); } [Fact] - public void config_should_match_package_result_name() + public void Config_should_match_package_result_name() { _packageResult.Name.ShouldEqual(Configuration.PackageNames); } [Fact] - public void should_remove_hooks_folder_for_the_package() + public void Should_remove_hooks_folder_for_the_package() { var hooksDirectory = Path.Combine(Scenario.get_top_level(), "hooks", Configuration.PackageNames.Replace(".hook", string.Empty)); @@ -1152,7 +1186,7 @@ public void should_remove_hooks_folder_for_the_package() } } - public class when_uninstalling_a_package_happy_path_with_hooks : ScenariosBase + public class When_uninstalling_a_package_happy_path_with_hooks : ScenariosBase { private PackageResult _packageResult; @@ -1165,12 +1199,12 @@ public override void Context() public override void Because() { - Results = Service.uninstall_run(Configuration); + Results = Service.Uninstall(Configuration); _packageResult = Results.FirstOrDefault().Value; } [Fact] - public void should_remove_the_package_from_the_lib_directory() + public void Should_remove_the_package_from_the_lib_directory() { var packageDir = Path.Combine(Scenario.get_top_level(), "lib", Configuration.PackageNames); @@ -1178,7 +1212,7 @@ public void should_remove_the_package_from_the_lib_directory() } [Fact] - public void should_delete_the_rollback() + public void Should_delete_the_rollback() { var packageDir = Path.Combine(Scenario.get_top_level(), "lib-bkp", Configuration.PackageNames); @@ -1188,7 +1222,7 @@ public void should_delete_the_rollback() [Fact] [WindowsOnly] [Platform(Exclude = "Mono")] - public void should_delete_a_shim_for_console_in_the_bin_directory() + public void Should_delete_a_shim_for_console_in_the_bin_directory() { var shimfile = Path.Combine(Scenario.get_top_level(), "bin", "console.exe"); @@ -1198,7 +1232,7 @@ public void should_delete_a_shim_for_console_in_the_bin_directory() [Fact] [WindowsOnly] [Platform(Exclude = "Mono")] - public void should_delete_a_shim_for_graphical_in_the_bin_directory() + public void Should_delete_a_shim_for_graphical_in_the_bin_directory() { var shimfile = Path.Combine(Scenario.get_top_level(), "bin", "graphical.exe"); @@ -1206,7 +1240,7 @@ public void should_delete_a_shim_for_graphical_in_the_bin_directory() } [Fact] - public void should_delete_any_files_created_during_the_install() + public void Should_delete_any_files_created_during_the_install() { var generatedFile = Path.Combine(Scenario.get_top_level(), "lib", Configuration.PackageNames, "simplefile.txt"); @@ -1214,10 +1248,10 @@ public void should_delete_any_files_created_during_the_install() } [Fact] - public void should_contain_a_warning_message_that_it_uninstalled_successfully() + public void Should_contain_a_warning_message_that_it_uninstalled_successfully() { bool installedSuccessfully = false; - foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).or_empty_list_if_null()) + foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).OrEmpty()) { if (message.Contains("1/1")) installedSuccessfully = true; } @@ -1226,25 +1260,25 @@ public void should_contain_a_warning_message_that_it_uninstalled_successfully() } [Fact] - public void should_have_a_successful_package_result() + public void Should_have_a_successful_package_result() { _packageResult.Success.ShouldBeTrue(); } [Fact] - public void should_not_have_inconclusive_package_result() + public void Should_not_have_inconclusive_package_result() { _packageResult.Inconclusive.ShouldBeFalse(); } [Fact] - public void should_not_have_warning_package_result() + public void Should_not_have_warning_package_result() { _packageResult.Warning.ShouldBeFalse(); } [Fact] - public void config_should_match_package_result_name() + public void Config_should_match_package_result_name() { _packageResult.Name.ShouldEqual(Configuration.PackageNames); } @@ -1252,77 +1286,77 @@ public void config_should_match_package_result_name() [Fact] [WindowsOnly] [Platform(Exclude = "Mono")] - public void should_have_executed_chocolateyBeforeModify_script() + public void Should_have_executed_chocolateyBeforeModify_script() { - MockLogger.contains_message("installpackage 1.0.0 Before Modification", LogLevel.Info).ShouldBeTrue(); + MockLogger.ContainsMessage("installpackage 1.0.0 Before Modification", LogLevel.Info).ShouldBeTrue(); } [Fact] [WindowsOnly] [Platform(Exclude = "Mono")] - public void should_have_executed_chocolateyUninstall_script() + public void Should_have_executed_chocolateyUninstall_script() { - MockLogger.contains_message("installpackage 1.0.0 Uninstalled", LogLevel.Info).ShouldBeTrue(); + MockLogger.ContainsMessage("installpackage 1.0.0 Uninstalled", LogLevel.Info).ShouldBeTrue(); } [Fact] [WindowsOnly] [Platform(Exclude = "Mono")] - public void should_have_executed_pre_all_hook_script() + public void Should_have_executed_pre_all_hook_script() { - MockLogger.contains_message("pre-uninstall-all.ps1 hook ran for installpackage 1.0.0", LogLevel.Info).ShouldBeTrue(); + MockLogger.ContainsMessage("pre-uninstall-all.ps1 hook ran for installpackage 1.0.0", LogLevel.Info).ShouldBeTrue(); } [Fact] [WindowsOnly] [Platform(Exclude = "Mono")] - public void should_have_executed_post_all_hook_script() + public void Should_have_executed_post_all_hook_script() { - MockLogger.contains_message("post-uninstall-all.ps1 hook ran for installpackage 1.0.0", LogLevel.Info).ShouldBeTrue(); + MockLogger.ContainsMessage("post-uninstall-all.ps1 hook ran for installpackage 1.0.0", LogLevel.Info).ShouldBeTrue(); } [Fact] [WindowsOnly] [Platform(Exclude = "Mono")] - public void should_have_executed_pre_installpackage_hook_script() + public void Should_have_executed_pre_installpackage_hook_script() { - MockLogger.contains_message("pre-uninstall-installpackage.ps1 hook ran for installpackage 1.0.0", LogLevel.Info).ShouldBeTrue(); + MockLogger.ContainsMessage("pre-uninstall-installpackage.ps1 hook ran for installpackage 1.0.0", LogLevel.Info).ShouldBeTrue(); } [Fact] [WindowsOnly] [Platform(Exclude = "Mono")] - public void should_have_executed_post_installpackage_hook_script() + public void Should_have_executed_post_installpackage_hook_script() { - MockLogger.contains_message("post-uninstall-installpackage.ps1 hook ran for installpackage 1.0.0", LogLevel.Info).ShouldBeTrue(); + MockLogger.ContainsMessage("post-uninstall-installpackage.ps1 hook ran for installpackage 1.0.0", LogLevel.Info).ShouldBeTrue(); } [Fact] [WindowsOnly] [Platform(Exclude = "Mono")] - public void should_not_have_executed_upgradepackage_hook_script() + public void Should_not_have_executed_upgradepackage_hook_script() { - MockLogger.contains_message("pre-uninstall-upgradepackage.ps1 hook ran for installpackage 1.0.0", LogLevel.Info).ShouldBeFalse(); + MockLogger.ContainsMessage("pre-uninstall-upgradepackage.ps1 hook ran for installpackage 1.0.0", LogLevel.Info).ShouldBeFalse(); } [Fact] [WindowsOnly] [Platform(Exclude = "Mono")] - public void should_have_executed_pre_beforemodify_hook_script() + public void Should_have_executed_pre_beforemodify_hook_script() { - MockLogger.contains_message("pre-beforemodify-all.ps1 hook ran for installpackage 1.0.0", LogLevel.Info).ShouldBeTrue(); + MockLogger.ContainsMessage("pre-beforemodify-all.ps1 hook ran for installpackage 1.0.0", LogLevel.Info).ShouldBeTrue(); } [Fact] [WindowsOnly] [Platform(Exclude = "Mono")] - public void should_have_executed_post_beforemodify_hook_script() + public void Should_have_executed_post_beforemodify_hook_script() { - MockLogger.contains_message("post-beforemodify-all.ps1 hook ran for installpackage 1.0.0", LogLevel.Info).ShouldBeTrue(); + MockLogger.ContainsMessage("post-beforemodify-all.ps1 hook ran for installpackage 1.0.0", LogLevel.Info).ShouldBeTrue(); } } - public class when_uninstalling_a_package_with_uppercase_id : ScenariosBase + public class When_uninstalling_a_package_with_uppercase_id : ScenariosBase { private PackageResult packageResult; @@ -1337,12 +1371,12 @@ public override void Context() public override void Because() { - Results = Service.uninstall_run(Configuration); + Results = Service.Uninstall(Configuration); packageResult = Results.FirstOrDefault().Value; } [Fact] - public void should_remove_the_package_from_the_lib_directory() + public void Should_remove_the_package_from_the_lib_directory() { var packageDir = Path.Combine(Scenario.get_top_level(), "lib", Configuration.PackageNames); @@ -1350,7 +1384,7 @@ public void should_remove_the_package_from_the_lib_directory() } [Fact] - public void should_delete_the_rollback() + public void Should_delete_the_rollback() { var packageDir = Path.Combine(Scenario.get_top_level(), "lib-bkp", Configuration.PackageNames); @@ -1358,10 +1392,10 @@ public void should_delete_the_rollback() } [Fact] - public void should_contain_a_warning_message_that_it_uninstalled_successfully() + public void Should_contain_a_warning_message_that_it_uninstalled_successfully() { bool installedSuccessfully = false; - foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).or_empty_list_if_null()) + foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).OrEmpty()) { if (message.Contains("1/1")) installedSuccessfully = true; } @@ -1370,25 +1404,25 @@ public void should_contain_a_warning_message_that_it_uninstalled_successfully() } [Fact] - public void should_have_a_successful_package_result() + public void Should_have_a_successful_package_result() { packageResult.Success.ShouldBeTrue(); } [Fact] - public void should_not_have_inconclusive_package_result() + public void Should_not_have_inconclusive_package_result() { packageResult.Inconclusive.ShouldBeFalse(); } [Fact] - public void should_not_have_warning_package_result() + public void Should_not_have_warning_package_result() { packageResult.Warning.ShouldBeFalse(); } [Fact] - public void config_should_match_package_result_name() + public void Config_should_match_package_result_name() { packageResult.Name.ShouldEqual(Configuration.PackageNames); } @@ -1396,21 +1430,21 @@ public void config_should_match_package_result_name() [Fact] [WindowsOnly] [Platform(Exclude = "Mono")] - public void should_have_executed_chocolateyBeforeModify_script() + public void Should_have_executed_chocolateyBeforeModify_script() { - MockLogger.contains_message("UpperCase 1.1.0 Before Modification", LogLevel.Info).ShouldBeTrue(); + MockLogger.ContainsMessage("UpperCase 1.1.0 Before Modification", LogLevel.Info).ShouldBeTrue(); } [Fact] [WindowsOnly] [Platform(Exclude = "Mono")] - public void should_have_executed_chocolateyUninstall_script() + public void Should_have_executed_chocolateyUninstall_script() { - MockLogger.contains_message("UpperCase 1.1.0 Uninstalled", LogLevel.Info).ShouldBeTrue(); + MockLogger.ContainsMessage("UpperCase 1.1.0 Uninstalled", LogLevel.Info).ShouldBeTrue(); } } - public class when_uninstalling_a_package_with_non_normalized_version : ScenariosBase + public class When_uninstalling_a_package_with_non_normalized_version : ScenariosBase { private PackageResult packageResult; @@ -1427,12 +1461,12 @@ public override void Context() public override void Because() { - Results = Service.uninstall_run(Configuration); + Results = Service.Uninstall(Configuration); packageResult = Results.FirstOrDefault().Value; } [Fact] - public void should_remove_the_package_from_the_lib_directory() + public void Should_remove_the_package_from_the_lib_directory() { var packageDir = Path.Combine(Scenario.get_top_level(), "lib", Configuration.PackageNames); @@ -1440,7 +1474,7 @@ public void should_remove_the_package_from_the_lib_directory() } [Fact] - public void should_delete_the_rollback() + public void Should_delete_the_rollback() { var packageDir = Path.Combine(Scenario.get_top_level(), "lib-bkp", Configuration.PackageNames); @@ -1450,7 +1484,7 @@ public void should_delete_the_rollback() [Fact] [WindowsOnly] [Platform(Exclude = "Mono")] - public void should_delete_a_shim_for_console_in_the_bin_directory() + public void Should_delete_a_shim_for_console_in_the_bin_directory() { var shimfile = Path.Combine(Scenario.get_top_level(), "bin", "console.exe"); @@ -1460,7 +1494,7 @@ public void should_delete_a_shim_for_console_in_the_bin_directory() [Fact] [WindowsOnly] [Platform(Exclude = "Mono")] - public void should_delete_a_shim_for_graphical_in_the_bin_directory() + public void Should_delete_a_shim_for_graphical_in_the_bin_directory() { var shimfile = Path.Combine(Scenario.get_top_level(), "bin", "graphical.exe"); @@ -1468,7 +1502,7 @@ public void should_delete_a_shim_for_graphical_in_the_bin_directory() } [Fact] - public void should_delete_any_files_created_during_the_install() + public void Should_delete_any_files_created_during_the_install() { var generatedFile = Path.Combine(Scenario.get_top_level(), "lib", Configuration.PackageNames, "simplefile.txt"); @@ -1476,10 +1510,10 @@ public void should_delete_any_files_created_during_the_install() } [Fact] - public void should_contain_a_warning_message_that_it_uninstalled_successfully() + public void Should_contain_a_warning_message_that_it_uninstalled_successfully() { bool installedSuccessfully = false; - foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).or_empty_list_if_null()) + foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).OrEmpty()) { if (message.Contains("1/1")) installedSuccessfully = true; } @@ -1488,25 +1522,25 @@ public void should_contain_a_warning_message_that_it_uninstalled_successfully() } [Fact] - public void should_have_a_successful_package_result() + public void Should_have_a_successful_package_result() { packageResult.Success.ShouldBeTrue(); } [Fact] - public void should_not_have_inconclusive_package_result() + public void Should_not_have_inconclusive_package_result() { packageResult.Inconclusive.ShouldBeFalse(); } [Fact] - public void should_not_have_warning_package_result() + public void Should_not_have_warning_package_result() { packageResult.Warning.ShouldBeFalse(); } [Fact] - public void config_should_match_package_result_name() + public void Config_should_match_package_result_name() { packageResult.Name.ShouldEqual(Configuration.PackageNames); } @@ -1514,31 +1548,31 @@ public void config_should_match_package_result_name() [Fact] [WindowsOnly] [Platform(Exclude = "Mono")] - public void should_have_executed_chocolateyBeforeModify_script() + public void Should_have_executed_chocolateyBeforeModify_script() { - MockLogger.contains_message("upgradepackage {0} Before Modification".format_with(NonNormalizedVersion), LogLevel.Info).ShouldBeTrue(); + MockLogger.ContainsMessage("upgradepackage {0} Before Modification".FormatWith(NonNormalizedVersion), LogLevel.Info).ShouldBeTrue(); } [Fact] [WindowsOnly] [Platform(Exclude = "Mono")] - public void should_have_executed_chocolateyUninstall_script() + public void Should_have_executed_chocolateyUninstall_script() { - MockLogger.contains_message("upgradepackage {0} Uninstalled".format_with(NonNormalizedVersion), LogLevel.Info).ShouldBeTrue(); + MockLogger.ContainsMessage("upgradepackage {0} Uninstalled".FormatWith(NonNormalizedVersion), LogLevel.Info).ShouldBeTrue(); } } - - public class when_uninstalling_a_package_with_remove_dependencies_with_beforeModify : ScenariosBase + + public class When_uninstalling_a_package_with_remove_dependencies_with_beforeModify : ScenariosBase { private const string TargetPackageName = "hasdependencywithbeforemodify"; private const string DependencyName = "isdependencywithbeforemodify"; - + public override void Context() { base.Context(); - Scenario.add_packages_to_source_location(Configuration, "{0}.*".format_with(TargetPackageName) + NuGetConstants.PackageExtension); - Scenario.add_packages_to_source_location(Configuration, "{0}.*".format_with(DependencyName) + NuGetConstants.PackageExtension); + Scenario.add_packages_to_source_location(Configuration, "{0}.*".FormatWith(TargetPackageName) + NuGetConstants.PackageExtension); + Scenario.add_packages_to_source_location(Configuration, "{0}.*".FormatWith(DependencyName) + NuGetConstants.PackageExtension); Scenario.install_package(Configuration, TargetPackageName, "1.0.0"); Scenario.install_package(Configuration, DependencyName, "1.0.0"); @@ -1548,47 +1582,47 @@ public override void Context() public override void Because() { - Results = Service.uninstall_run(Configuration); + Results = Service.Uninstall(Configuration); } [Fact] - public void should_uninstall_the_package() + public void Should_uninstall_the_package() { - var packageFile = Path.Combine(Scenario.get_top_level(), "lib", TargetPackageName, "{0}.nupkg".format_with(TargetPackageName)); + var packageFile = Path.Combine(Scenario.get_top_level(), "lib", TargetPackageName, "{0}.nupkg".FormatWith(TargetPackageName)); File.Exists(packageFile).ShouldBeFalse(); } [Fact] - public void should_uninstall_the_dependency() + public void Should_uninstall_the_dependency() { - var packageFile = Path.Combine(Scenario.get_top_level(), "lib", DependencyName, "{0}.nupkg".format_with(DependencyName)); + var packageFile = Path.Combine(Scenario.get_top_level(), "lib", DependencyName, "{0}.nupkg".FormatWith(DependencyName)); File.Exists(packageFile).ShouldBeFalse(); } [Fact] - public void should_contain_a_message_that_everything_uninstalled_successfully() + public void Should_contain_a_message_that_everything_uninstalled_successfully() { - MockLogger.contains_message("uninstalled 2/2", LogLevel.Warn).ShouldBeTrue(); + MockLogger.ContainsMessage("uninstalled 2/2", LogLevel.Warn).ShouldBeTrue(); } [Fact] [WindowsOnly] [Platform(Exclude = "Mono")] - public void should_run_target_package_beforeModify() + public void Should_run_target_package_beforeModify() { - MockLogger.contains_message("Ran BeforeModify: {0} {1}".format_with(TargetPackageName, "1.0.0"), LogLevel.Info).ShouldBeTrue(); + MockLogger.ContainsMessage("Ran BeforeModify: {0} {1}".FormatWith(TargetPackageName, "1.0.0"), LogLevel.Info).ShouldBeTrue(); } [Fact] [WindowsOnly] [Platform(Exclude = "Mono")] - public void should_run_dependency_package_beforeModify() + public void Should_run_dependency_package_beforeModify() { - MockLogger.contains_message("Ran BeforeModify: {0} {1}".format_with(DependencyName, "1.0.0"), LogLevel.Info).ShouldBeTrue(); + MockLogger.ContainsMessage("Ran BeforeModify: {0} {1}".FormatWith(DependencyName, "1.0.0"), LogLevel.Info).ShouldBeTrue(); } [Fact] - public void should_have_a_successful_package_result() + public void Should_have_a_successful_package_result() { foreach (var packageResult in Results) { @@ -1597,7 +1631,7 @@ public void should_have_a_successful_package_result() } [Fact] - public void should_not_have_inconclusive_package_result() + public void Should_not_have_inconclusive_package_result() { foreach (var packageResult in Results) { @@ -1606,7 +1640,7 @@ public void should_not_have_inconclusive_package_result() } [Fact] - public void should_not_have_warning_package_result() + public void Should_not_have_warning_package_result() { foreach (var packageResult in Results) { diff --git a/src/chocolatey.tests.integration/scenarios/UpgradeScenarios.cs b/src/chocolatey.tests.integration/scenarios/UpgradeScenarios.cs index 0eaab5708d..a33028e7d7 100644 --- a/src/chocolatey.tests.integration/scenarios/UpgradeScenarios.cs +++ b/src/chocolatey.tests.integration/scenarios/UpgradeScenarios.cs @@ -62,7 +62,7 @@ public override void Context() } } - public class when_noop_upgrading_a_package_that_has_available_upgrades : ScenariosBase + public class When_noop_upgrading_a_package_that_has_available_upgrades : ScenariosBase { public override void Context() { @@ -72,11 +72,11 @@ public override void Context() public override void Because() { - Service.upgrade_noop(Configuration); + Service.UpgradeDryRun(Configuration); } [Fact] - public void should_contain_older_version_in_directory() + public void Should_contain_older_version_in_directory() { var shimFile = Path.Combine(Scenario.get_top_level(), "lib", Configuration.PackageNames, "tools", "console.exe"); @@ -84,10 +84,10 @@ public void should_contain_older_version_in_directory() } [Fact] - public void should_contain_a_message_that_a_new_version_is_available() + public void Should_contain_a_message_that_a_new_version_is_available() { bool expectedMessage = false; - foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).or_empty_list_if_null()) + foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).OrEmpty()) { if (message.Contains("You have upgradepackage v1.0.0 installed. Version 1.1.0 is available based on your source(s)")) expectedMessage = true; } @@ -96,10 +96,10 @@ public void should_contain_a_message_that_a_new_version_is_available() } [Fact] - public void should_contain_a_message_that_a_package_can_be_upgraded() + public void Should_contain_a_message_that_a_package_can_be_upgraded() { bool expectedMessage = false; - foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).or_empty_list_if_null()) + foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).OrEmpty()) { if (message.Contains("can upgrade 1/1")) expectedMessage = true; } @@ -108,7 +108,7 @@ public void should_contain_a_message_that_a_package_can_be_upgraded() } [Fact] - public void should_not_create_a_rollback() + public void Should_not_create_a_rollback() { var packageDir = Path.Combine(Scenario.get_top_level(), "lib-bkp", Configuration.PackageNames); @@ -116,7 +116,7 @@ public void should_not_create_a_rollback() } } - public class when_noop_upgrading_a_package_that_does_not_have_available_upgrades : ScenariosBase + public class When_noop_upgrading_a_package_that_does_not_have_available_upgrades : ScenariosBase { public override void Context() { @@ -127,14 +127,14 @@ public override void Context() public override void Because() { - Service.upgrade_noop(Configuration); + Service.UpgradeDryRun(Configuration); } [Fact] - public void should_contain_a_message_that_you_have_the_latest_version_available() + public void Should_contain_a_message_that_you_have_the_latest_version_available() { bool expectedMessage = false; - foreach (var message in MockLogger.MessagesFor(LogLevel.Info).or_empty_list_if_null()) + foreach (var message in MockLogger.MessagesFor(LogLevel.Info).OrEmpty()) { if (message.Contains("installpackage v1.0.0 is the latest version available based on your source(s)")) expectedMessage = true; } @@ -143,10 +143,10 @@ public void should_contain_a_message_that_you_have_the_latest_version_available( } [Fact] - public void should_contain_a_message_that_no_packages_can_be_upgraded() + public void Should_contain_a_message_that_no_packages_can_be_upgraded() { bool expectedMessage = false; - foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).or_empty_list_if_null()) + foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).OrEmpty()) { if (message.Contains("can upgrade 0/1")) expectedMessage = true; } @@ -155,7 +155,7 @@ public void should_contain_a_message_that_no_packages_can_be_upgraded() } [Fact] - public void should_not_create_a_rollback() + public void Should_not_create_a_rollback() { var packageDir = Path.Combine(Scenario.get_top_level(), "lib-bkp", Configuration.PackageNames); @@ -163,7 +163,7 @@ public void should_not_create_a_rollback() } } - public class when_noop_upgrading_a_package_that_does_not_exist : ScenariosBase + public class When_noop_upgrading_a_package_that_does_not_exist : ScenariosBase { public override void Context() { @@ -174,14 +174,14 @@ public override void Context() public override void Because() { - Service.upgrade_noop(Configuration); + Service.UpgradeDryRun(Configuration); } [Fact] - public void should_contain_a_message_the_package_was_not_found() + public void Should_contain_a_message_the_package_was_not_found() { bool expectedMessage = false; - foreach (var message in MockLogger.MessagesFor(LogLevel.Error).or_empty_list_if_null()) + foreach (var message in MockLogger.MessagesFor(LogLevel.Error).OrEmpty()) { if (message.Contains("nonexistentpackage not installed. The package was not found with the source(s) listed")) expectedMessage = true; } @@ -190,10 +190,10 @@ public void should_contain_a_message_the_package_was_not_found() } [Fact] - public void should_contain_a_message_that_no_packages_can_be_upgraded() + public void Should_contain_a_message_that_no_packages_can_be_upgraded() { bool expectedMessage = false; - foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).or_empty_list_if_null()) + foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).OrEmpty()) { if (message.Contains("can upgrade 0/0")) expectedMessage = true; } @@ -202,24 +202,24 @@ public void should_contain_a_message_that_no_packages_can_be_upgraded() } } - public class when_upgrading_an_existing_package_happy_path : ScenariosBase + public class When_upgrading_an_existing_package_happy_path : ScenariosBase { private PackageResult _packageResult; public override void Because() { - Results = Service.upgrade_run(Configuration); + Results = Service.Upgrade(Configuration); _packageResult = Results.FirstOrDefault().Value; } [Fact] - public void should_upgrade_where_install_location_reports() + public void Should_upgrade_where_install_location_reports() { DirectoryAssert.Exists(_packageResult.InstallLocation); } [Fact] - public void should_upgrade_a_package_in_the_lib_directory() + public void Should_upgrade_a_package_in_the_lib_directory() { var packageDir = Path.Combine(Scenario.get_top_level(), "lib", Configuration.PackageNames); @@ -227,7 +227,7 @@ public void should_upgrade_a_package_in_the_lib_directory() } [Fact] - public void should_delete_the_rollback() + public void Should_delete_the_rollback() { var packageDir = Path.Combine(Scenario.get_top_level(), "lib-bkp", Configuration.PackageNames); @@ -235,7 +235,7 @@ public void should_delete_the_rollback() } [Fact] - public void should_contain_newer_version_in_directory() + public void Should_contain_newer_version_in_directory() { var shimFile = Path.Combine(Scenario.get_top_level(), "lib", Configuration.PackageNames, "tools", "console.exe"); @@ -243,20 +243,20 @@ public void should_contain_newer_version_in_directory() } [Fact] - public void should_upgrade_the_package() + public void Should_upgrade_the_package() { var packageFile = Path.Combine(Scenario.get_top_level(), "lib", Configuration.PackageNames, Configuration.PackageNames + NuGetConstants.PackageExtension); using (var packageReader = new PackageArchiveReader(packageFile)) { - packageReader.NuspecReader.GetVersion().to_string().ShouldEqual("1.1.0"); + packageReader.NuspecReader.GetVersion().ToStringSafe().ShouldEqual("1.1.0"); } } [Fact] - public void should_contain_a_warning_message_that_it_upgraded_successfully() + public void Should_contain_a_warning_message_that_it_upgraded_successfully() { bool upgradedSuccessMessage = false; - foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).or_empty_list_if_null()) + foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).OrEmpty()) { if (message.Contains("upgraded 1/1")) upgradedSuccessMessage = true; } @@ -265,10 +265,10 @@ public void should_contain_a_warning_message_that_it_upgraded_successfully() } [Fact] - public void should_contain_a_warning_message_with_old_and_new_versions() + public void Should_contain_a_warning_message_with_old_and_new_versions() { bool upgradeMessage = false; - foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).or_empty_list_if_null()) + foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).OrEmpty()) { if (message.Contains("You have upgradepackage v1.0.0 installed. Version 1.1.0 is available based on your source")) upgradeMessage = true; } @@ -277,31 +277,34 @@ public void should_contain_a_warning_message_with_old_and_new_versions() } [Fact] - public void should_have_a_successful_package_result() + public void Should_have_a_successful_package_result() { _packageResult.Success.ShouldBeTrue(); } [Fact] - public void should_not_have_inconclusive_package_result() + public void Should_not_have_inconclusive_package_result() { _packageResult.Inconclusive.ShouldBeFalse(); } [Fact] - public void should_not_have_warning_package_result() + public void Should_not_have_warning_package_result_other_than_before_modify_failures() { - _packageResult.Warning.ShouldBeFalse(); + // For before modify scripts that fail, we add a warning message. + // So we will ignore any such warnings. + var messages = _packageResult.Messages.Where(m => m.MessageType == ResultType.Warn && !m.Message.ContainsSafe("chocolateyBeforeModify")); + messages.ShouldBeEmpty(); } [Fact] - public void config_should_match_package_result_name() + public void Config_should_match_package_result_name() { _packageResult.Name.ShouldEqual(Configuration.PackageNames); } [Fact] - public void should_match_the_upgrade_version_of_one_dot_one_dot_zero() + public void Should_match_the_upgrade_version_of_one_dot_one_dot_zero() { _packageResult.Version.ShouldEqual("1.1.0"); } @@ -309,45 +312,45 @@ public void should_match_the_upgrade_version_of_one_dot_one_dot_zero() [Fact] [WindowsOnly] [Platform(Exclude = "Mono")] - public void should_have_executed_chocolateyBeforeModify_script_for_original_package() + public void Should_have_executed_chocolateyBeforeModify_script_for_original_package() { - MockLogger.contains_message("upgradepackage 1.0.0 Before Modification", LogLevel.Info).ShouldBeTrue(); + MockLogger.ContainsMessage("upgradepackage 1.0.0 Before Modification", LogLevel.Info).ShouldBeTrue(); } [Fact] [WindowsOnly] [Platform(Exclude = "Mono")] - public void should_have_executed_chocolateyBeforeModify_before_chocolateyInstall() + public void Should_have_executed_chocolateyBeforeModify_before_chocolateyInstall() { - MockLogger.MessagesFor(LogLevel.Info).or_empty_list_if_null() + MockLogger.MessagesFor(LogLevel.Info).OrEmpty() .SkipWhile(p => !p.Contains("upgradepackage 1.0.0 Before Modification")) .Any(p => p.EndsWith("upgradepackage 1.1.0 Installed")) .ShouldBeTrue(); } [Fact] - public void should_not_have_executed_chocolateyUninstall_script_for_original_package() + public void Should_not_have_executed_chocolateyUninstall_script_for_original_package() { - MockLogger.contains_message("upgradepackage 1.0.0 Uninstalled", LogLevel.Info).ShouldBeFalse(); + MockLogger.ContainsMessage("upgradepackage 1.0.0 Uninstalled", LogLevel.Info).ShouldBeFalse(); } [Fact] - public void should_not_have_executed_chocolateyBeforeModify_script_for_new_package() + public void Should_not_have_executed_chocolateyBeforeModify_script_for_new_package() { - MockLogger.contains_message("upgradepackage 1.1.0 Before Modification", LogLevel.Info).ShouldBeFalse(); + MockLogger.ContainsMessage("upgradepackage 1.1.0 Before Modification", LogLevel.Info).ShouldBeFalse(); } [Fact] [WindowsOnly] [Platform(Exclude = "Mono")] - public void should_have_executed_chocolateyInstall_script_for_new_package() + public void Should_have_executed_chocolateyInstall_script_for_new_package() { - MockLogger.contains_message("upgradepackage 1.1.0 Installed", LogLevel.Info).ShouldBeTrue(); + MockLogger.ContainsMessage("upgradepackage 1.1.0 Installed", LogLevel.Info).ShouldBeTrue(); } } [Categories.SourcePriority] - public class when_upgrading_an_existing_package_with_higher_version_in_non_prioritised_source : ScenariosBase + public class When_upgrading_an_existing_package_with_higher_version_in_non_prioritised_source : ScenariosBase { private PackageResult _packageResult; @@ -362,15 +365,15 @@ public override void Context() public override void Because() { - Results = Service.upgrade_run(Configuration); + Results = Service.Upgrade(Configuration); _packageResult = Results.Select(r => r.Value).FirstOrDefault(); } [Fact] - public void should_contain_a_message_that_you_have_the_latest_version_available() + public void Should_contain_a_message_that_you_have_the_latest_version_available() { bool expectedMessage = false; - foreach (var message in MockLogger.MessagesFor(LogLevel.Info).or_empty_list_if_null()) + foreach (var message in MockLogger.MessagesFor(LogLevel.Info).OrEmpty()) { if (message.Contains("upgradepackage v1.0.0 is the latest version available based on your source(s)")) expectedMessage = true; } @@ -379,10 +382,10 @@ public void should_contain_a_message_that_you_have_the_latest_version_available( } [Fact] - public void should_contain_a_message_that_no_packages_were_upgraded() + public void Should_contain_a_message_that_no_packages_were_upgraded() { bool expectedMessage = false; - foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).or_empty_list_if_null()) + foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).OrEmpty()) { if (message.Contains("upgraded 0/1 ")) expectedMessage = true; } @@ -391,7 +394,7 @@ public void should_contain_a_message_that_no_packages_were_upgraded() } [Fact] - public void should_not_create_a_rollback() + public void Should_not_create_a_rollback() { var packageDir = Path.Combine(Scenario.get_top_level(), "lib-bkp", Configuration.PackageNames); @@ -399,7 +402,7 @@ public void should_not_create_a_rollback() } [Fact] - public void should_not_remove_the_package_from_the_lib_directory() + public void Should_not_remove_the_package_from_the_lib_directory() { var packageDir = Path.Combine(Scenario.get_top_level(), "lib", Configuration.PackageNames); @@ -407,7 +410,7 @@ public void should_not_remove_the_package_from_the_lib_directory() } [Fact] - public void should_be_the_same_version_of_the_package() + public void Should_be_the_same_version_of_the_package() { var packageFolder = Path.Combine(Scenario.get_top_level(), "lib", Configuration.PackageNames, Configuration.PackageNames + NuGetConstants.PackageExtension); @@ -418,31 +421,31 @@ public void should_be_the_same_version_of_the_package() } [Fact] - public void should_have_a_successful_package_result() + public void Should_have_a_successful_package_result() { _packageResult.Success.ShouldBeTrue(); } [Fact] - public void should_have_inconclusive_package_result() + public void Should_have_inconclusive_package_result() { _packageResult.Inconclusive.ShouldBeTrue(); } [Fact] - public void should_not_have_warning_package_result() + public void Should_not_have_warning_package_result() { _packageResult.Warning.ShouldBeFalse(); } [Fact] - public void should_match_the_original_package_version() + public void Should_match_the_original_package_version() { _packageResult.Version.ShouldEqual("1.0.0"); } } - public class when_upgrading_an_existing_package_with_prerelease_available_without_prerelease_specified : ScenariosBase + public class When_upgrading_an_existing_package_with_prerelease_available_without_prerelease_specified : ScenariosBase { private PackageResult _packageResult; @@ -454,15 +457,15 @@ public override void Context() public override void Because() { - Results = Service.upgrade_run(Configuration); + Results = Service.Upgrade(Configuration); _packageResult = Results.FirstOrDefault().Value; } [Fact] - public void should_contain_a_message_that_you_have_the_latest_version_available() + public void Should_contain_a_message_that_you_have_the_latest_version_available() { bool expectedMessage = false; - foreach (var message in MockLogger.MessagesFor(LogLevel.Info).or_empty_list_if_null()) + foreach (var message in MockLogger.MessagesFor(LogLevel.Info).OrEmpty()) { if (message.Contains("upgradepackage v1.1.0 is the latest version available based on your source(s)")) expectedMessage = true; } @@ -471,10 +474,10 @@ public void should_contain_a_message_that_you_have_the_latest_version_available( } [Fact] - public void should_contain_a_message_that_no_packages_were_upgraded() + public void Should_contain_a_message_that_no_packages_were_upgraded() { bool expectedMessage = false; - foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).or_empty_list_if_null()) + foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).OrEmpty()) { if (message.Contains("upgraded 0/1 ")) expectedMessage = true; } @@ -483,7 +486,7 @@ public void should_contain_a_message_that_no_packages_were_upgraded() } [Fact] - public void should_not_create_a_rollback() + public void Should_not_create_a_rollback() { var packageDir = Path.Combine(Scenario.get_top_level(), "lib-bkp", Configuration.PackageNames); @@ -491,7 +494,7 @@ public void should_not_create_a_rollback() } [Fact] - public void should_not_remove_the_package_from_the_lib_directory() + public void Should_not_remove_the_package_from_the_lib_directory() { var packageDir = Path.Combine(Scenario.get_top_level(), "lib", Configuration.PackageNames); @@ -499,41 +502,41 @@ public void should_not_remove_the_package_from_the_lib_directory() } [Fact] - public void should_be_the_same_version_of_the_package() + public void Should_be_the_same_version_of_the_package() { var packageFile = Path.Combine(Scenario.get_top_level(), "lib", Configuration.PackageNames, Configuration.PackageNames + NuGetConstants.PackageExtension); using (var packageReader = new PackageArchiveReader(packageFile)) { - packageReader.NuspecReader.GetVersion().to_string().ShouldEqual("1.1.0"); + packageReader.NuspecReader.GetVersion().ToStringSafe().ShouldEqual("1.1.0"); } } [Fact] - public void should_have_a_successful_package_result() + public void Should_have_a_successful_package_result() { _packageResult.Success.ShouldBeTrue(); } [Fact] - public void should_have_inconclusive_package_result() + public void Should_have_inconclusive_package_result() { _packageResult.Inconclusive.ShouldBeTrue(); } [Fact] - public void should_not_have_warning_package_result() + public void Should_not_have_warning_package_result() { _packageResult.Warning.ShouldBeFalse(); } [Fact] - public void should_match_the_original_package_version() + public void Should_match_the_original_package_version() { _packageResult.Version.ShouldEqual("1.1.0"); } } - public class when_upgrading_an_existing_package_with_prerelease_available_and_prerelease_specified : ScenariosBase + public class When_upgrading_an_existing_package_with_prerelease_available_and_prerelease_specified : ScenariosBase { private PackageResult _packageResult; @@ -545,18 +548,18 @@ public override void Context() public override void Because() { - Results = Service.upgrade_run(Configuration); + Results = Service.Upgrade(Configuration); _packageResult = Results.FirstOrDefault().Value; } [Fact] - public void should_upgrade_where_install_location_reports() + public void Should_upgrade_where_install_location_reports() { DirectoryAssert.Exists(_packageResult.InstallLocation); } [Fact] - public void should_upgrade_a_package_in_the_lib_directory() + public void Should_upgrade_a_package_in_the_lib_directory() { var packageDir = Path.Combine(Scenario.get_top_level(), "lib", Configuration.PackageNames); @@ -564,7 +567,7 @@ public void should_upgrade_a_package_in_the_lib_directory() } [Fact] - public void should_delete_the_rollback() + public void Should_delete_the_rollback() { var packageDir = Path.Combine(Scenario.get_top_level(), "lib-bkp", Configuration.PackageNames); @@ -572,7 +575,7 @@ public void should_delete_the_rollback() } [Fact] - public void should_contain_newer_version_in_directory() + public void Should_contain_newer_version_in_directory() { var shimFile = Path.Combine(Scenario.get_top_level(), "lib", Configuration.PackageNames, "tools", "console.exe"); @@ -580,23 +583,23 @@ public void should_contain_newer_version_in_directory() } [Fact] - public void should_upgrade_the_package() + public void Should_upgrade_the_package() { var packageFile = Path.Combine(Scenario.get_top_level(), "lib", Configuration.PackageNames, Configuration.PackageNames + NuGetConstants.PackageExtension); using (var packageReader = new PackageArchiveReader(packageFile)) { var version = packageReader.NuspecReader.GetVersion(); - version.Version.to_string().ShouldEqual("1.1.1.0"); - version.OriginalVersion.to_string().ShouldEqual("1.1.1-beta2"); + version.Version.ToStringSafe().ShouldEqual("1.1.1.0"); + version.OriginalVersion.ToStringSafe().ShouldEqual("1.1.1-beta2"); version.ToString().ShouldEqual("1.1.1-beta2"); } } [Fact] - public void should_contain_a_warning_message_that_it_upgraded_successfully() + public void Should_contain_a_warning_message_that_it_upgraded_successfully() { bool upgradedSuccessMessage = false; - foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).or_empty_list_if_null()) + foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).OrEmpty()) { if (message.Contains("upgraded 1/1")) upgradedSuccessMessage = true; } @@ -605,10 +608,10 @@ public void should_contain_a_warning_message_that_it_upgraded_successfully() } [Fact] - public void should_contain_a_warning_message_with_old_and_new_versions() + public void Should_contain_a_warning_message_with_old_and_new_versions() { bool upgradeMessage = false; - foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).or_empty_list_if_null()) + foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).OrEmpty()) { if (message.Contains("You have upgradepackage v1.0.0 installed. Version 1.1.1-beta2 is available based on your source")) upgradeMessage = true; } @@ -617,31 +620,34 @@ public void should_contain_a_warning_message_with_old_and_new_versions() } [Fact] - public void should_have_a_successful_package_result() + public void Should_have_a_successful_package_result() { _packageResult.Success.ShouldBeTrue(); } [Fact] - public void should_not_have_inconclusive_package_result() + public void Should_not_have_inconclusive_package_result() { _packageResult.Inconclusive.ShouldBeFalse(); } [Fact] - public void should_not_have_warning_package_result() + public void Should_not_have_warning_package_result_other_than_before_modify_failures() { - _packageResult.Warning.ShouldBeFalse(); + // For before modify scripts that fail, we add a warning message. + // So we will ignore any such warnings. + var messages = _packageResult.Messages.Where(m => m.MessageType == ResultType.Warn && !m.Message.ContainsSafe("chocolateyBeforeModify")); + messages.ShouldBeEmpty(); } [Fact] - public void config_should_match_package_result_name() + public void Config_should_match_package_result_name() { _packageResult.Name.ShouldEqual(Configuration.PackageNames); } [Fact] - public void should_match_the_upgrade_version_of_the_new_beta() + public void Should_match_the_upgrade_version_of_the_new_beta() { _packageResult.Version.ShouldEqual("1.1.1-beta2"); } @@ -649,45 +655,45 @@ public void should_match_the_upgrade_version_of_the_new_beta() [Fact] [WindowsOnly] [Platform(Exclude = "Mono")] - public void should_have_executed_chocolateyBeforeModify_script_for_original_package() + public void Should_have_executed_chocolateyBeforeModify_script_for_original_package() { - MockLogger.contains_message("upgradepackage 1.0.0 Before Modification", LogLevel.Info).ShouldBeTrue(); + MockLogger.ContainsMessage("upgradepackage 1.0.0 Before Modification", LogLevel.Info).ShouldBeTrue(); } [Fact] [WindowsOnly] [Platform(Exclude = "Mono")] - public void should_have_executed_chocolateyBeforeModify_before_chocolateyInstall() + public void Should_have_executed_chocolateyBeforeModify_before_chocolateyInstall() { - MockLogger.MessagesFor(LogLevel.Info).or_empty_list_if_null() + MockLogger.MessagesFor(LogLevel.Info).OrEmpty() .SkipWhile(p => !p.Contains("upgradepackage 1.0.0 Before Modification")) .Any(p => p.EndsWith("upgradepackage 1.1.1-beta2 Installed")) .ShouldBeTrue(); } [Fact] - public void should_not_have_executed_chocolateyUninstall_script_for_original_package() + public void Should_not_have_executed_chocolateyUninstall_script_for_original_package() { - MockLogger.contains_message("upgradepackage 1.0.0 Uninstalled", LogLevel.Info).ShouldBeFalse(); + MockLogger.ContainsMessage("upgradepackage 1.0.0 Uninstalled", LogLevel.Info).ShouldBeFalse(); } [Fact] - public void should_not_have_executed_chocolateyBeforeModify_script_for_new_package() + public void Should_not_have_executed_chocolateyBeforeModify_script_for_new_package() { - MockLogger.contains_message("upgradepackage 1.1.1-beta2 Before Modification", LogLevel.Info).ShouldBeFalse(); + MockLogger.ContainsMessage("upgradepackage 1.1.1-beta2 Before Modification", LogLevel.Info).ShouldBeFalse(); } [Fact] [WindowsOnly] [Platform(Exclude = "Mono")] - public void should_have_executed_chocolateyInstall_script_for_new_package() + public void Should_have_executed_chocolateyInstall_script_for_new_package() { - MockLogger.contains_message("upgradepackage 1.1.1-beta2 Installed", LogLevel.Info).ShouldBeTrue(); + MockLogger.ContainsMessage("upgradepackage 1.1.1-beta2 Installed", LogLevel.Info).ShouldBeTrue(); } } [Categories.SemVer20] - public class when_upgrading_an_existing_package_with_semver_2_0_prerelease_available_and_prerelease_specified : ScenariosBase + public class When_upgrading_an_existing_package_with_semver_2_0_prerelease_available_and_prerelease_specified : ScenariosBase { private PackageResult _packageResult; @@ -700,18 +706,18 @@ public override void Context() public override void Because() { - Results = Service.upgrade_run(Configuration); + Results = Service.Upgrade(Configuration); _packageResult = Results.FirstOrDefault().Value; } [Fact] - public void should_upgrade_where_install_location_reports() + public void Should_upgrade_where_install_location_reports() { DirectoryAssert.Exists(_packageResult.InstallLocation); } [Fact] - public void should_upgrade_a_package_in_the_lib_directory() + public void Should_upgrade_a_package_in_the_lib_directory() { var packageDir = Path.Combine(Scenario.get_top_level(), "lib", Configuration.PackageNames); @@ -719,7 +725,7 @@ public void should_upgrade_a_package_in_the_lib_directory() } [Fact] - public void should_delete_the_rollback() + public void Should_delete_the_rollback() { var packageDir = Path.Combine(Scenario.get_top_level(), "lib-bkp", Configuration.PackageNames); @@ -727,7 +733,7 @@ public void should_delete_the_rollback() } [Fact] - public void should_contain_newer_version_in_directory() + public void Should_contain_newer_version_in_directory() { var shimFile = Path.Combine(Scenario.get_top_level(), "lib", Configuration.PackageNames, "tools", "console.exe"); @@ -735,23 +741,23 @@ public void should_contain_newer_version_in_directory() } [Fact] - public void should_upgrade_the_package() + public void Should_upgrade_the_package() { var packageFile = Path.Combine(Scenario.get_top_level(), "lib", Configuration.PackageNames, Configuration.PackageNames + NuGetConstants.PackageExtension); using (var packageReader = new PackageArchiveReader(packageFile)) { var version = packageReader.NuspecReader.GetVersion(); - version.Version.to_string().ShouldEqual("1.1.1.0"); - version.OriginalVersion.to_string().ShouldEqual("1.1.1-beta.1"); + version.Version.ToStringSafe().ShouldEqual("1.1.1.0"); + version.OriginalVersion.ToStringSafe().ShouldEqual("1.1.1-beta.1"); version.ToString().ShouldEqual("1.1.1-beta.1"); } } [Fact] - public void should_contain_a_warning_message_that_it_upgraded_successfully() + public void Should_contain_a_warning_message_that_it_upgraded_successfully() { bool upgradedSuccessMessage = false; - foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).or_empty_list_if_null()) + foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).OrEmpty()) { if (message.Contains("upgraded 1/1")) upgradedSuccessMessage = true; } @@ -760,10 +766,10 @@ public void should_contain_a_warning_message_that_it_upgraded_successfully() } [Fact] - public void should_contain_a_warning_message_with_old_and_new_versions() + public void Should_contain_a_warning_message_with_old_and_new_versions() { bool upgradeMessage = false; - foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).or_empty_list_if_null()) + foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).OrEmpty()) { if (message.Contains("You have upgradepackage v1.0.0 installed. Version 1.1.1-beta.1 is available based on your source")) upgradeMessage = true; } @@ -772,31 +778,34 @@ public void should_contain_a_warning_message_with_old_and_new_versions() } [Fact] - public void should_have_a_successful_package_result() + public void Should_have_a_successful_package_result() { _packageResult.Success.ShouldBeTrue(); } [Fact] - public void should_not_have_inconclusive_package_result() + public void Should_not_have_inconclusive_package_result() { _packageResult.Inconclusive.ShouldBeFalse(); } [Fact] - public void should_not_have_warning_package_result() + public void Should_not_have_warning_package_result_other_than_before_modify_failures() { - _packageResult.Warning.ShouldBeFalse(); + // For before modify scripts that fail, we add a warning message. + // So we will ignore any such warnings. + var messages = _packageResult.Messages.Where(m => m.MessageType == ResultType.Warn && !m.Message.ContainsSafe("chocolateyBeforeModify")); + messages.ShouldBeEmpty(); } [Fact] - public void config_should_match_package_result_name() + public void Config_should_match_package_result_name() { _packageResult.Name.ShouldEqual(Configuration.PackageNames); } [Fact] - public void should_match_the_upgrade_version_of_the_new_beta() + public void Should_match_the_upgrade_version_of_the_new_beta() { _packageResult.Version.ShouldEqual("1.1.1-beta.1"); } @@ -804,44 +813,44 @@ public void should_match_the_upgrade_version_of_the_new_beta() [Fact] [WindowsOnly] [Platform(Exclude = "Mono")] - public void should_have_executed_chocolateyBeforeModify_script_for_original_package() + public void Should_have_executed_chocolateyBeforeModify_script_for_original_package() { - MockLogger.contains_message("upgradepackage 1.0.0 Before Modification", LogLevel.Info).ShouldBeTrue(); + MockLogger.ContainsMessage("upgradepackage 1.0.0 Before Modification", LogLevel.Info).ShouldBeTrue(); } [Fact] [WindowsOnly] [Platform(Exclude = "Mono")] - public void should_have_executed_chocolateyBeforeModify_before_chocolateyInstall() + public void Should_have_executed_chocolateyBeforeModify_before_chocolateyInstall() { - MockLogger.MessagesFor(LogLevel.Info).or_empty_list_if_null() + MockLogger.MessagesFor(LogLevel.Info).OrEmpty() .SkipWhile(p => !p.Contains("upgradepackage 1.0.0 Before Modification")) .Any(p => p.EndsWith("upgradepackage 1.1.1-beta.1 Installed")) .ShouldBeTrue(); } [Fact] - public void should_not_have_executed_chocolateyUninstall_script_for_original_package() + public void Should_not_have_executed_chocolateyUninstall_script_for_original_package() { - MockLogger.contains_message("upgradepackage 1.0.0 Uninstalled", LogLevel.Info).ShouldBeFalse(); + MockLogger.ContainsMessage("upgradepackage 1.0.0 Uninstalled", LogLevel.Info).ShouldBeFalse(); } [Fact] - public void should_not_have_executed_chocolateyBeforeModify_script_for_new_package() + public void Should_not_have_executed_chocolateyBeforeModify_script_for_new_package() { - MockLogger.contains_message("upgradepackage 1.1.1-beta.1 Before Modification", LogLevel.Info).ShouldBeFalse(); + MockLogger.ContainsMessage("upgradepackage 1.1.1-beta.1 Before Modification", LogLevel.Info).ShouldBeFalse(); } [Fact] [WindowsOnly] [Platform(Exclude = "Mono")] - public void should_have_executed_chocolateyInstall_script_for_new_package() + public void Should_have_executed_chocolateyInstall_script_for_new_package() { - MockLogger.contains_message("upgradepackage 1.1.1-beta.1 Installed", LogLevel.Info).ShouldBeTrue(); + MockLogger.ContainsMessage("upgradepackage 1.1.1-beta.1 Installed", LogLevel.Info).ShouldBeTrue(); } } - public class when_upgrading_an_existing_prerelease_package_without_prerelease_specified : ScenariosBase + public class When_upgrading_an_existing_prerelease_package_without_prerelease_specified : ScenariosBase { private PackageResult _packageResult; @@ -855,18 +864,18 @@ public override void Context() public override void Because() { - Results = Service.upgrade_run(Configuration); + Results = Service.Upgrade(Configuration); _packageResult = Results.FirstOrDefault().Value; } [Fact] - public void should_upgrade_where_install_location_reports() + public void Should_upgrade_where_install_location_reports() { DirectoryAssert.Exists(_packageResult.InstallLocation); } [Fact] - public void should_upgrade_a_package_in_the_lib_directory() + public void Should_upgrade_a_package_in_the_lib_directory() { var packageDir = Path.Combine(Scenario.get_top_level(), "lib", Configuration.PackageNames); @@ -874,7 +883,7 @@ public void should_upgrade_a_package_in_the_lib_directory() } [Fact] - public void should_delete_the_rollback() + public void Should_delete_the_rollback() { var packageDir = Path.Combine(Scenario.get_top_level(), "lib-bkp", Configuration.PackageNames); @@ -882,7 +891,7 @@ public void should_delete_the_rollback() } [Fact] - public void should_contain_newer_version_in_directory() + public void Should_contain_newer_version_in_directory() { var shimFile = Path.Combine(Scenario.get_top_level(), "lib", Configuration.PackageNames, "tools", "console.exe"); @@ -890,24 +899,24 @@ public void should_contain_newer_version_in_directory() } [Fact] - public void should_upgrade_the_package() + public void Should_upgrade_the_package() { var packageFile = Path.Combine(Scenario.get_top_level(), "lib", Configuration.PackageNames, Configuration.PackageNames + NuGetConstants.PackageExtension); using (var packageReader = new PackageArchiveReader(packageFile)) { var version = packageReader.NuspecReader.GetVersion(); - version.Version.to_string().ShouldEqual("1.1.1.0"); - version.OriginalVersion.to_string().ShouldEqual("1.1.1-beta2"); - version.to_string().ShouldEqual("1.1.1-beta2"); + version.Version.ToStringSafe().ShouldEqual("1.1.1.0"); + version.OriginalVersion.ToStringSafe().ShouldEqual("1.1.1-beta2"); + version.ToStringSafe().ShouldEqual("1.1.1-beta2"); } } [Fact] - public void should_contain_a_warning_message_that_it_upgraded_successfully() + public void Should_contain_a_warning_message_that_it_upgraded_successfully() { bool upgradedSuccessMessage = false; - foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).or_empty_list_if_null()) + foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).OrEmpty()) { if (message.Contains("upgraded 1/1")) upgradedSuccessMessage = true; } @@ -916,10 +925,10 @@ public void should_contain_a_warning_message_that_it_upgraded_successfully() } [Fact] - public void should_contain_a_warning_message_with_old_and_new_versions() + public void Should_contain_a_warning_message_with_old_and_new_versions() { bool upgradeMessage = false; - foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).or_empty_list_if_null()) + foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).OrEmpty()) { if (message.Contains("You have upgradepackage v1.1.1-beta installed. Version 1.1.1-beta2 is available based on your source")) upgradeMessage = true; } @@ -928,31 +937,31 @@ public void should_contain_a_warning_message_with_old_and_new_versions() } [Fact] - public void should_have_a_successful_package_result() + public void Should_have_a_successful_package_result() { _packageResult.Success.ShouldBeTrue(); } [Fact] - public void should_not_have_inconclusive_package_result() + public void Should_not_have_inconclusive_package_result() { _packageResult.Inconclusive.ShouldBeFalse(); } [Fact] - public void should_not_have_warning_package_result() + public void Should_not_have_warning_package_result() { _packageResult.Warning.ShouldBeFalse(); } [Fact] - public void config_should_match_package_result_name() + public void Config_should_match_package_result_name() { _packageResult.Name.ShouldEqual(Configuration.PackageNames); } [Fact] - public void should_match_the_upgrade_version_of_the_new_beta() + public void Should_match_the_upgrade_version_of_the_new_beta() { _packageResult.Version.ShouldEqual("1.1.1-beta2"); } @@ -960,45 +969,45 @@ public void should_match_the_upgrade_version_of_the_new_beta() [Fact] [WindowsOnly] [Platform(Exclude = "Mono")] - public void should_have_executed_chocolateyBeforeModify_script_for_original_package() + public void Should_have_executed_chocolateyBeforeModify_script_for_original_package() { - MockLogger.contains_message("upgradepackage 1.1.1-beta Before Modification", LogLevel.Info).ShouldBeTrue(); + MockLogger.ContainsMessage("upgradepackage 1.1.1-beta Before Modification", LogLevel.Info).ShouldBeTrue(); } [Fact] [WindowsOnly] [Platform(Exclude = "Mono")] - public void should_have_executed_chocolateyBeforeModify_before_chocolateyInstall() + public void Should_have_executed_chocolateyBeforeModify_before_chocolateyInstall() { - MockLogger.MessagesFor(LogLevel.Info).or_empty_list_if_null() + MockLogger.MessagesFor(LogLevel.Info).OrEmpty() .SkipWhile(p => !p.Contains("upgradepackage 1.1.1-beta Before Modification")) .Any(p => p.EndsWith("upgradepackage 1.1.1-beta2 Installed")) .ShouldBeTrue(); } [Fact] - public void should_not_have_executed_chocolateyUninstall_script_for_original_package() + public void Should_not_have_executed_chocolateyUninstall_script_for_original_package() { - MockLogger.contains_message("upgradepackage 1.1.1-beta Uninstalled", LogLevel.Info).ShouldBeFalse(); + MockLogger.ContainsMessage("upgradepackage 1.1.1-beta Uninstalled", LogLevel.Info).ShouldBeFalse(); } [Fact] - public void should_not_have_executed_chocolateyBeforeModify_script_for_new_package() + public void Should_not_have_executed_chocolateyBeforeModify_script_for_new_package() { - MockLogger.contains_message("upgradepackage 1.1.1-beta2 Before Modification", LogLevel.Info).ShouldBeFalse(); + MockLogger.ContainsMessage("upgradepackage 1.1.1-beta2 Before Modification", LogLevel.Info).ShouldBeFalse(); } [Fact] [WindowsOnly] [Platform(Exclude = "Mono")] - public void should_have_executed_chocolateyInstall_script_for_new_package() + public void Should_have_executed_chocolateyInstall_script_for_new_package() { - MockLogger.contains_message("upgradepackage 1.1.1-beta2 Installed", LogLevel.Info).ShouldBeTrue(); + MockLogger.ContainsMessage("upgradepackage 1.1.1-beta2 Installed", LogLevel.Info).ShouldBeTrue(); } } [Categories.SemVer20] - public class when_upgrading_an_existing_prerelease_package_to_semver_2_0_without_prerelease_specified : ScenariosBase + public class When_upgrading_an_existing_prerelease_package_to_semver_2_0_without_prerelease_specified : ScenariosBase { private PackageResult _packageResult; @@ -1013,18 +1022,18 @@ public override void Context() public override void Because() { - Results = Service.upgrade_run(Configuration); + Results = Service.Upgrade(Configuration); _packageResult = Results.FirstOrDefault().Value; } [Fact] - public void should_upgrade_where_install_location_reports() + public void Should_upgrade_where_install_location_reports() { DirectoryAssert.Exists(_packageResult.InstallLocation); } [Fact] - public void should_upgrade_a_package_in_the_lib_directory() + public void Should_upgrade_a_package_in_the_lib_directory() { var packageDir = Path.Combine(Scenario.get_top_level(), "lib", Configuration.PackageNames); @@ -1032,7 +1041,7 @@ public void should_upgrade_a_package_in_the_lib_directory() } [Fact] - public void should_delete_the_rollback() + public void Should_delete_the_rollback() { var packageDir = Path.Combine(Scenario.get_top_level(), "lib-bkp", Configuration.PackageNames); @@ -1040,7 +1049,7 @@ public void should_delete_the_rollback() } [Fact] - public void should_contain_newer_version_in_directory() + public void Should_contain_newer_version_in_directory() { var shimFile = Path.Combine(Scenario.get_top_level(), "lib", Configuration.PackageNames, "tools", "console.exe"); @@ -1048,24 +1057,24 @@ public void should_contain_newer_version_in_directory() } [Fact] - public void should_upgrade_the_package() + public void Should_upgrade_the_package() { var packageFile = Path.Combine(Scenario.get_top_level(), "lib", Configuration.PackageNames, Configuration.PackageNames + NuGetConstants.PackageExtension); using (var packageReader = new PackageArchiveReader(packageFile)) { var version = packageReader.NuspecReader.GetVersion(); - version.Version.to_string().ShouldEqual("1.1.1.0"); - version.OriginalVersion.to_string().ShouldEqual("1.1.1-beta.1"); - version.to_string().ShouldEqual("1.1.1-beta.1"); + version.Version.ToStringSafe().ShouldEqual("1.1.1.0"); + version.OriginalVersion.ToStringSafe().ShouldEqual("1.1.1-beta.1"); + version.ToStringSafe().ShouldEqual("1.1.1-beta.1"); } } [Fact] - public void should_contain_a_warning_message_that_it_upgraded_successfully() + public void Should_contain_a_warning_message_that_it_upgraded_successfully() { bool upgradedSuccessMessage = false; - foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).or_empty_list_if_null()) + foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).OrEmpty()) { if (message.Contains("upgraded 1/1")) upgradedSuccessMessage = true; } @@ -1074,10 +1083,10 @@ public void should_contain_a_warning_message_that_it_upgraded_successfully() } [Fact] - public void should_contain_a_warning_message_with_old_and_new_versions() + public void Should_contain_a_warning_message_with_old_and_new_versions() { bool upgradeMessage = false; - foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).or_empty_list_if_null()) + foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).OrEmpty()) { if (message.Contains("You have upgradepackage v1.1.1-beta installed. Version 1.1.1-beta.1 is available based on your source")) upgradeMessage = true; } @@ -1086,31 +1095,31 @@ public void should_contain_a_warning_message_with_old_and_new_versions() } [Fact] - public void should_have_a_successful_package_result() + public void Should_have_a_successful_package_result() { _packageResult.Success.ShouldBeTrue(); } [Fact] - public void should_not_have_inconclusive_package_result() + public void Should_not_have_inconclusive_package_result() { _packageResult.Inconclusive.ShouldBeFalse(); } [Fact] - public void should_not_have_warning_package_result() + public void Should_not_have_warning_package_result() { _packageResult.Warning.ShouldBeFalse(); } [Fact] - public void config_should_match_package_result_name() + public void Config_should_match_package_result_name() { _packageResult.Name.ShouldEqual(Configuration.PackageNames); } [Fact] - public void should_match_the_upgrade_version_of_the_new_beta() + public void Should_match_the_upgrade_version_of_the_new_beta() { _packageResult.Version.ShouldEqual("1.1.1-beta.1"); } @@ -1118,45 +1127,45 @@ public void should_match_the_upgrade_version_of_the_new_beta() [Fact] [WindowsOnly] [Platform(Exclude = "Mono")] - public void should_have_executed_chocolateyBeforeModify_script_for_original_package() + public void Should_have_executed_chocolateyBeforeModify_script_for_original_package() { - MockLogger.contains_message("upgradepackage 1.1.1-beta Before Modification", LogLevel.Info).ShouldBeTrue(); + MockLogger.ContainsMessage("upgradepackage 1.1.1-beta Before Modification", LogLevel.Info).ShouldBeTrue(); } [Fact] [WindowsOnly] [Platform(Exclude = "Mono")] - public void should_have_executed_chocolateyBeforeModify_before_chocolateyInstall() + public void Should_have_executed_chocolateyBeforeModify_before_chocolateyInstall() { - MockLogger.MessagesFor(LogLevel.Info).or_empty_list_if_null() + MockLogger.MessagesFor(LogLevel.Info).OrEmpty() .SkipWhile(p => !p.Contains("upgradepackage 1.1.1-beta Before Modification")) .Any(p => p.EndsWith("upgradepackage 1.1.1-beta.1 Installed")) .ShouldBeTrue(); } [Fact] - public void should_not_have_executed_chocolateyUninstall_script_for_original_package() + public void Should_not_have_executed_chocolateyUninstall_script_for_original_package() { - MockLogger.contains_message("upgradepackage 1.1.1-beta Uninstalled", LogLevel.Info).ShouldBeFalse(); + MockLogger.ContainsMessage("upgradepackage 1.1.1-beta Uninstalled", LogLevel.Info).ShouldBeFalse(); } [Fact] - public void should_not_have_executed_chocolateyBeforeModify_script_for_new_package() + public void Should_not_have_executed_chocolateyBeforeModify_script_for_new_package() { - MockLogger.contains_message("upgradepackage 1.1.1-beta.1 Before Modification", LogLevel.Info).ShouldBeFalse(); + MockLogger.ContainsMessage("upgradepackage 1.1.1-beta.1 Before Modification", LogLevel.Info).ShouldBeFalse(); } [Fact] [WindowsOnly] [Platform(Exclude = "Mono")] - public void should_have_executed_chocolateyInstall_script_for_new_package() + public void Should_have_executed_chocolateyInstall_script_for_new_package() { - MockLogger.contains_message("upgradepackage 1.1.1-beta.1 Installed", LogLevel.Info).ShouldBeTrue(); + MockLogger.ContainsMessage("upgradepackage 1.1.1-beta.1 Installed", LogLevel.Info).ShouldBeTrue(); } } [Categories.SemVer20] - public class when_upgrading_an_existing_semver_2_0_prerelease_package_to_legacy_semver_without_prerelease_specified : ScenariosBase + public class When_upgrading_an_existing_semver_2_0_prerelease_package_to_legacy_semver_without_prerelease_specified : ScenariosBase { private PackageResult _packageResult; @@ -1170,18 +1179,18 @@ public override void Context() public override void Because() { - Results = Service.upgrade_run(Configuration); + Results = Service.Upgrade(Configuration); _packageResult = Results.FirstOrDefault().Value; } [Fact] - public void should_upgrade_where_install_location_reports() + public void Should_upgrade_where_install_location_reports() { DirectoryAssert.Exists(_packageResult.InstallLocation); } [Fact] - public void should_upgrade_a_package_in_the_lib_directory() + public void Should_upgrade_a_package_in_the_lib_directory() { var packageDir = Path.Combine(Scenario.get_top_level(), "lib", Configuration.PackageNames); @@ -1189,7 +1198,7 @@ public void should_upgrade_a_package_in_the_lib_directory() } [Fact] - public void should_delete_the_rollback() + public void Should_delete_the_rollback() { var packageDir = Path.Combine(Scenario.get_top_level(), "lib-bkp", Configuration.PackageNames); @@ -1197,7 +1206,7 @@ public void should_delete_the_rollback() } [Fact] - public void should_contain_newer_version_in_directory() + public void Should_contain_newer_version_in_directory() { var shimFile = Path.Combine(Scenario.get_top_level(), "lib", Configuration.PackageNames, "tools", "console.exe"); @@ -1205,24 +1214,24 @@ public void should_contain_newer_version_in_directory() } [Fact] - public void should_upgrade_the_package() + public void Should_upgrade_the_package() { var packageFile = Path.Combine(Scenario.get_top_level(), "lib", Configuration.PackageNames, Configuration.PackageNames + NuGetConstants.PackageExtension); using (var packageReader = new PackageArchiveReader(packageFile)) { var version = packageReader.NuspecReader.GetVersion(); - version.Version.to_string().ShouldEqual("1.1.1.0"); - version.OriginalVersion.to_string().ShouldEqual("1.1.1-beta2"); - version.to_string().ShouldEqual("1.1.1-beta2"); + version.Version.ToStringSafe().ShouldEqual("1.1.1.0"); + version.OriginalVersion.ToStringSafe().ShouldEqual("1.1.1-beta2"); + version.ToStringSafe().ShouldEqual("1.1.1-beta2"); } } [Fact] - public void should_contain_a_warning_message_that_it_upgraded_successfully() + public void Should_contain_a_warning_message_that_it_upgraded_successfully() { bool upgradedSuccessMessage = false; - foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).or_empty_list_if_null()) + foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).OrEmpty()) { if (message.Contains("upgraded 1/1")) upgradedSuccessMessage = true; } @@ -1231,10 +1240,10 @@ public void should_contain_a_warning_message_that_it_upgraded_successfully() } [Fact] - public void should_contain_a_warning_message_with_old_and_new_versions() + public void Should_contain_a_warning_message_with_old_and_new_versions() { bool upgradeMessage = false; - foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).or_empty_list_if_null()) + foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).OrEmpty()) { if (message.Contains("You have upgradepackage v1.1.1-beta.1 installed. Version 1.1.1-beta2 is available based on your source")) upgradeMessage = true; } @@ -1243,31 +1252,31 @@ public void should_contain_a_warning_message_with_old_and_new_versions() } [Fact] - public void should_have_a_successful_package_result() + public void Should_have_a_successful_package_result() { _packageResult.Success.ShouldBeTrue(); } [Fact] - public void should_not_have_inconclusive_package_result() + public void Should_not_have_inconclusive_package_result() { _packageResult.Inconclusive.ShouldBeFalse(); } [Fact] - public void should_not_have_warning_package_result() + public void Should_not_have_warning_package_result() { _packageResult.Warning.ShouldBeFalse(); } [Fact] - public void config_should_match_package_result_name() + public void Config_should_match_package_result_name() { _packageResult.Name.ShouldEqual(Configuration.PackageNames); } [Fact] - public void should_match_the_upgrade_version_of_the_new_beta() + public void Should_match_the_upgrade_version_of_the_new_beta() { _packageResult.Version.ShouldEqual("1.1.1-beta2"); } @@ -1275,44 +1284,44 @@ public void should_match_the_upgrade_version_of_the_new_beta() [Fact] [WindowsOnly] [Platform(Exclude = "Mono")] - public void should_have_executed_chocolateyBeforeModify_script_for_original_package() + public void Should_have_executed_chocolateyBeforeModify_script_for_original_package() { - MockLogger.contains_message("upgradepackage 1.1.1-beta.1 Before Modification", LogLevel.Info).ShouldBeTrue(); + MockLogger.ContainsMessage("upgradepackage 1.1.1-beta.1 Before Modification", LogLevel.Info).ShouldBeTrue(); } [Fact] [WindowsOnly] [Platform(Exclude = "Mono")] - public void should_have_executed_chocolateyBeforeModify_before_chocolateyInstall() + public void Should_have_executed_chocolateyBeforeModify_before_chocolateyInstall() { - MockLogger.MessagesFor(LogLevel.Info).or_empty_list_if_null() + MockLogger.MessagesFor(LogLevel.Info).OrEmpty() .SkipWhile(p => !p.Contains("upgradepackage 1.1.1-beta.1 Before Modification")) .Any(p => p.EndsWith("upgradepackage 1.1.1-beta2 Installed")) .ShouldBeTrue(); } [Fact] - public void should_not_have_executed_chocolateyUninstall_script_for_original_package() + public void Should_not_have_executed_chocolateyUninstall_script_for_original_package() { - MockLogger.contains_message("upgradepackage 1.1.1-beta.1 Uninstalled", LogLevel.Info).ShouldBeFalse(); + MockLogger.ContainsMessage("upgradepackage 1.1.1-beta.1 Uninstalled", LogLevel.Info).ShouldBeFalse(); } [Fact] - public void should_not_have_executed_chocolateyBeforeModify_script_for_new_package() + public void Should_not_have_executed_chocolateyBeforeModify_script_for_new_package() { - MockLogger.contains_message("upgradepackage 1.1.1-beta2 Before Modification", LogLevel.Info).ShouldBeFalse(); + MockLogger.ContainsMessage("upgradepackage 1.1.1-beta2 Before Modification", LogLevel.Info).ShouldBeFalse(); } [Fact] [WindowsOnly] [Platform(Exclude = "Mono")] - public void should_have_executed_chocolateyInstall_script_for_new_package() + public void Should_have_executed_chocolateyInstall_script_for_new_package() { - MockLogger.contains_message("upgradepackage 1.1.1-beta2 Installed", LogLevel.Info).ShouldBeTrue(); + MockLogger.ContainsMessage("upgradepackage 1.1.1-beta2 Installed", LogLevel.Info).ShouldBeTrue(); } } - public class when_upgrading_an_existing_prerelease_package_with_prerelease_available_with_excludeprerelease_and_without_prerelease_specified : ScenariosBase + public class When_upgrading_an_existing_prerelease_package_with_prerelease_available_with_excludeprerelease_and_without_prerelease_specified : ScenariosBase { private PackageResult _packageResult; @@ -1327,15 +1336,15 @@ public override void Context() public override void Because() { - Results = Service.upgrade_run(Configuration); + Results = Service.Upgrade(Configuration); _packageResult = Results.FirstOrDefault().Value; } [Fact] - public void should_contain_a_message_that_you_have_the_latest_version_available() + public void Should_contain_a_message_that_you_have_the_latest_version_available() { bool expectedMessage = false; - foreach (var message in MockLogger.MessagesFor(LogLevel.Info).or_empty_list_if_null()) + foreach (var message in MockLogger.MessagesFor(LogLevel.Info).OrEmpty()) { if (message.Contains("upgradepackage v1.1.1-beta is newer")) expectedMessage = true; } @@ -1344,10 +1353,10 @@ public void should_contain_a_message_that_you_have_the_latest_version_available( } [Fact] - public void should_contain_a_message_that_no_packages_were_upgraded() + public void Should_contain_a_message_that_no_packages_were_upgraded() { bool expectedMessage = false; - foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).or_empty_list_if_null()) + foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).OrEmpty()) { if (message.Contains("upgraded 0/1 ")) expectedMessage = true; } @@ -1356,7 +1365,7 @@ public void should_contain_a_message_that_no_packages_were_upgraded() } [Fact] - public void should_not_create_a_rollback() + public void Should_not_create_a_rollback() { var packageDir = Path.Combine(Scenario.get_top_level(), "lib-bkp", Configuration.PackageNames); @@ -1364,7 +1373,7 @@ public void should_not_create_a_rollback() } [Fact] - public void should_not_remove_the_package_from_the_lib_directory() + public void Should_not_remove_the_package_from_the_lib_directory() { var packageDir = Path.Combine(Scenario.get_top_level(), "lib", Configuration.PackageNames); @@ -1372,44 +1381,44 @@ public void should_not_remove_the_package_from_the_lib_directory() } [Fact] - public void should_be_the_same_version_of_the_package() + public void Should_be_the_same_version_of_the_package() { var packageFile = Path.Combine(Scenario.get_top_level(), "lib", Configuration.PackageNames, Configuration.PackageNames + NuGetConstants.PackageExtension); using (var packageReader = new PackageArchiveReader(packageFile)) { var version = packageReader.NuspecReader.GetVersion(); - version.Version.to_string().ShouldEqual("1.1.1.0"); + version.Version.ToStringSafe().ShouldEqual("1.1.1.0"); version.OriginalVersion.ShouldEqual("1.1.1-beta"); - version.to_string().ShouldEqual("1.1.1-beta"); + version.ToStringSafe().ShouldEqual("1.1.1-beta"); } } [Fact] - public void should_have_a_successful_package_result() + public void Should_have_a_successful_package_result() { _packageResult.Success.ShouldBeTrue(); } [Fact] - public void should_have_inconclusive_package_result() + public void Should_have_inconclusive_package_result() { _packageResult.Inconclusive.ShouldBeTrue(); } [Fact] - public void should_not_have_warning_package_result() + public void Should_not_have_warning_package_result() { _packageResult.Warning.ShouldBeFalse(); } [Fact] - public void should_only_find_the_last_stable_version() + public void Should_only_find_the_last_stable_version() { _packageResult.Version.ShouldEqual("1.1.0"); } } - public class when_upgrading_an_existing_prerelease_package_with_allow_downgrade_with_excludeprerelease_and_without_prerelease_specified : ScenariosBase + public class When_upgrading_an_existing_prerelease_package_with_allow_downgrade_with_excludeprerelease_and_without_prerelease_specified : ScenariosBase { private PackageResult _packageResult; @@ -1425,15 +1434,15 @@ public override void Context() public override void Because() { - Results = Service.upgrade_run(Configuration); + Results = Service.Upgrade(Configuration); _packageResult = Results.FirstOrDefault().Value; } [Fact] - public void should_contain_a_message_that_you_have_the_latest_version_available() + public void Should_contain_a_message_that_you_have_the_latest_version_available() { bool expectedMessage = false; - foreach (var message in MockLogger.MessagesFor(LogLevel.Info).or_empty_list_if_null()) + foreach (var message in MockLogger.MessagesFor(LogLevel.Info).OrEmpty()) { if (message.Contains("upgradepackage v1.1.1-beta is newer")) expectedMessage = true; } @@ -1442,10 +1451,10 @@ public void should_contain_a_message_that_you_have_the_latest_version_available( } [Fact] - public void should_contain_a_message_that_no_packages_were_upgraded() + public void Should_contain_a_message_that_no_packages_were_upgraded() { bool expectedMessage = false; - foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).or_empty_list_if_null()) + foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).OrEmpty()) { if (message.Contains("upgraded 0/1 ")) expectedMessage = true; } @@ -1454,7 +1463,7 @@ public void should_contain_a_message_that_no_packages_were_upgraded() } [Fact] - public void should_not_create_a_rollback() + public void Should_not_create_a_rollback() { var packageDir = Path.Combine(Scenario.get_top_level(), "lib-bkp", Configuration.PackageNames); @@ -1462,7 +1471,7 @@ public void should_not_create_a_rollback() } [Fact] - public void should_not_remove_the_package_from_the_lib_directory() + public void Should_not_remove_the_package_from_the_lib_directory() { var packageDir = Path.Combine(Scenario.get_top_level(), "lib", Configuration.PackageNames); @@ -1470,44 +1479,44 @@ public void should_not_remove_the_package_from_the_lib_directory() } [Fact] - public void should_be_the_same_version_of_the_package() + public void Should_be_the_same_version_of_the_package() { var packageFile = Path.Combine(Scenario.get_top_level(), "lib", Configuration.PackageNames, Configuration.PackageNames + NuGetConstants.PackageExtension); using (var packageReader = new PackageArchiveReader(packageFile)) { var version = packageReader.NuspecReader.GetVersion(); - version.Version.to_string().ShouldEqual("1.1.1.0"); + version.Version.ToStringSafe().ShouldEqual("1.1.1.0"); version.OriginalVersion.ShouldEqual("1.1.1-beta"); - version.to_string().ShouldEqual("1.1.1-beta"); + version.ToStringSafe().ShouldEqual("1.1.1-beta"); } } [Fact] - public void should_have_a_successful_package_result() + public void Should_have_a_successful_package_result() { _packageResult.Success.ShouldBeTrue(); } [Fact] - public void should_have_inconclusive_package_result() + public void Should_have_inconclusive_package_result() { _packageResult.Inconclusive.ShouldBeTrue(); } [Fact] - public void should_not_have_warning_package_result() + public void Should_not_have_warning_package_result() { _packageResult.Warning.ShouldBeFalse(); } [Fact] - public void should_only_find_the_last_stable_version() + public void Should_only_find_the_last_stable_version() { _packageResult.Version.ShouldEqual("1.1.0"); } } - public class when_force_upgrading_a_package : ScenariosBase + public class When_force_upgrading_a_package : ScenariosBase { private PackageResult _packageResult; @@ -1519,18 +1528,18 @@ public override void Context() public override void Because() { - Results = Service.upgrade_run(Configuration); + Results = Service.Upgrade(Configuration); _packageResult = Results.FirstOrDefault().Value; } [Fact] - public void should_upgrade_where_install_location_reports() + public void Should_upgrade_where_install_location_reports() { DirectoryAssert.Exists(_packageResult.InstallLocation); } [Fact] - public void should_upgrade_a_package_in_the_lib_directory() + public void Should_upgrade_a_package_in_the_lib_directory() { var packageDir = Path.Combine(Scenario.get_top_level(), "lib", Configuration.PackageNames); @@ -1538,17 +1547,17 @@ public void should_upgrade_a_package_in_the_lib_directory() } [Fact] - public void should_upgrade_the_package() + public void Should_upgrade_the_package() { var packageFile = Path.Combine(Scenario.get_top_level(), "lib", Configuration.PackageNames, Configuration.PackageNames + NuGetConstants.PackageExtension); using (var packageReader = new PackageArchiveReader(packageFile)) { - packageReader.NuspecReader.GetVersion().to_string().ShouldEqual("1.1.0"); + packageReader.NuspecReader.GetVersion().ToStringSafe().ShouldEqual("1.1.0"); } } [Fact] - public void should_delete_the_rollback() + public void Should_delete_the_rollback() { var packageDir = Path.Combine(Scenario.get_top_level(), "lib-bkp", Configuration.PackageNames); @@ -1556,7 +1565,7 @@ public void should_delete_the_rollback() } [Fact] - public void should_contain_newer_version_in_directory() + public void Should_contain_newer_version_in_directory() { var shimFile = Path.Combine(Scenario.get_top_level(), "lib", Configuration.PackageNames, "tools", "console.exe"); @@ -1564,10 +1573,10 @@ public void should_contain_newer_version_in_directory() } [Fact] - public void should_contain_a_warning_message_that_it_upgraded_successfully() + public void Should_contain_a_warning_message_that_it_upgraded_successfully() { bool upgradedSuccessMessage = false; - foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).or_empty_list_if_null()) + foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).OrEmpty()) { if (message.Contains("upgraded 1/1")) upgradedSuccessMessage = true; } @@ -1576,10 +1585,10 @@ public void should_contain_a_warning_message_that_it_upgraded_successfully() } [Fact] - public void should_contain_a_warning_message_with_old_and_new_versions() + public void Should_contain_a_warning_message_with_old_and_new_versions() { bool upgradeMessage = false; - foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).or_empty_list_if_null()) + foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).OrEmpty()) { if (message.Contains("You have upgradepackage v1.0.0 installed. Version 1.1.0 is available based on your source")) upgradeMessage = true; } @@ -1588,37 +1597,40 @@ public void should_contain_a_warning_message_with_old_and_new_versions() } [Fact] - public void should_have_a_successful_package_result() + public void Should_have_a_successful_package_result() { _packageResult.Success.ShouldBeTrue(); } [Fact] - public void should_not_have_inconclusive_package_result() + public void Should_not_have_inconclusive_package_result() { _packageResult.Inconclusive.ShouldBeFalse(); } [Fact] - public void should_not_have_warning_package_result() + public void Should_not_have_warning_package_result_other_than_before_modify_failures() { - _packageResult.Warning.ShouldBeFalse(); + // For before modify scripts that fail, we add a warning message. + // So we will ignore any such warnings. + var messages = _packageResult.Messages.Where(m => m.MessageType == ResultType.Warn && !m.Message.ContainsSafe("chocolateyBeforeModify")); + messages.ShouldBeEmpty(); } [Fact] - public void config_should_match_package_result_name() + public void Config_should_match_package_result_name() { _packageResult.Name.ShouldEqual(Configuration.PackageNames); } [Fact] - public void should_match_the_upgrade_version_of_one_dot_one_dot_zero() + public void Should_match_the_upgrade_version_of_one_dot_one_dot_zero() { _packageResult.Version.ShouldEqual("1.1.0"); } } - public class when_upgrading_a_package_that_does_not_have_available_upgrades : ScenariosBase + public class When_upgrading_a_package_that_does_not_have_available_upgrades : ScenariosBase { private PackageResult _packageResult; @@ -1630,15 +1642,15 @@ public override void Context() public override void Because() { - Results = Service.upgrade_run(Configuration); + Results = Service.Upgrade(Configuration); _packageResult = Results.FirstOrDefault().Value; } [Fact] - public void should_contain_a_message_that_you_have_the_latest_version_available() + public void Should_contain_a_message_that_you_have_the_latest_version_available() { bool expectedMessage = false; - foreach (var message in MockLogger.MessagesFor(LogLevel.Info).or_empty_list_if_null()) + foreach (var message in MockLogger.MessagesFor(LogLevel.Info).OrEmpty()) { if (message.Contains("installpackage v1.0.0 is the latest version available based on your source(s)")) expectedMessage = true; } @@ -1647,10 +1659,10 @@ public void should_contain_a_message_that_you_have_the_latest_version_available( } [Fact] - public void should_contain_a_message_that_no_packages_were_upgraded() + public void Should_contain_a_message_that_no_packages_were_upgraded() { bool expectedMessage = false; - foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).or_empty_list_if_null()) + foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).OrEmpty()) { if (message.Contains("upgraded 0/1 ")) expectedMessage = true; } @@ -1659,7 +1671,7 @@ public void should_contain_a_message_that_no_packages_were_upgraded() } [Fact] - public void should_not_create_a_rollback() + public void Should_not_create_a_rollback() { var packageDir = Path.Combine(Scenario.get_top_level(), "lib-bkp", Configuration.PackageNames); @@ -1667,7 +1679,7 @@ public void should_not_create_a_rollback() } [Fact] - public void should_not_remove_the_package_from_the_lib_directory() + public void Should_not_remove_the_package_from_the_lib_directory() { var packageDir = Path.Combine(Scenario.get_top_level(), "lib", Configuration.PackageNames); @@ -1675,41 +1687,41 @@ public void should_not_remove_the_package_from_the_lib_directory() } [Fact] - public void should_be_the_same_version_of_the_package() + public void Should_be_the_same_version_of_the_package() { var packageFile = Path.Combine(Scenario.get_top_level(), "lib", Configuration.PackageNames, Configuration.PackageNames + NuGetConstants.PackageExtension); using (var packageReader = new PackageArchiveReader(packageFile)) { - packageReader.NuspecReader.GetVersion().to_string().ShouldEqual("1.0.0"); + packageReader.NuspecReader.GetVersion().ToStringSafe().ShouldEqual("1.0.0"); } } [Fact] - public void should_have_a_successful_package_result() + public void Should_have_a_successful_package_result() { _packageResult.Success.ShouldBeTrue(); } [Fact] - public void should_have_inconclusive_package_result() + public void Should_have_inconclusive_package_result() { _packageResult.Inconclusive.ShouldBeTrue(); } [Fact] - public void should_not_have_warning_package_result() + public void Should_not_have_warning_package_result() { _packageResult.Warning.ShouldBeFalse(); } [Fact] - public void should_match_the_existing_version_of_one_dot_zero_dot_zero() + public void Should_match_the_existing_version_of_one_dot_zero_dot_zero() { _packageResult.Version.ShouldEqual("1.0.0"); } } - public class when_force_upgrading_a_package_that_does_not_have_available_upgrades : ScenariosBase + public class When_force_upgrading_a_package_that_does_not_have_available_upgrades : ScenariosBase { private PackageResult _packageResult; @@ -1722,15 +1734,15 @@ public override void Context() public override void Because() { - Results = Service.upgrade_run(Configuration); + Results = Service.Upgrade(Configuration); _packageResult = Results.FirstOrDefault().Value; } [Fact] - public void should_contain_a_message_that_you_have_the_latest_version_available() + public void Should_contain_a_message_that_you_have_the_latest_version_available() { bool expectedMessage = false; - foreach (var message in MockLogger.MessagesFor(LogLevel.Info).or_empty_list_if_null()) + foreach (var message in MockLogger.MessagesFor(LogLevel.Info).OrEmpty()) { if (message.Contains("installpackage v1.0.0 is the latest version available based on your source(s)")) expectedMessage = true; } @@ -1739,10 +1751,10 @@ public void should_contain_a_message_that_you_have_the_latest_version_available( } [Fact] - public void should_contain_a_message_that_the_package_was_upgraded() + public void Should_contain_a_message_that_the_package_was_upgraded() { bool expectedMessage = false; - foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).or_empty_list_if_null()) + foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).OrEmpty()) { if (message.Contains("upgraded 1/1")) expectedMessage = true; } @@ -1751,7 +1763,7 @@ public void should_contain_a_message_that_the_package_was_upgraded() } [Fact] - public void should_not_create_a_rollback() + public void Should_not_create_a_rollback() { var packageDir = Path.Combine(Scenario.get_top_level(), "lib-bkp", Configuration.PackageNames); @@ -1759,7 +1771,7 @@ public void should_not_create_a_rollback() } [Fact] - public void should_not_remove_the_package_from_the_lib_directory() + public void Should_not_remove_the_package_from_the_lib_directory() { var packageDir = Path.Combine(Scenario.get_top_level(), "lib", Configuration.PackageNames); @@ -1767,46 +1779,46 @@ public void should_not_remove_the_package_from_the_lib_directory() } [Fact] - public void should_be_the_same_version_of_the_package() + public void Should_be_the_same_version_of_the_package() { var packageFile = Path.Combine(Scenario.get_top_level(), "lib", Configuration.PackageNames, Configuration.PackageNames + NuGetConstants.PackageExtension); using (var packageReader = new PackageArchiveReader(packageFile)) { - packageReader.NuspecReader.GetVersion().to_string().ShouldEqual("1.0.0"); + packageReader.NuspecReader.GetVersion().ToStringSafe().ShouldEqual("1.0.0"); } } [Fact] - public void should_have_a_successful_package_result() + public void Should_have_a_successful_package_result() { _packageResult.Success.ShouldBeTrue(); } [Fact] - public void should_not_have_inconclusive_package_result() + public void Should_not_have_inconclusive_package_result() { _packageResult.Inconclusive.ShouldBeFalse(); } [Fact] - public void should_not_have_warning_package_result() + public void Should_not_have_warning_package_result() { _packageResult.Warning.ShouldBeFalse(); } [Fact] - public void should_match_the_existing_version_of_one_dot_zero_dot_zero() + public void Should_match_the_existing_version_of_one_dot_zero_dot_zero() { _packageResult.Version.ShouldEqual("1.0.0"); } } - public class when_upgrading_packages_with_packages_config : ScenariosBase + public class When_upgrading_packages_with_packages_config : ScenariosBase { public override void Context() { base.Context(); - var packagesConfig = "{0}{1}context{1}testing.packages.config".format_with(Scenario.get_top_level(), Path.DirectorySeparatorChar); + var packagesConfig = "{0}{1}context{1}testing.packages.config".FormatWith(Scenario.get_top_level(), Path.DirectorySeparatorChar); Configuration.PackageNames = Configuration.Input = packagesConfig; } @@ -1815,9 +1827,9 @@ public override void Because() } [Fact] - public void should_throw_an_error_that_it_is_not_allowed() + public void Should_throw_an_error_that_it_is_not_allowed() { - Action m = () => Service.upgrade_run(Configuration); + Action m = () => Service.Upgrade(Configuration); m.ShouldThrow(); } @@ -1825,7 +1837,7 @@ public void should_throw_an_error_that_it_is_not_allowed() [WindowsOnly] [Platform(Exclude = "Mono")] - public class when_upgrading_a_package_with_readonly_files : ScenariosBase + public class When_upgrading_a_package_with_readonly_files : ScenariosBase { private PackageResult _packageResult; @@ -1834,23 +1846,23 @@ public override void Context() base.Context(); var fileToSetReadOnly = Path.Combine(Scenario.get_top_level(), "lib", Configuration.PackageNames, "tools", "chocolateyInstall.ps1"); var fileSystem = new DotNetFileSystem(); - fileSystem.ensure_file_attribute_set(fileToSetReadOnly, FileAttributes.ReadOnly); + fileSystem.EnsureFileAttributeSet(fileToSetReadOnly, FileAttributes.ReadOnly); } public override void Because() { - Results = Service.upgrade_run(Configuration); + Results = Service.Upgrade(Configuration); _packageResult = Results.FirstOrDefault().Value; } [Fact] - public void should_upgrade_where_install_location_reports() + public void Should_upgrade_where_install_location_reports() { DirectoryAssert.Exists(_packageResult.InstallLocation); } [Fact] - public void should_upgrade_a_package_in_the_lib_directory() + public void Should_upgrade_a_package_in_the_lib_directory() { var packageDir = Path.Combine(Scenario.get_top_level(), "lib", Configuration.PackageNames); @@ -1858,17 +1870,17 @@ public void should_upgrade_a_package_in_the_lib_directory() } [Fact] - public void should_upgrade_the_package() + public void Should_upgrade_the_package() { var packageFile = Path.Combine(Scenario.get_top_level(), "lib", Configuration.PackageNames, Configuration.PackageNames + NuGetConstants.PackageExtension); using (var packageReader = new PackageArchiveReader(packageFile)) { - packageReader.NuspecReader.GetVersion().to_string().ShouldEqual("1.1.0"); + packageReader.NuspecReader.GetVersion().ToStringSafe().ShouldEqual("1.1.0"); } } [Fact] - public void should_delete_the_rollback() + public void Should_delete_the_rollback() { var packageDir = Path.Combine(Scenario.get_top_level(), "lib-bkp", Configuration.PackageNames); @@ -1876,7 +1888,7 @@ public void should_delete_the_rollback() } [Fact] - public void should_contain_newer_version_in_directory() + public void Should_contain_newer_version_in_directory() { var shimFile = Path.Combine(Scenario.get_top_level(), "lib", Configuration.PackageNames, "tools", "console.exe"); @@ -1884,10 +1896,10 @@ public void should_contain_newer_version_in_directory() } [Fact] - public void should_contain_a_warning_message_that_it_upgraded_successfully() + public void Should_contain_a_warning_message_that_it_upgraded_successfully() { bool upgradedSuccessMessage = false; - foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).or_empty_list_if_null()) + foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).OrEmpty()) { if (message.Contains("upgraded 1/1")) upgradedSuccessMessage = true; } @@ -1896,10 +1908,10 @@ public void should_contain_a_warning_message_that_it_upgraded_successfully() } [Fact] - public void should_contain_a_warning_message_with_old_and_new_versions() + public void Should_contain_a_warning_message_with_old_and_new_versions() { bool upgradeMessage = false; - foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).or_empty_list_if_null()) + foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).OrEmpty()) { if (message.Contains("You have upgradepackage v1.0.0 installed. Version 1.1.0 is available based on your source")) upgradeMessage = true; } @@ -1908,60 +1920,63 @@ public void should_contain_a_warning_message_with_old_and_new_versions() } [Fact] - public void should_have_a_successful_package_result() + public void Should_have_a_successful_package_result() { _packageResult.Success.ShouldBeTrue(); } [Fact] - public void should_not_have_inconclusive_package_result() + public void Should_not_have_inconclusive_package_result() { _packageResult.Inconclusive.ShouldBeFalse(); } [Fact] - public void should_not_have_warning_package_result() + public void Should_not_have_warning_package_result_other_than_before_modify_failures() { - _packageResult.Warning.ShouldBeFalse(); + // For before modify scripts that fail, we add a warning message. + // So we will ignore any such warnings. + var messages = _packageResult.Messages.Where(m => m.MessageType == ResultType.Warn && !m.Message.ContainsSafe("chocolateyBeforeModify")); + messages.ShouldBeEmpty(); } } [WindowsOnly] [Platform(Exclude = "Mono")] - public class when_upgrading_a_package_with_a_read_and_delete_share_locked_file : ScenariosBase + public class When_upgrading_a_package_with_a_read_and_delete_share_locked_file : ScenariosBase { private PackageResult _packageResult; - private FileStream fileStream; + private FileStream _fileStream; public override void Context() { base.Context(); var fileToOpen = Path.Combine(Scenario.get_top_level(), "lib", Configuration.PackageNames, "tools", "chocolateyInstall.ps1"); - fileStream = new FileStream(fileToOpen, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.Read | FileShare.Delete); + _fileStream = new FileStream(fileToOpen, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.Read | FileShare.Delete); } public override void AfterObservations() { base.AfterObservations(); - fileStream.Close(); - fileStream.Dispose(); + _fileStream.Close(); + _fileStream.Dispose(); } public override void Because() { - Results = Service.upgrade_run(Configuration); + Results = Service.Upgrade(Configuration); _packageResult = Results.FirstOrDefault().Value; } [Fact] - public void should_upgrade_where_install_location_reports() + public void Should_upgrade_where_install_location_reports() { DirectoryAssert.Exists(_packageResult.InstallLocation); } [Fact] - public void should_upgrade_a_package_in_the_lib_directory() + public void Should_upgrade_a_package_in_the_lib_directory() { var packageDir = Path.Combine(Scenario.get_top_level(), "lib", Configuration.PackageNames); @@ -1969,19 +1984,29 @@ public void should_upgrade_a_package_in_the_lib_directory() } [Fact] - public void should_upgrade_the_package() + public void Should_upgrade_the_package() { var packageFile = Path.Combine(Scenario.get_top_level(), "lib", Configuration.PackageNames, Configuration.PackageNames + NuGetConstants.PackageExtension); using (var packageReader = new PackageArchiveReader(packageFile)) { - packageReader.NuspecReader.GetVersion().to_string().ShouldEqual("1.1.0"); + packageReader.NuspecReader.GetVersion().ToStringSafe().ShouldEqual("1.1.0"); } } - [Fact] - [Pending("Does not work under .Net 4.8, See issue #2690")] - [Broken] - public void should_not_be_able_delete_the_rollback() + // Locking is inconsistent between client and server operating systems in .NET 4.8. + // On a server, if a file is Read and delete locked it can't be deleted, but on client systems it can. + [Fact, Platform(Exclude = "WindowsServer10")] + public void Should_have_deleted_the_rollback() + { + var packageDir = Path.Combine(Scenario.get_top_level(), "lib-bkp", Configuration.PackageNames); + + DirectoryAssert.DoesNotExist(packageDir); + } + + // Locking is inconsistent between client and server operating systems in .NET 4.8. + // On a server, if a file is Read and delete locked it can't be deleted, but on client systems it can. + [Fact, Platform("WindowsServer10")] + public void Should_not_have_deleted_the_rollback_on_server() { var packageDir = Path.Combine(Scenario.get_top_level(), "lib-bkp", Configuration.PackageNames); @@ -1989,7 +2014,7 @@ public void should_not_be_able_delete_the_rollback() } [Fact] - public void should_contain_newer_version_in_directory() + public void Should_contain_newer_version_in_directory() { var shimFile = Path.Combine(Scenario.get_top_level(), "lib", Configuration.PackageNames, "tools", "console.exe"); @@ -1997,10 +2022,10 @@ public void should_contain_newer_version_in_directory() } [Fact] - public void should_contain_a_warning_message_that_it_upgraded_successfully() + public void Should_contain_a_warning_message_that_it_upgraded_successfully() { bool upgradedSuccessMessage = false; - foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).or_empty_list_if_null()) + foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).OrEmpty()) { if (message.Contains("upgraded 1/1")) upgradedSuccessMessage = true; } @@ -2009,10 +2034,10 @@ public void should_contain_a_warning_message_that_it_upgraded_successfully() } [Fact] - public void should_contain_a_warning_message_with_old_and_new_versions() + public void Should_contain_a_warning_message_with_old_and_new_versions() { bool upgradeMessage = false; - foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).or_empty_list_if_null()) + foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).OrEmpty()) { if (message.Contains("You have upgradepackage v1.0.0 installed. Version 1.1.0 is available based on your source")) upgradeMessage = true; } @@ -2021,54 +2046,57 @@ public void should_contain_a_warning_message_with_old_and_new_versions() } [Fact] - public void should_have_a_successful_package_result() + public void Should_have_a_successful_package_result() { _packageResult.Success.ShouldBeTrue(); } [Fact] - public void should_not_have_inconclusive_package_result() + public void Should_not_have_inconclusive_package_result() { _packageResult.Inconclusive.ShouldBeFalse(); } [Fact] - public void should_not_have_warning_package_result() + public void Should_not_have_warning_package_result_other_than_before_modify_failures() { - _packageResult.Warning.ShouldBeFalse(); + // For before modify scripts that fail, we add a warning message. + // So we will ignore any such warnings. + var messages = _packageResult.Messages.Where(m => m.MessageType == ResultType.Warn && !m.Message.ContainsSafe("chocolateyBeforeModify")); + messages.ShouldBeEmpty(); } } [WindowsOnly] [Platform(Exclude = "Mono")] - public class when_upgrading_a_package_with_an_exclusively_locked_file : ScenariosBase + public class When_upgrading_a_package_with_an_exclusively_locked_file : ScenariosBase { private PackageResult _packageResult; - private FileStream fileStream; + private FileStream _fileStream; public override void Context() { base.Context(); var fileToOpen = Path.Combine(Scenario.get_top_level(), "lib", Configuration.PackageNames, "tools", "chocolateyInstall.ps1"); - fileStream = new FileStream(fileToOpen, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None); + _fileStream = new FileStream(fileToOpen, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None); } public override void AfterObservations() { base.AfterObservations(); - fileStream.Close(); - fileStream.Dispose(); + _fileStream.Close(); + _fileStream.Dispose(); } public override void Because() { - Results = Service.upgrade_run(Configuration); + Results = Service.Upgrade(Configuration); _packageResult = Results.FirstOrDefault().Value; } [Fact] - public void should_have_a_package_installed_in_the_lib_directory() + public void Should_have_a_package_installed_in_the_lib_directory() { var packageDir = Path.Combine(Scenario.get_top_level(), "lib", Configuration.PackageNames); @@ -2076,7 +2104,7 @@ public void should_have_a_package_installed_in_the_lib_directory() } [Fact] - public void should_delete_the_rollback() + public void Should_delete_the_rollback() { var packageDir = Path.Combine(Scenario.get_top_level(), "lib-bkp", Configuration.PackageNames); @@ -2084,7 +2112,7 @@ public void should_delete_the_rollback() } [Fact] - public void should_contain_old_version_in_directory() + public void Should_contain_old_version_in_directory() { var shimFile = Path.Combine(Scenario.get_top_level(), "lib", Configuration.PackageNames, "tools", "console.exe"); @@ -2092,20 +2120,20 @@ public void should_contain_old_version_in_directory() } [Fact] - public void should_not_upgrade_the_package() + public void Should_not_upgrade_the_package() { var packageFile = Path.Combine(Scenario.get_top_level(), "lib", Configuration.PackageNames, Configuration.PackageNames + NuGetConstants.PackageExtension); using (var packageReader = new PackageArchiveReader(packageFile)) { - packageReader.NuspecReader.GetVersion().to_string().ShouldEqual("1.0.0"); + packageReader.NuspecReader.GetVersion().ToStringSafe().ShouldEqual("1.0.0"); } } [Fact] - public void should_contain_a_warning_message_that_it_was_not_able_to_upgrade() + public void Should_contain_a_warning_message_that_it_was_not_able_to_upgrade() { bool upgradedSuccessMessage = false; - foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).or_empty_list_if_null()) + foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).OrEmpty()) { if (message.Contains("upgraded 0/1")) upgradedSuccessMessage = true; } @@ -2114,10 +2142,10 @@ public void should_contain_a_warning_message_that_it_was_not_able_to_upgrade() } [Fact] - public void should_contain_a_warning_message_with_old_and_new_versions() + public void Should_contain_a_warning_message_with_old_and_new_versions() { bool upgradeMessage = false; - foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).or_empty_list_if_null()) + foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).OrEmpty()) { if (message.Contains("You have upgradepackage v1.0.0 installed. Version 1.1.0 is available based on your source")) upgradeMessage = true; } @@ -2126,25 +2154,25 @@ public void should_contain_a_warning_message_with_old_and_new_versions() } [Fact] - public void should_not_have_a_successful_package_result() + public void Should_not_have_a_successful_package_result() { _packageResult.Success.ShouldBeFalse(); } [Fact] - public void should_not_have_inconclusive_package_result() + public void Should_not_have_inconclusive_package_result() { _packageResult.Inconclusive.ShouldBeFalse(); } [Fact] - public void should_not_have_warning_package_result() + public void Should_not_have_warning_package_result() { _packageResult.Warning.ShouldBeFalse(); } } - public class when_upgrading_a_package_with_added_files : ScenariosBase + public class When_upgrading_a_package_with_added_files : ScenariosBase { private PackageResult _packageResult; @@ -2157,12 +2185,12 @@ public override void Context() public override void Because() { - Results = Service.upgrade_run(Configuration); + Results = Service.Upgrade(Configuration); _packageResult = Results.FirstOrDefault().Value; } [Fact] - public void should_keep_the_added_file() + public void Should_keep_the_added_file() { var fileAdded = Path.Combine(Scenario.get_top_level(), "lib", Configuration.PackageNames, "dude.txt"); @@ -2170,7 +2198,7 @@ public void should_keep_the_added_file() } [Fact] - public void should_contain_newer_version_in_directory() + public void Should_contain_newer_version_in_directory() { var shimFile = Path.Combine(Scenario.get_top_level(), "lib", Configuration.PackageNames, "tools", "console.exe"); @@ -2178,20 +2206,20 @@ public void should_contain_newer_version_in_directory() } [Fact] - public void should_upgrade_the_package() + public void Should_upgrade_the_package() { var packageFile = Path.Combine(Scenario.get_top_level(), "lib", Configuration.PackageNames, Configuration.PackageNames + NuGetConstants.PackageExtension); using (var packageReader = new PackageArchiveReader(packageFile)) { - packageReader.NuspecReader.GetVersion().to_string().ShouldEqual("1.1.0"); + packageReader.NuspecReader.GetVersion().ToStringSafe().ShouldEqual("1.1.0"); } } [Fact] - public void should_contain_a_warning_message_that_it_upgraded_successfully() + public void Should_contain_a_warning_message_that_it_upgraded_successfully() { bool upgradedSuccessMessage = false; - foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).or_empty_list_if_null()) + foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).OrEmpty()) { if (message.Contains("upgraded 1/1")) upgradedSuccessMessage = true; } @@ -2200,31 +2228,34 @@ public void should_contain_a_warning_message_that_it_upgraded_successfully() } [Fact] - public void should_have_a_successful_package_result() + public void Should_have_a_successful_package_result() { _packageResult.Success.ShouldBeTrue(); } [Fact] - public void should_not_have_inconclusive_package_result() + public void Should_not_have_inconclusive_package_result() { _packageResult.Inconclusive.ShouldBeFalse(); } [Fact] - public void should_not_have_warning_package_result() + public void Should_not_have_warning_package_result_other_than_before_modify_failures() { - _packageResult.Warning.ShouldBeFalse(); + // For before modify scripts that fail, we add a warning message. + // So we will ignore any such warnings. + var messages = _packageResult.Messages.Where(m => m.MessageType == ResultType.Warn && !m.Message.ContainsSafe("chocolateyBeforeModify")); + messages.ShouldBeEmpty(); } [Fact] - public void should_match_the_upgrade_version_of_one_dot_one_dot_zero() + public void Should_match_the_upgrade_version_of_one_dot_one_dot_zero() { _packageResult.Version.ShouldEqual("1.1.0"); } } - public class when_upgrading_a_package_with_changed_files : ScenariosBase + public class When_upgrading_a_package_with_changed_files : ScenariosBase { private PackageResult _packageResult; @@ -2237,12 +2268,12 @@ public override void Context() public override void Because() { - Results = Service.upgrade_run(Configuration); + Results = Service.Upgrade(Configuration); _packageResult = Results.FirstOrDefault().Value; } [Fact] - public void should_update_the_changed_file() + public void Should_update_the_changed_file() { var fileChanged = Path.Combine(Scenario.get_top_level(), "lib", Configuration.PackageNames, "tools", "chocolateyinstall.ps1"); @@ -2250,7 +2281,7 @@ public void should_update_the_changed_file() } [Fact] - public void should_contain_newer_version_in_directory() + public void Should_contain_newer_version_in_directory() { var shimFile = Path.Combine(Scenario.get_top_level(), "lib", Configuration.PackageNames, "tools", "console.exe"); @@ -2258,20 +2289,20 @@ public void should_contain_newer_version_in_directory() } [Fact] - public void should_upgrade_the_package() + public void Should_upgrade_the_package() { var packageFile = Path.Combine(Scenario.get_top_level(), "lib", Configuration.PackageNames, Configuration.PackageNames + NuGetConstants.PackageExtension); using (var packageReader = new PackageArchiveReader(packageFile)) { - packageReader.NuspecReader.GetVersion().to_string().ShouldEqual("1.1.0"); + packageReader.NuspecReader.GetVersion().ToStringSafe().ShouldEqual("1.1.0"); } } [Fact] - public void should_contain_a_warning_message_that_it_upgraded_successfully() + public void Should_contain_a_warning_message_that_it_upgraded_successfully() { bool upgradedSuccessMessage = false; - foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).or_empty_list_if_null()) + foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).OrEmpty()) { if (message.Contains("upgraded 1/1")) upgradedSuccessMessage = true; } @@ -2280,33 +2311,36 @@ public void should_contain_a_warning_message_that_it_upgraded_successfully() } [Fact] - public void should_have_a_successful_package_result() + public void Should_have_a_successful_package_result() { _packageResult.Success.ShouldBeTrue(); } [Fact] - public void should_not_have_inconclusive_package_result() + public void Should_not_have_inconclusive_package_result() { _packageResult.Inconclusive.ShouldBeFalse(); } [Fact] - public void should_not_have_warning_package_result() + public void Should_not_have_warning_package_result_other_than_before_modify_failures() { - _packageResult.Warning.ShouldBeFalse(); + // For before modify scripts that fail, we add a warning message. + // So we will ignore any such warnings. + var messages = _packageResult.Messages.Where(m => m.MessageType == ResultType.Warn && !m.Message.ContainsSafe("chocolateyBeforeModify")); + messages.ShouldBeEmpty(); } [Fact] - public void should_match_the_upgrade_version_of_one_dot_one_dot_zero() + public void Should_match_the_upgrade_version_of_one_dot_one_dot_zero() { _packageResult.Version.ShouldEqual("1.1.0"); } } - public class when_upgrading_a_package_that_does_not_exist : ScenariosBase + public class When_upgrading_a_package_that_does_not_exist : ScenariosBase { - private PackageResult packageResult; + private PackageResult _packageResult; public override void Context() { @@ -2316,12 +2350,12 @@ public override void Context() public override void Because() { - Results = Service.upgrade_run(Configuration); - packageResult = Results.FirstOrDefault().Value; + Results = Service.Upgrade(Configuration); + _packageResult = Results.FirstOrDefault().Value; } [Fact] - public void should_not_install_a_package_in_the_lib_directory() + public void Should_not_install_a_package_in_the_lib_directory() { var packageDir = Path.Combine(Scenario.get_top_level(), "lib", Configuration.PackageNames); @@ -2329,10 +2363,10 @@ public void should_not_install_a_package_in_the_lib_directory() } [Fact] - public void should_contain_a_message_the_package_was_not_found() + public void Should_contain_a_message_the_package_was_not_found() { bool expectedMessage = false; - foreach (var message in MockLogger.MessagesFor(LogLevel.Error).or_empty_list_if_null()) + foreach (var message in MockLogger.MessagesFor(LogLevel.Error).OrEmpty()) { if (message.Contains("nonexistentpackage not installed. The package was not found with the source(s) listed")) expectedMessage = true; } @@ -2341,10 +2375,10 @@ public void should_contain_a_message_the_package_was_not_found() } [Fact] - public void should_contain_a_message_that_no_packages_were_upgraded() + public void Should_contain_a_message_that_no_packages_were_upgraded() { bool expectedMessage = false; - foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).or_empty_list_if_null()) + foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).OrEmpty()) { if (message.Contains("upgraded 0/1")) expectedMessage = true; } @@ -2353,28 +2387,28 @@ public void should_contain_a_message_that_no_packages_were_upgraded() } [Fact] - public void should_not_have_a_successful_package_result() + public void Should_not_have_a_successful_package_result() { - packageResult.Success.ShouldBeFalse(); + _packageResult.Success.ShouldBeFalse(); } [Fact] - public void should_not_have_inconclusive_package_result() + public void Should_not_have_inconclusive_package_result() { - packageResult.Inconclusive.ShouldBeFalse(); + _packageResult.Inconclusive.ShouldBeFalse(); } [Fact] - public void should_not_have_warning_package_result() + public void Should_not_have_warning_package_result() { - packageResult.Warning.ShouldBeFalse(); + _packageResult.Warning.ShouldBeFalse(); } [Fact] - public void should_have_an_error_package_result() + public void Should_have_an_error_package_result() { bool errorFound = false; - foreach (var message in packageResult.Messages) + foreach (var message in _packageResult.Messages) { if (message.MessageType == ResultType.Error) { @@ -2386,10 +2420,10 @@ public void should_have_an_error_package_result() } [Fact] - public void should_have_expected_error_in_package_result() + public void Should_have_expected_error_in_package_result() { bool errorFound = false; - foreach (var message in packageResult.Messages) + foreach (var message in _packageResult.Messages) { if (message.MessageType == ResultType.Error) { @@ -2401,7 +2435,7 @@ public void should_have_expected_error_in_package_result() } } - public class when_upgrading_a_package_that_is_not_installed : ScenariosBase + public class When_upgrading_a_package_that_is_not_installed : ScenariosBase { private PackageResult _packageResult; @@ -2409,23 +2443,23 @@ public override void Context() { base.Context(); Configuration.PackageNames = Configuration.Input = "installpackage"; - Service.uninstall_run(Configuration); + Service.Uninstall(Configuration); } public override void Because() { - Results = Service.upgrade_run(Configuration); + Results = Service.Upgrade(Configuration); _packageResult = Results.FirstOrDefault().Value; } [Fact] - public void should_install_where_install_location_reports() + public void Should_install_where_install_location_reports() { DirectoryAssert.Exists(_packageResult.InstallLocation); } [Fact] - public void should_install_a_package_in_the_lib_directory() + public void Should_install_a_package_in_the_lib_directory() { var packageDir = Path.Combine(Scenario.get_top_level(), "lib", Configuration.PackageNames); @@ -2433,7 +2467,7 @@ public void should_install_a_package_in_the_lib_directory() } [Fact] - public void should_not_have_a_rollback_directory() + public void Should_not_have_a_rollback_directory() { var packageDir = Path.Combine(Scenario.get_top_level(), "lib-bkp", Configuration.PackageNames); @@ -2441,10 +2475,10 @@ public void should_not_have_a_rollback_directory() } [Fact] - public void should_contain_a_warning_message_that_it_upgraded_successfully() + public void Should_contain_a_warning_message_that_it_upgraded_successfully() { bool upgradedSuccessMessage = false; - foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).or_empty_list_if_null()) + foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).OrEmpty()) { if (message.Contains("upgraded 1/1")) upgradedSuccessMessage = true; } @@ -2453,19 +2487,19 @@ public void should_contain_a_warning_message_that_it_upgraded_successfully() } [Fact] - public void should_have_a_successful_package_result() + public void Should_have_a_successful_package_result() { _packageResult.Success.ShouldBeTrue(); } [Fact] - public void should_not_have_inconclusive_package_result() + public void Should_not_have_inconclusive_package_result() { _packageResult.Inconclusive.ShouldBeFalse(); } [Fact] - public void should_not_have_warning_package_result() + public void Should_not_have_warning_package_result() { _packageResult.Warning.ShouldBeFalse(); } @@ -2473,7 +2507,7 @@ public void should_not_have_warning_package_result() [WindowsOnly] [Platform(Exclude = "Mono")] - public class when_upgrading_a_package_that_is_not_installed_and_failing_on_not_installed : ScenariosBase + public class When_upgrading_a_package_that_is_not_installed_and_failing_on_not_installed : ScenariosBase { private PackageResult _packageResult; @@ -2481,18 +2515,18 @@ public override void Context() { base.Context(); Configuration.PackageNames = Configuration.Input = "installpackage"; - Service.uninstall_run(Configuration); + Service.Uninstall(Configuration); Configuration.UpgradeCommand.FailOnNotInstalled = true; } public override void Because() { - Results = Service.upgrade_run(Configuration); + Results = Service.Upgrade(Configuration); _packageResult = Results.FirstOrDefault().Value; } [Fact] - public void should_not_install_a_package_in_the_lib_directory() + public void Should_not_install_a_package_in_the_lib_directory() { var packageDir = Path.Combine(Scenario.get_top_level(), "lib", Configuration.PackageNames); @@ -2500,10 +2534,10 @@ public void should_not_install_a_package_in_the_lib_directory() } [Fact] - public void should_contain_a_warning_message_that_it_was_unable_to_upgrade_a_package() + public void Should_contain_a_warning_message_that_it_was_unable_to_upgrade_a_package() { bool notInstalled = false; - foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).or_empty_list_if_null()) + foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).OrEmpty()) { if (message.Contains("0/1")) notInstalled = true; } @@ -2512,25 +2546,25 @@ public void should_contain_a_warning_message_that_it_was_unable_to_upgrade_a_pac } [Fact] - public void should_not_have_a_successful_package_result() + public void Should_not_have_a_successful_package_result() { _packageResult.Success.ShouldBeFalse(); } [Fact] - public void should_not_have_inconclusive_package_result() + public void Should_not_have_inconclusive_package_result() { _packageResult.Inconclusive.ShouldBeFalse(); } [Fact] - public void should_not_have_warning_package_result() + public void Should_not_have_warning_package_result() { _packageResult.Warning.ShouldBeFalse(); } [Fact] - public void should_have_an_error_package_result() + public void Should_have_an_error_package_result() { bool errorFound = false; foreach (var message in _packageResult.Messages) @@ -2545,7 +2579,7 @@ public void should_have_an_error_package_result() } [Fact] - public void should_have_expected_error_in_package_result() + public void Should_have_expected_error_in_package_result() { bool errorFound = false; foreach (var message in _packageResult.Messages) @@ -2562,9 +2596,9 @@ public void should_have_expected_error_in_package_result() [WindowsOnly] [Platform(Exclude = "Mono")] - public class when_upgrading_a_package_that_errors : ScenariosBase + public class When_upgrading_a_package_that_errors : ScenariosBase { - private PackageResult packageResult; + private PackageResult _packageResult; public override void Context() { @@ -2574,12 +2608,12 @@ public override void Context() public override void Because() { - Results = Service.upgrade_run(Configuration); - packageResult = Results.FirstOrDefault().Value; + Results = Service.Upgrade(Configuration); + _packageResult = Results.FirstOrDefault().Value; } [Fact] - public void should_not_remove_package_from_the_lib_directory() + public void Should_not_remove_package_from_the_lib_directory() { var packageDir = Path.Combine(Scenario.get_top_level(), "lib", Configuration.PackageNames); @@ -2587,17 +2621,17 @@ public void should_not_remove_package_from_the_lib_directory() } [Fact] - public void should_not_upgrade_the_package() + public void Should_not_upgrade_the_package() { var packageFile = Path.Combine(Scenario.get_top_level(), "lib", Configuration.PackageNames, Configuration.PackageNames + NuGetConstants.PackageExtension); using (var packageReader = new PackageArchiveReader(packageFile)) { - packageReader.NuspecReader.GetVersion().to_string().ShouldEqual("1.0.0"); + packageReader.NuspecReader.GetVersion().ToStringSafe().ShouldEqual("1.0.0"); } } [Fact] - public void should_put_the_package_in_the_lib_bad_directory() + public void Should_put_the_package_in_the_lib_bad_directory() { var packageDir = Path.Combine(Scenario.get_top_level(), "lib-bad", Configuration.PackageNames); @@ -2605,17 +2639,17 @@ public void should_put_the_package_in_the_lib_bad_directory() } [Fact] - public void should_have_the_erroring_upgraded_package_in_the_lib_bad_directory() + public void Should_have_the_erroring_upgraded_package_in_the_lib_bad_directory() { - var packageFile = Path.Combine(Scenario.get_top_level(), "lib-bad", Configuration.PackageNames, Configuration.PackageNames + NuGetConstants.PackageExtension); + var packageFile = Path.Combine(Scenario.get_top_level(), "lib-bad", Configuration.PackageNames, "2.0.0", Configuration.PackageNames + NuGetConstants.PackageExtension); using (var packageReader = new PackageArchiveReader(packageFile)) { - packageReader.NuspecReader.GetVersion().to_string().ShouldEqual("2.0.0"); + packageReader.NuspecReader.GetVersion().ToStringSafe().ShouldEqual("2.0.0"); } } [Fact] - public void should_delete_the_rollback() + public void Should_delete_the_rollback() { var packageDir = Path.Combine(Scenario.get_top_level(), "lib-bkp", Configuration.PackageNames); @@ -2623,10 +2657,10 @@ public void should_delete_the_rollback() } [Fact] - public void should_contain_a_warning_message_that_it_was_unable_to_upgrade_a_package() + public void Should_contain_a_warning_message_that_it_was_unable_to_upgrade_a_package() { bool installedSuccessfully = false; - foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).or_empty_list_if_null()) + foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).OrEmpty()) { if (message.Contains("0/1")) installedSuccessfully = true; } @@ -2635,28 +2669,28 @@ public void should_contain_a_warning_message_that_it_was_unable_to_upgrade_a_pac } [Fact] - public void should_not_have_a_successful_package_result() + public void Should_not_have_a_successful_package_result() { - packageResult.Success.ShouldBeFalse(); + _packageResult.Success.ShouldBeFalse(); } [Fact] - public void should_not_have_inconclusive_package_result() + public void Should_not_have_inconclusive_package_result() { - packageResult.Inconclusive.ShouldBeFalse(); + _packageResult.Inconclusive.ShouldBeFalse(); } [Fact] - public void should_not_have_warning_package_result() + public void Should_not_have_warning_package_result() { - packageResult.Warning.ShouldBeFalse(); + _packageResult.Warning.ShouldBeFalse(); } [Fact] - public void should_have_an_error_package_result() + public void Should_have_an_error_package_result() { bool errorFound = false; - foreach (var message in packageResult.Messages) + foreach (var message in _packageResult.Messages) { if (message.MessageType == ResultType.Error) { @@ -2668,10 +2702,10 @@ public void should_have_an_error_package_result() } [Fact] - public void should_have_expected_error_in_package_result() + public void Should_have_expected_error_in_package_result() { bool errorFound = false; - foreach (var message in packageResult.Messages) + foreach (var message in _packageResult.Messages) { if (message.MessageType == ResultType.Error) { @@ -2683,7 +2717,7 @@ public void should_have_expected_error_in_package_result() } } - public class when_upgrading_a_package_with_dependencies_happy : ScenariosBase + public class When_upgrading_a_package_with_dependencies_happy : ScenariosBase { public override void Context() { @@ -2698,44 +2732,44 @@ public override void Context() public override void Because() { - Results = Service.upgrade_run(Configuration); + Results = Service.Upgrade(Configuration); } [Fact] - public void should_upgrade_the_package() + public void Should_upgrade_the_package() { var packageFile = Path.Combine(Scenario.get_top_level(), "lib", "hasdependency", "hasdependency.nupkg"); using (var packageReader = new PackageArchiveReader(packageFile)) { - packageReader.NuspecReader.GetVersion().to_string().ShouldEqual("2.1.0"); + packageReader.NuspecReader.GetVersion().ToStringSafe().ShouldEqual("2.1.0"); } } [Fact] - public void should_upgrade_the_minimum_version_dependency() + public void Should_upgrade_the_minimum_version_dependency() { var packageFile = Path.Combine(Scenario.get_top_level(), "lib", "isdependency", "isdependency.nupkg"); using (var packageReader = new PackageArchiveReader(packageFile)) { - packageReader.NuspecReader.GetVersion().to_string().ShouldEqual("2.1.0"); + packageReader.NuspecReader.GetVersion().ToStringSafe().ShouldEqual("2.1.0"); } } [Fact] - public void should_upgrade_the_exact_version_dependency() + public void Should_upgrade_the_exact_version_dependency() { var packageFile = Path.Combine(Scenario.get_top_level(), "lib", "isexactversiondependency", "isexactversiondependency.nupkg"); using (var packageReader = new PackageArchiveReader(packageFile)) { - packageReader.NuspecReader.GetVersion().to_string().ShouldEqual("2.0.0"); + packageReader.NuspecReader.GetVersion().ToStringSafe().ShouldEqual("2.0.0"); } } [Fact] - public void should_contain_a_message_that_everything_upgraded_successfully() + public void Should_contain_a_message_that_everything_upgraded_successfully() { bool expectedMessage = false; - foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).or_empty_list_if_null()) + foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).OrEmpty()) { if (message.Contains("upgraded 3/3")) expectedMessage = true; } @@ -2744,7 +2778,7 @@ public void should_contain_a_message_that_everything_upgraded_successfully() } [Fact] - public void should_have_a_successful_package_result() + public void Should_have_a_successful_package_result() { foreach (var packageResult in Results) { @@ -2753,7 +2787,7 @@ public void should_have_a_successful_package_result() } [Fact] - public void should_not_have_inconclusive_package_result() + public void Should_not_have_inconclusive_package_result() { foreach (var packageResult in Results) { @@ -2762,7 +2796,7 @@ public void should_not_have_inconclusive_package_result() } [Fact] - public void should_not_have_warning_package_result() + public void Should_not_have_warning_package_result() { foreach (var packageResult in Results) { @@ -2771,7 +2805,7 @@ public void should_not_have_warning_package_result() } } - public class when_upgrading_a_package_with_unavailable_dependencies : ScenariosBase + public class When_upgrading_a_package_with_unavailable_dependencies : ScenariosBase { public override void Context() { @@ -2786,44 +2820,44 @@ public override void Context() public override void Because() { - Results = Service.upgrade_run(Configuration); + Results = Service.Upgrade(Configuration); } [Fact] - public void should_not_upgrade_the_package() + public void Should_not_upgrade_the_package() { var packageFile = Path.Combine(Scenario.get_top_level(), "lib", "hasdependency", "hasdependency.nupkg"); using (var packageReader = new PackageArchiveReader(packageFile)) { - packageReader.NuspecReader.GetVersion().to_string().ShouldEqual("1.0.0"); + packageReader.NuspecReader.GetVersion().ToStringSafe().ShouldEqual("1.0.0"); } } [Fact] - public void should_not_upgrade_the_minimum_version_dependency() + public void Should_not_upgrade_the_minimum_version_dependency() { var packageFile = Path.Combine(Scenario.get_top_level(), "lib", "isdependency", "isdependency.nupkg"); using (var packageReader = new PackageArchiveReader(packageFile)) { - packageReader.NuspecReader.GetVersion().to_string().ShouldEqual("1.0.0"); + packageReader.NuspecReader.GetVersion().ToStringSafe().ShouldEqual("1.0.0"); } } [Fact] - public void should_not_upgrade_the_exact_version_dependency() + public void Should_not_upgrade_the_exact_version_dependency() { var packageFile = Path.Combine(Scenario.get_top_level(), "lib", "isexactversiondependency", "isexactversiondependency.nupkg"); using (var packageReader = new PackageArchiveReader(packageFile)) { - packageReader.NuspecReader.GetVersion().to_string().ShouldEqual("1.0.0"); + packageReader.NuspecReader.GetVersion().ToStringSafe().ShouldEqual("1.0.0"); } } [Fact] - public void should_contain_a_message_that_it_was_unable_to_upgrade_anything() + public void Should_contain_a_message_that_it_was_unable_to_upgrade_anything() { bool expectedMessage = false; - foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).or_empty_list_if_null()) + foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).OrEmpty()) { if (message.Contains("upgraded 0/1")) expectedMessage = true; } @@ -2832,7 +2866,7 @@ public void should_contain_a_message_that_it_was_unable_to_upgrade_anything() } [Fact] - public void should_not_have_a_successful_package_result() + public void Should_not_have_a_successful_package_result() { foreach (var packageResult in Results) { @@ -2841,7 +2875,7 @@ public void should_not_have_a_successful_package_result() } [Fact] - public void should_not_have_inconclusive_package_result() + public void Should_not_have_inconclusive_package_result() { foreach (var packageResult in Results) { @@ -2850,7 +2884,7 @@ public void should_not_have_inconclusive_package_result() } [Fact] - public void should_not_have_warning_package_result() + public void Should_not_have_warning_package_result() { foreach (var packageResult in Results) { @@ -2859,7 +2893,7 @@ public void should_not_have_warning_package_result() } [Fact] - public void should_have_an_error_package_result() + public void Should_have_an_error_package_result() { bool errorFound = false; @@ -2878,7 +2912,7 @@ public void should_have_an_error_package_result() } [Fact] - public void should_have_expected_error_in_package_result() + public void Should_have_expected_error_in_package_result() { bool errorFound = false; @@ -2897,7 +2931,7 @@ public void should_have_expected_error_in_package_result() } } - public class when_upgrading_a_package_with_unavailable_dependencies_ignoring_dependencies : ScenariosBase + public class When_upgrading_a_package_with_unavailable_dependencies_ignoring_dependencies : ScenariosBase { public override void Context() { @@ -2913,44 +2947,44 @@ public override void Context() public override void Because() { - Results = Service.upgrade_run(Configuration); + Results = Service.Upgrade(Configuration); } [Fact] - public void should_upgrade_the_package() + public void Should_upgrade_the_package() { var packageFile = Path.Combine(Scenario.get_top_level(), "lib", "hasdependency", "hasdependency.nupkg"); using (var packageReader = new PackageArchiveReader(packageFile)) { - packageReader.NuspecReader.GetVersion().to_string().ShouldEqual("2.1.0"); + packageReader.NuspecReader.GetVersion().ToStringSafe().ShouldEqual("2.1.0"); } } [Fact] - public void should_not_upgrade_the_minimum_version_dependency() + public void Should_not_upgrade_the_minimum_version_dependency() { var packageFile = Path.Combine(Scenario.get_top_level(), "lib", "isdependency", "isdependency.nupkg"); using (var packageReader = new PackageArchiveReader(packageFile)) { - packageReader.NuspecReader.GetVersion().to_string().ShouldEqual("1.0.0"); + packageReader.NuspecReader.GetVersion().ToStringSafe().ShouldEqual("1.0.0"); } } [Fact] - public void should_not_upgrade_the_exact_version_dependency() + public void Should_not_upgrade_the_exact_version_dependency() { var packageFile = Path.Combine(Scenario.get_top_level(), "lib", "isexactversiondependency", "isexactversiondependency.nupkg"); using (var packageReader = new PackageArchiveReader(packageFile)) { - packageReader.NuspecReader.GetVersion().to_string().ShouldEqual("1.0.0"); + packageReader.NuspecReader.GetVersion().ToStringSafe().ShouldEqual("1.0.0"); } } [Fact] - public void should_contain_a_message_that_it_upgraded_only_the_package_successfully() + public void Should_contain_a_message_that_it_upgraded_only_the_package_successfully() { bool expectedMessage = false; - foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).or_empty_list_if_null()) + foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).OrEmpty()) { if (message.Contains("upgraded 1/1")) expectedMessage = true; } @@ -2959,7 +2993,7 @@ public void should_contain_a_message_that_it_upgraded_only_the_package_successfu } [Fact] - public void should_have_a_successful_package_result() + public void Should_have_a_successful_package_result() { foreach (var packageResult in Results) { @@ -2968,7 +3002,7 @@ public void should_have_a_successful_package_result() } [Fact] - public void should_not_have_inconclusive_package_result() + public void Should_not_have_inconclusive_package_result() { foreach (var packageResult in Results) { @@ -2977,7 +3011,7 @@ public void should_not_have_inconclusive_package_result() } [Fact] - public void should_not_have_warning_package_result() + public void Should_not_have_warning_package_result() { foreach (var packageResult in Results) { @@ -2986,7 +3020,7 @@ public void should_not_have_warning_package_result() } } - public class when_upgrading_a_dependency_happy : ScenariosBase + public class When_upgrading_a_dependency_happy : ScenariosBase { public override void Context() { @@ -3001,44 +3035,44 @@ public override void Context() public override void Because() { - Results = Service.upgrade_run(Configuration); + Results = Service.Upgrade(Configuration); } [Fact] - public void should_upgrade_the_package() + public void Should_upgrade_the_package() { var packageFile = Path.Combine(Scenario.get_top_level(), "lib", "isdependency", "isdependency.nupkg"); using (var packageReader = new PackageArchiveReader(packageFile)) { - packageReader.NuspecReader.GetVersion().to_string().ShouldEqual("1.1.0"); + packageReader.NuspecReader.GetVersion().ToStringSafe().ShouldEqual("1.1.0"); } } [Fact] - public void should_not_upgrade_the_parent_package() + public void Should_not_upgrade_the_parent_package() { var packageFile = Path.Combine(Scenario.get_top_level(), "lib", "hasdependency", "hasdependency.nupkg"); using (var packageReader = new PackageArchiveReader(packageFile)) { - packageReader.NuspecReader.GetVersion().to_string().ShouldEqual("1.0.0"); + packageReader.NuspecReader.GetVersion().ToStringSafe().ShouldEqual("1.0.0"); } } [Fact] - public void should_not_upgrade_the_exact_version_dependency() + public void Should_not_upgrade_the_exact_version_dependency() { var packageFile = Path.Combine(Scenario.get_top_level(), "lib", "isexactversiondependency", "isexactversiondependency.nupkg"); using (var packageReader = new PackageArchiveReader(packageFile)) { - packageReader.NuspecReader.GetVersion().to_string().ShouldEqual("1.0.0"); + packageReader.NuspecReader.GetVersion().ToStringSafe().ShouldEqual("1.0.0"); } } [Fact] - public void should_contain_a_message_the_dependency_upgraded_successfully() + public void Should_contain_a_message_the_dependency_upgraded_successfully() { bool expectedMessage = false; - foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).or_empty_list_if_null()) + foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).OrEmpty()) { if (message.Contains("upgraded 1/1")) expectedMessage = true; } @@ -3047,7 +3081,7 @@ public void should_contain_a_message_the_dependency_upgraded_successfully() } [Fact] - public void should_have_a_successful_package_result() + public void Should_have_a_successful_package_result() { foreach (var packageResult in Results) { @@ -3056,7 +3090,7 @@ public void should_have_a_successful_package_result() } [Fact] - public void should_not_have_inconclusive_package_result() + public void Should_not_have_inconclusive_package_result() { foreach (var packageResult in Results) { @@ -3065,7 +3099,7 @@ public void should_not_have_inconclusive_package_result() } [Fact] - public void should_not_have_warning_package_result() + public void Should_not_have_warning_package_result() { foreach (var packageResult in Results) { @@ -3074,7 +3108,7 @@ public void should_not_have_warning_package_result() } } - public class when_upgrading_a_dependency_with_parent_that_depends_on_a_range_less_than_upgrade_version : ScenariosBase + public class When_upgrading_a_dependency_with_parent_that_depends_on_a_range_less_than_upgrade_version : ScenariosBase { public override void Context() { @@ -3089,44 +3123,44 @@ public override void Context() public override void Because() { - Results = Service.upgrade_run(Configuration); + Results = Service.Upgrade(Configuration); } [Fact] - public void should_upgrade_the_package() + public void Should_upgrade_the_package() { var packageFile = Path.Combine(Scenario.get_top_level(), "lib", "isdependency", "isdependency.nupkg"); using (var packageReader = new PackageArchiveReader(packageFile)) { - packageReader.NuspecReader.GetVersion().to_string().ShouldEqual("2.1.0"); + packageReader.NuspecReader.GetVersion().ToStringSafe().ShouldEqual("2.1.0"); } } [Fact] - public void should_upgrade_the_parent_package_to_highest_version_that_meets_new_dependency_version() + public void Should_upgrade_the_parent_package_to_highest_version_that_meets_new_dependency_version() { var packageFile = Path.Combine(Scenario.get_top_level(), "lib", "hasdependency", "hasdependency.nupkg"); using (var packageReader = new PackageArchiveReader(packageFile)) { - packageReader.NuspecReader.GetVersion().to_string().ShouldEqual("2.1.0"); + packageReader.NuspecReader.GetVersion().ToStringSafe().ShouldEqual("2.1.0"); } } [Fact] - public void should_upgrade_the_exact_version_dependency() + public void Should_upgrade_the_exact_version_dependency() { var packageFile = Path.Combine(Scenario.get_top_level(), "lib", "isexactversiondependency", "isexactversiondependency.nupkg"); using (var packageReader = new PackageArchiveReader(packageFile)) { - packageReader.NuspecReader.GetVersion().to_string().ShouldEqual("2.0.0"); + packageReader.NuspecReader.GetVersion().ToStringSafe().ShouldEqual("2.0.0"); } } [Fact] - public void should_contain_a_message_that_everything_upgraded_successfully() + public void Should_contain_a_message_that_everything_upgraded_successfully() { bool expectedMessage = false; - foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).or_empty_list_if_null()) + foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).OrEmpty()) { if (message.Contains("upgraded 3/3")) expectedMessage = true; } @@ -3135,7 +3169,7 @@ public void should_contain_a_message_that_everything_upgraded_successfully() } [Fact] - public void should_have_a_successful_package_result() + public void Should_have_a_successful_package_result() { foreach (var packageResult in Results) { @@ -3144,7 +3178,7 @@ public void should_have_a_successful_package_result() } [Fact] - public void should_not_have_inconclusive_package_result() + public void Should_not_have_inconclusive_package_result() { foreach (var packageResult in Results) { @@ -3153,7 +3187,7 @@ public void should_not_have_inconclusive_package_result() } [Fact] - public void should_not_have_warning_package_result() + public void Should_not_have_warning_package_result() { foreach (var packageResult in Results) { @@ -3162,7 +3196,7 @@ public void should_not_have_warning_package_result() } } - public class when_upgrading_a_dependency_with_parent_that_depends_on_a_range_less_than_upgrade_version_and_has_a_different_missing_dependency : ScenariosBase + public class When_upgrading_a_dependency_with_parent_that_depends_on_a_range_less_than_upgrade_version_and_has_a_different_missing_dependency : ScenariosBase { public override void Context() { @@ -3179,44 +3213,44 @@ public override void Context() public override void Because() { - Results = Service.upgrade_run(Configuration); + Results = Service.Upgrade(Configuration); } [Fact] - public void should_upgrade_the_package() + public void Should_upgrade_the_package() { var packageFile = Path.Combine(Scenario.get_top_level(), "lib", "isdependency", "isdependency.nupkg"); using (var packageReader = new PackageArchiveReader(packageFile)) { - packageReader.NuspecReader.GetVersion().to_string().ShouldEqual("2.1.0"); + packageReader.NuspecReader.GetVersion().ToStringSafe().ShouldEqual("2.1.0"); } } [Fact] - public void should_upgrade_the_parent_package_to_highest_version_that_meets_new_dependency_version() + public void Should_upgrade_the_parent_package_to_highest_version_that_meets_new_dependency_version() { var packageFile = Path.Combine(Scenario.get_top_level(), "lib", "hasdependency", "hasdependency.nupkg"); using (var packageReader = new PackageArchiveReader(packageFile)) { - packageReader.NuspecReader.GetVersion().to_string().ShouldEqual("2.1.0"); + packageReader.NuspecReader.GetVersion().ToStringSafe().ShouldEqual("2.1.0"); } } [Fact] - public void should_upgrade_the_exact_version_dependency() + public void Should_upgrade_the_exact_version_dependency() { var packageFile = Path.Combine(Scenario.get_top_level(), "lib", "isexactversiondependency", "isexactversiondependency.nupkg"); using (var packageReader = new PackageArchiveReader(packageFile)) { - packageReader.NuspecReader.GetVersion().to_string().ShouldEqual("2.0.0"); + packageReader.NuspecReader.GetVersion().ToStringSafe().ShouldEqual("2.0.0"); } } [Fact] - public void should_contain_a_message_that_everything_upgraded_successfully() + public void Should_contain_a_message_that_everything_upgraded_successfully() { bool expectedMessage = false; - foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).or_empty_list_if_null()) + foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).OrEmpty()) { if (message.Contains("upgraded 3/3")) expectedMessage = true; } @@ -3225,7 +3259,7 @@ public void should_contain_a_message_that_everything_upgraded_successfully() } [Fact] - public void should_have_a_successful_package_result() + public void Should_have_a_successful_package_result() { foreach (var packageResult in Results) { @@ -3234,7 +3268,7 @@ public void should_have_a_successful_package_result() } [Fact] - public void should_not_have_inconclusive_package_result() + public void Should_not_have_inconclusive_package_result() { foreach (var packageResult in Results) { @@ -3243,7 +3277,7 @@ public void should_not_have_inconclusive_package_result() } [Fact] - public void should_not_have_warning_package_result() + public void Should_not_have_warning_package_result() { foreach (var packageResult in Results) { @@ -3252,7 +3286,7 @@ public void should_not_have_warning_package_result() } } - public class when_upgrading_a_dependency_with_parent_being_pinned_and_depends_on_a_range_less_than_upgrade_version : ScenariosBase + public class When_upgrading_a_dependency_with_parent_being_pinned_and_depends_on_a_range_less_than_upgrade_version : ScenariosBase { public override void Context() { @@ -3269,44 +3303,44 @@ public override void Context() public override void Because() { - Results = Service.upgrade_run(Configuration); + Results = Service.Upgrade(Configuration); } [Fact] - public void should_upgrade_the_package_to_highest_version_in_range() + public void Should_upgrade_the_package_to_highest_version_in_range() { var packageFile = Path.Combine(Scenario.get_top_level(), "lib", "isdependency", "isdependency.nupkg"); using (var packageReader = new PackageArchiveReader(packageFile)) { - packageReader.NuspecReader.GetVersion().to_string().ShouldEqual("1.1.0"); + packageReader.NuspecReader.GetVersion().ToStringSafe().ShouldEqual("1.1.0"); } } [Fact] - public void should_not_upgrade_parent_package() + public void Should_not_upgrade_parent_package() { var packageFile = Path.Combine(Scenario.get_top_level(), "lib", "hasdependency", "hasdependency.nupkg"); using (var packageReader = new PackageArchiveReader(packageFile)) { - packageReader.NuspecReader.GetVersion().to_string().ShouldEqual("1.0.0"); + packageReader.NuspecReader.GetVersion().ToStringSafe().ShouldEqual("1.0.0"); } } [Fact] - public void should_not_upgrade_the_exact_version_dependency() + public void Should_not_upgrade_the_exact_version_dependency() { var packageFile = Path.Combine(Scenario.get_top_level(), "lib", "isexactversiondependency", "isexactversiondependency.nupkg"); using (var packageReader = new PackageArchiveReader(packageFile)) { - packageReader.NuspecReader.GetVersion().to_string().ShouldEqual("1.0.0"); + packageReader.NuspecReader.GetVersion().ToStringSafe().ShouldEqual("1.0.0"); } } [Fact] - public void should_contain_a_message_that_everything_upgraded_successfully() + public void Should_contain_a_message_that_everything_upgraded_successfully() { bool expectedMessage = false; - foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).or_empty_list_if_null()) + foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).OrEmpty()) { if (message.Contains("upgraded 1/1")) expectedMessage = true; } @@ -3315,7 +3349,7 @@ public void should_contain_a_message_that_everything_upgraded_successfully() } [Fact] - public void should_have_a_successful_package_result() + public void Should_have_a_successful_package_result() { foreach (var packageResult in Results) { @@ -3324,7 +3358,7 @@ public void should_have_a_successful_package_result() } [Fact] - public void should_not_have_inconclusive_package_result() + public void Should_not_have_inconclusive_package_result() { foreach (var packageResult in Results) { @@ -3333,7 +3367,7 @@ public void should_not_have_inconclusive_package_result() } [Fact] - public void should_not_have_warning_package_result() + public void Should_not_have_warning_package_result() { foreach (var packageResult in Results) { @@ -3342,10 +3376,10 @@ public void should_not_have_warning_package_result() } [Fact] - public void should_have_outputted_conflicting_upgrade_message() + public void Should_have_outputted_conflicting_upgrade_message() { bool expectedMessage = false; - foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).or_empty_list_if_null()) + foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).OrEmpty()) { if (message.Contains("One or more unresolved package dependency constraints detected in the Chocolatey lib folder") && message.Contains("hasdependency 1.0.0 constraint: isdependency (>= 1.0.0 && < 2.0.0)")) @@ -3358,7 +3392,7 @@ public void should_have_outputted_conflicting_upgrade_message() } } - public class when_upgrading_a_dependency_with_parent_being_pinned_and_depends_on_a_range_less_than_upgrade_version_and_has_missing_dependency : ScenariosBase + public class When_upgrading_a_dependency_with_parent_being_pinned_and_depends_on_a_range_less_than_upgrade_version_and_has_missing_dependency : ScenariosBase { public override void Context() { @@ -3377,44 +3411,44 @@ public override void Context() public override void Because() { - Results = Service.upgrade_run(Configuration); + Results = Service.Upgrade(Configuration); } [Fact] - public void should_upgrade_the_package_to_highest_version_in_range() + public void Should_upgrade_the_package_to_highest_version_in_range() { var packageFile = Path.Combine(Scenario.get_top_level(), "lib", "isdependency", "isdependency.nupkg"); using (var packageReader = new PackageArchiveReader(packageFile)) { - packageReader.NuspecReader.GetVersion().to_string().ShouldEqual("1.1.0"); + packageReader.NuspecReader.GetVersion().ToStringSafe().ShouldEqual("1.1.0"); } } [Fact] - public void should_not_upgrade_parent_package() + public void Should_not_upgrade_parent_package() { var packageFile = Path.Combine(Scenario.get_top_level(), "lib", "hasdependency", "hasdependency.nupkg"); using (var packageReader = new PackageArchiveReader(packageFile)) { - packageReader.NuspecReader.GetVersion().to_string().ShouldEqual("1.0.0"); + packageReader.NuspecReader.GetVersion().ToStringSafe().ShouldEqual("1.0.0"); } } [Fact] - public void should_not_upgrade_the_exact_version_dependency() + public void Should_not_upgrade_the_exact_version_dependency() { var packageFile = Path.Combine(Scenario.get_top_level(), "lib", "isexactversiondependency", "isexactversiondependency.nupkg"); using (var packageReader = new PackageArchiveReader(packageFile)) { - packageReader.NuspecReader.GetVersion().to_string().ShouldEqual("1.0.0"); + packageReader.NuspecReader.GetVersion().ToStringSafe().ShouldEqual("1.0.0"); } } [Fact] - public void should_contain_a_message_that_everything_upgraded_successfully() + public void Should_contain_a_message_that_everything_upgraded_successfully() { bool expectedMessage = false; - foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).or_empty_list_if_null()) + foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).OrEmpty()) { if (message.Contains("upgraded 2/2")) expectedMessage = true; } @@ -3423,7 +3457,7 @@ public void should_contain_a_message_that_everything_upgraded_successfully() } [Fact] - public void should_have_a_successful_package_result() + public void Should_have_a_successful_package_result() { foreach (var packageResult in Results) { @@ -3432,7 +3466,7 @@ public void should_have_a_successful_package_result() } [Fact] - public void should_not_have_inconclusive_package_result() + public void Should_not_have_inconclusive_package_result() { foreach (var packageResult in Results) { @@ -3441,7 +3475,7 @@ public void should_not_have_inconclusive_package_result() } [Fact] - public void should_not_have_warning_package_result() + public void Should_not_have_warning_package_result() { foreach (var packageResult in Results) { @@ -3450,10 +3484,10 @@ public void should_not_have_warning_package_result() } [Fact] - public void should_have_outputted_conflicting_upgrade_message() + public void Should_have_outputted_conflicting_upgrade_message() { bool expectedMessage = false; - foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).or_empty_list_if_null()) + foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).OrEmpty()) { if (message.Contains("One or more unresolved package dependency constraints detected in the Chocolatey lib folder") && message.Contains("hasdependency 1.0.0 constraint: isexactversiondependency (= 1.0.0)") @@ -3467,7 +3501,7 @@ public void should_have_outputted_conflicting_upgrade_message() } } - public class when_upgrading_a_dependency_with_parent_has_different_pinned_dependency_and_depends_on_a_range_less_than_upgrade_version : ScenariosBase + public class When_upgrading_a_dependency_with_parent_has_different_pinned_dependency_and_depends_on_a_range_less_than_upgrade_version : ScenariosBase { public override void Context() { @@ -3486,44 +3520,44 @@ public override void Context() public override void Because() { - Results = Service.upgrade_run(Configuration); + Results = Service.Upgrade(Configuration); } [Fact] - public void should_upgrade_the_package_to_highest_version_in_range() + public void Should_upgrade_the_package_to_highest_version_in_range() { var packageFile = Path.Combine(Scenario.get_top_level(), "lib", "isdependency", "isdependency.nupkg"); using (var packageReader = new PackageArchiveReader(packageFile)) { - packageReader.NuspecReader.GetVersion().to_string().ShouldEqual("1.1.0"); + packageReader.NuspecReader.GetVersion().ToStringSafe().ShouldEqual("1.1.0"); } } [Fact] - public void should_not_upgrade_parent_package() + public void Should_not_upgrade_parent_package() { var packageFile = Path.Combine(Scenario.get_top_level(), "lib", "hasdependency", "hasdependency.nupkg"); using (var packageReader = new PackageArchiveReader(packageFile)) { - packageReader.NuspecReader.GetVersion().to_string().ShouldEqual("1.0.0"); + packageReader.NuspecReader.GetVersion().ToStringSafe().ShouldEqual("1.0.0"); } } [Fact] - public void should_not_upgrade_the_exact_version_dependency() + public void Should_not_upgrade_the_exact_version_dependency() { var packageFile = Path.Combine(Scenario.get_top_level(), "lib", "isexactversiondependency", "isexactversiondependency.nupkg"); using (var packageReader = new PackageArchiveReader(packageFile)) { - packageReader.NuspecReader.GetVersion().to_string().ShouldEqual("1.0.0"); + packageReader.NuspecReader.GetVersion().ToStringSafe().ShouldEqual("1.0.0"); } } [Fact] - public void should_contain_a_message_that_everything_upgraded_successfully() + public void Should_contain_a_message_that_everything_upgraded_successfully() { bool expectedMessage = false; - foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).or_empty_list_if_null()) + foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).OrEmpty()) { if (message.Contains("upgraded 1/1")) expectedMessage = true; } @@ -3532,7 +3566,7 @@ public void should_contain_a_message_that_everything_upgraded_successfully() } [Fact] - public void should_have_a_successful_package_result() + public void Should_have_a_successful_package_result() { foreach (var packageResult in Results) { @@ -3541,7 +3575,7 @@ public void should_have_a_successful_package_result() } [Fact] - public void should_not_have_inconclusive_package_result() + public void Should_not_have_inconclusive_package_result() { foreach (var packageResult in Results) { @@ -3550,7 +3584,7 @@ public void should_not_have_inconclusive_package_result() } [Fact] - public void should_not_have_warning_package_result() + public void Should_not_have_warning_package_result() { foreach (var packageResult in Results) { @@ -3559,10 +3593,10 @@ public void should_not_have_warning_package_result() } [Fact] - public void should_have_outputted_conflicting_upgrade_message() + public void Should_have_outputted_conflicting_upgrade_message() { bool expectedMessage = false; - foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).or_empty_list_if_null()) + foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).OrEmpty()) { if (message.Contains("One or more unresolved package dependency constraints detected in the Chocolatey lib folder") && message.Contains("hasdependency 1.0.0 constraint: isdependency (>= 1.0.0 && < 2.0.0)")) @@ -3575,7 +3609,7 @@ public void should_have_outputted_conflicting_upgrade_message() } } - public class when_upgrading_a_dependency_while_ignoring_dependencies_and_parent_package_is_pinned : ScenariosBase + public class When_upgrading_a_dependency_while_ignoring_dependencies_and_parent_package_is_pinned : ScenariosBase { public override void Context() { @@ -3593,44 +3627,44 @@ public override void Context() public override void Because() { - Results = Service.upgrade_run(Configuration); + Results = Service.Upgrade(Configuration); } [Fact] - public void should_not_upgrade_the_package() + public void Should_not_upgrade_the_package() { var packageFile = Path.Combine(Scenario.get_top_level(), "lib", "isdependency", "isdependency.nupkg"); using (var packageReader = new PackageArchiveReader(packageFile)) { - packageReader.NuspecReader.GetVersion().to_string().ShouldEqual("1.0.0"); + packageReader.NuspecReader.GetVersion().ToStringSafe().ShouldEqual("1.0.0"); } } [Fact] - public void should_not_upgrade_parent_package() + public void Should_not_upgrade_parent_package() { var packageFile = Path.Combine(Scenario.get_top_level(), "lib", "hasdependency", "hasdependency.nupkg"); using (var packageReader = new PackageArchiveReader(packageFile)) { - packageReader.NuspecReader.GetVersion().to_string().ShouldEqual("1.0.0"); + packageReader.NuspecReader.GetVersion().ToStringSafe().ShouldEqual("1.0.0"); } } [Fact] - public void should_not_upgrade_the_exact_version_dependency() + public void Should_not_upgrade_the_exact_version_dependency() { var packageFile = Path.Combine(Scenario.get_top_level(), "lib", "isexactversiondependency", "isexactversiondependency.nupkg"); using (var packageReader = new PackageArchiveReader(packageFile)) { - packageReader.NuspecReader.GetVersion().to_string().ShouldEqual("1.0.0"); + packageReader.NuspecReader.GetVersion().ToStringSafe().ShouldEqual("1.0.0"); } } [Fact] - public void should_contain_a_message_that_nothing_was_upgraded() + public void Should_contain_a_message_that_nothing_was_upgraded() { bool expectedMessage = false; - foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).or_empty_list_if_null()) + foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).OrEmpty()) { if (message.Contains("upgraded 0/1")) expectedMessage = true; } @@ -3639,7 +3673,7 @@ public void should_contain_a_message_that_nothing_was_upgraded() } [Fact] - public void should_have_an_error_package_result() + public void Should_have_an_error_package_result() { foreach (var packageResult in Results) { @@ -3648,7 +3682,7 @@ public void should_have_an_error_package_result() } [Fact] - public void should_not_have_inconclusive_package_result() + public void Should_not_have_inconclusive_package_result() { foreach (var packageResult in Results) { @@ -3657,7 +3691,7 @@ public void should_not_have_inconclusive_package_result() } [Fact] - public void should_not_have_warning_package_result() + public void Should_not_have_warning_package_result() { foreach (var packageResult in Results) { @@ -3666,10 +3700,10 @@ public void should_not_have_warning_package_result() } [Fact] - public void should_have_outputted_expected_error_message() + public void Should_have_outputted_expected_error_message() { bool expectedMessage = false; - foreach (var message in MockLogger.MessagesFor(LogLevel.Error).or_empty_list_if_null()) + foreach (var message in MockLogger.MessagesFor(LogLevel.Error).OrEmpty()) { if (message.Contains("Unable to resolve dependency chain. This may be caused by a parent package depending on this package, try specifying a specific version to use or don't ignore any dependencies!")) expectedMessage = true; } @@ -3678,7 +3712,7 @@ public void should_have_outputted_expected_error_message() } } - public class when_upgrading_a_package_with_config_transforms : ScenariosBase + public class When_upgrading_a_package_with_config_transforms : ScenariosBase { private PackageResult _packageResult; private string _xmlFilePath = string.Empty; @@ -3693,7 +3727,7 @@ public override void Context() public override void Because() { - Results = Service.upgrade_run(Configuration); + Results = Service.Upgrade(Configuration); _packageResult = Results.FirstOrDefault().Value; var xmlDocument = new XPathDocument(_xmlFilePath); @@ -3701,20 +3735,20 @@ public override void Because() } [Fact] - public void should_upgrade_the_package() + public void Should_upgrade_the_package() { var packageFile = Path.Combine(Scenario.get_top_level(), "lib", Configuration.PackageNames, Configuration.PackageNames + NuGetConstants.PackageExtension); using (var packageReader = new PackageArchiveReader(packageFile)) { - packageReader.NuspecReader.GetVersion().to_string().ShouldEqual("1.1.0"); + packageReader.NuspecReader.GetVersion().ToStringSafe().ShouldEqual("1.1.0"); } } [Fact] - public void should_contain_a_warning_message_that_it_upgraded_successfully() + public void Should_contain_a_warning_message_that_it_upgraded_successfully() { bool upgradedSuccessMessage = false; - foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).or_empty_list_if_null()) + foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).OrEmpty()) { if (message.Contains("upgraded 1/1")) upgradedSuccessMessage = true; } @@ -3723,25 +3757,28 @@ public void should_contain_a_warning_message_that_it_upgraded_successfully() } [Fact] - public void should_have_a_successful_package_result() + public void Should_have_a_successful_package_result() { _packageResult.Success.ShouldBeTrue(); } [Fact] - public void should_not_have_inconclusive_package_result() + public void Should_not_have_inconclusive_package_result() { _packageResult.Inconclusive.ShouldBeFalse(); } [Fact] - public void should_not_have_warning_package_result() + public void Should_not_have_warning_package_result_other_than_before_modify_failures() { - _packageResult.Warning.ShouldBeFalse(); + // For before modify scripts that fail, we add a warning message. + // So we will ignore any such warnings. + var messages = _packageResult.Messages.Where(m => m.MessageType == ResultType.Warn && !m.Message.ContainsSafe("chocolateyBeforeModify")); + messages.ShouldBeEmpty(); } [Fact] - public void should_match_the_upgrade_version_of_one_dot_one_dot_zero() + public void Should_match_the_upgrade_version_of_one_dot_one_dot_zero() { _packageResult.Version.ShouldEqual("1.1.0"); } @@ -3751,36 +3788,36 @@ public void should_match_the_upgrade_version_of_one_dot_one_dot_zero() // if we've determined that there is an xdt file [Fact] - public void should_not_change_the_test_value_in_the_config_from_original_one_dot_zero_dot_zero_due_to_upgrade_and_XDT_InsertIfMissing() + public void Should_not_change_the_test_value_in_the_config_from_original_one_dot_zero_dot_zero_due_to_upgrade_and_XDT_InsertIfMissing() { - _xPathNavigator.SelectSingleNode("//configuration/appSettings/add[@key='test']/@value").TypedValue.to_string().ShouldEqual("default 1.0.0"); + _xPathNavigator.SelectSingleNode("//configuration/appSettings/add[@key='test']/@value").TypedValue.ToStringSafe().ShouldEqual("default 1.0.0"); } [Fact] - public void should_change_the_testReplace_value_in_the_config_due_to_XDT_Replace() + public void Should_change_the_testReplace_value_in_the_config_due_to_XDT_Replace() { - _xPathNavigator.SelectSingleNode("//configuration/appSettings/add[@key='testReplace']/@value").TypedValue.to_string().ShouldEqual("1.1.0"); + _xPathNavigator.SelectSingleNode("//configuration/appSettings/add[@key='testReplace']/@value").TypedValue.ToStringSafe().ShouldEqual("1.1.0"); } [Fact] - public void should_not_change_the_insert_value_in_the_config_due_to_upgrade_and_XDT_InsertIfMissing() + public void Should_not_change_the_insert_value_in_the_config_due_to_upgrade_and_XDT_InsertIfMissing() { - _xPathNavigator.SelectSingleNode("//configuration/appSettings/add[@key='insert']/@value").TypedValue.to_string().ShouldEqual("1.0.0"); + _xPathNavigator.SelectSingleNode("//configuration/appSettings/add[@key='insert']/@value").TypedValue.ToStringSafe().ShouldEqual("1.0.0"); } [Fact] - public void should_add_the_insertNew_value_in_the_config_due_to_XDT_InsertIfMissing() + public void Should_add_the_insertNew_value_in_the_config_due_to_XDT_InsertIfMissing() { - _xPathNavigator.SelectSingleNode("//configuration/appSettings/add[@key='insertNew']/@value").TypedValue.to_string().ShouldEqual("1.1.0"); + _xPathNavigator.SelectSingleNode("//configuration/appSettings/add[@key='insertNew']/@value").TypedValue.ToStringSafe().ShouldEqual("1.1.0"); } } - public class when_upgrading_a_package_with_config_transforms_when_config_was_edited : ScenariosBase + public class When_upgrading_a_package_with_config_transforms_when_config_was_edited : ScenariosBase { private PackageResult _packageResult; private string _xmlFilePath = string.Empty; private XPathNavigator _xPathNavigator; - private const string COMMENT_ADDED = ""; + private const string CommentAdded = ""; public override void Context() { @@ -3788,12 +3825,12 @@ public override void Context() _xmlFilePath = Path.Combine(Scenario.get_top_level(), "lib", Configuration.PackageNames, "tools", "console.exe.config"); - File.WriteAllText(_xmlFilePath, File.ReadAllText(_xmlFilePath) + COMMENT_ADDED); + File.WriteAllText(_xmlFilePath, File.ReadAllText(_xmlFilePath) + CommentAdded); } public override void Because() { - Results = Service.upgrade_run(Configuration); + Results = Service.Upgrade(Configuration); _packageResult = Results.FirstOrDefault().Value; var xmlDocument = new XPathDocument(_xmlFilePath); @@ -3801,20 +3838,20 @@ public override void Because() } [Fact] - public void should_upgrade_the_package() + public void Should_upgrade_the_package() { var packageFile = Path.Combine(Scenario.get_top_level(), "lib", Configuration.PackageNames, Configuration.PackageNames + NuGetConstants.PackageExtension); using (var packageReader = new PackageArchiveReader(packageFile)) { - packageReader.NuspecReader.GetVersion().to_string().ShouldEqual("1.1.0"); + packageReader.NuspecReader.GetVersion().ToStringSafe().ShouldEqual("1.1.0"); } } [Fact] - public void should_contain_a_warning_message_that_it_upgraded_successfully() + public void Should_contain_a_warning_message_that_it_upgraded_successfully() { bool upgradedSuccessMessage = false; - foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).or_empty_list_if_null()) + foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).OrEmpty()) { if (message.Contains("upgraded 1/1")) upgradedSuccessMessage = true; } @@ -3823,25 +3860,28 @@ public void should_contain_a_warning_message_that_it_upgraded_successfully() } [Fact] - public void should_have_a_successful_package_result() + public void Should_have_a_successful_package_result() { _packageResult.Success.ShouldBeTrue(); } [Fact] - public void should_not_have_inconclusive_package_result() + public void Should_not_have_inconclusive_package_result() { _packageResult.Inconclusive.ShouldBeFalse(); } [Fact] - public void should_not_have_warning_package_result() + public void Should_not_have_warning_package_result_other_than_before_modify_failures() { - _packageResult.Warning.ShouldBeFalse(); + // For before modify scripts that fail, we add a warning message. + // So we will ignore any such warnings. + var messages = _packageResult.Messages.Where(m => m.MessageType == ResultType.Warn && !m.Message.ContainsSafe("chocolateyBeforeModify")); + messages.ShouldBeEmpty(); } [Fact] - public void should_match_the_upgrade_version_of_one_dot_one_dot_zero() + public void Should_match_the_upgrade_version_of_one_dot_one_dot_zero() { _packageResult.Version.ShouldEqual("1.1.0"); } @@ -3851,37 +3891,37 @@ public void should_match_the_upgrade_version_of_one_dot_one_dot_zero() // if we've determined that there is an xdt file [Fact] - public void should_not_change_the_test_value_in_the_config_from_original_one_dot_zero_dot_zero_due_to_upgrade_and_XDT_InsertIfMissing() + public void Should_not_change_the_test_value_in_the_config_from_original_one_dot_zero_dot_zero_due_to_upgrade_and_XDT_InsertIfMissing() { - _xPathNavigator.SelectSingleNode("//configuration/appSettings/add[@key='test']/@value").TypedValue.to_string().ShouldEqual("default 1.0.0"); + _xPathNavigator.SelectSingleNode("//configuration/appSettings/add[@key='test']/@value").TypedValue.ToStringSafe().ShouldEqual("default 1.0.0"); } [Fact] - public void should_change_the_testReplace_value_in_the_config_due_to_XDT_Replace() + public void Should_change_the_testReplace_value_in_the_config_due_to_XDT_Replace() { - _xPathNavigator.SelectSingleNode("//configuration/appSettings/add[@key='testReplace']/@value").TypedValue.to_string().ShouldEqual("1.1.0"); + _xPathNavigator.SelectSingleNode("//configuration/appSettings/add[@key='testReplace']/@value").TypedValue.ToStringSafe().ShouldEqual("1.1.0"); } [Fact] - public void should_not_change_the_insert_value_in_the_config_due_to_upgrade_and_XDT_InsertIfMissing() + public void Should_not_change_the_insert_value_in_the_config_due_to_upgrade_and_XDT_InsertIfMissing() { - _xPathNavigator.SelectSingleNode("//configuration/appSettings/add[@key='insert']/@value").TypedValue.to_string().ShouldEqual("1.0.0"); + _xPathNavigator.SelectSingleNode("//configuration/appSettings/add[@key='insert']/@value").TypedValue.ToStringSafe().ShouldEqual("1.0.0"); } [Fact] - public void should_add_the_insertNew_value_in_the_config_due_to_XDT_InsertIfMissing() + public void Should_add_the_insertNew_value_in_the_config_due_to_XDT_InsertIfMissing() { - _xPathNavigator.SelectSingleNode("//configuration/appSettings/add[@key='insertNew']/@value").TypedValue.to_string().ShouldEqual("1.1.0"); + _xPathNavigator.SelectSingleNode("//configuration/appSettings/add[@key='insertNew']/@value").TypedValue.ToStringSafe().ShouldEqual("1.1.0"); } [Fact] - public void should_have_a_config_with_the_comment_from_the_original() + public void Should_have_a_config_with_the_comment_from_the_original() { - File.ReadAllText(_xmlFilePath).ShouldContain(COMMENT_ADDED); + File.ReadAllText(_xmlFilePath).ShouldContain(CommentAdded); } } - public class when_upgrading_a_package_with_no_sources_enabled : ScenariosBase + public class When_upgrading_a_package_with_no_sources_enabled : ScenariosBase { public override void Context() { @@ -3891,23 +3931,23 @@ public override void Context() public override void Because() { - Results = Service.upgrade_run(Configuration); + Results = Service.Upgrade(Configuration); } [Fact] - public void should_have_no_sources_enabled_result() + public void Should_have_no_sources_enabled_result() { - MockLogger.contains_message("Upgrading was NOT successful. There are no sources enabled for", LogLevel.Error).ShouldBeTrue(); + MockLogger.ContainsMessage("Upgrading was NOT successful. There are no sources enabled for", LogLevel.Error).ShouldBeTrue(); } [Fact] - public void should_not_have_any_packages_upgraded() + public void Should_not_have_any_packages_upgraded() { Results.Count().ShouldEqual(0); } } - public class when_upgrading_all_packages_happy_path : ScenariosBase + public class When_upgrading_all_packages_happy_path : ScenariosBase { public override void Context() { @@ -3917,17 +3957,17 @@ public override void Context() public override void Because() { - Results = Service.upgrade_run(Configuration); + Results = Service.Upgrade(Configuration); } [Fact] - public void should_report_for_all_installed_packages() + public void Should_report_for_all_installed_packages() { Results.Count().ShouldEqual(3); } [Fact] - public void should_upgrade_packages_with_upgrades() + public void Should_upgrade_packages_with_upgrades() { var upgradePackageResult = Results.Where(x => x.Key == "upgradepackage").ToList(); upgradePackageResult.Count.ShouldEqual(1, "upgradepackage must be there once"); @@ -3935,7 +3975,7 @@ public void should_upgrade_packages_with_upgrades() } [Fact] - public void should_skip_packages_without_upgrades() + public void Should_skip_packages_without_upgrades() { var installPackageResult = Results.Where(x => x.Key == "installpackage").ToList(); installPackageResult.Count.ShouldEqual(1, "installpackage must be there once"); @@ -3943,7 +3983,7 @@ public void should_skip_packages_without_upgrades() } } - public class when_upgrading_all_packages_with_prereleases_installed : ScenariosBase + public class When_upgrading_all_packages_with_prereleases_installed : ScenariosBase { public override void Context() { @@ -3956,17 +3996,17 @@ public override void Context() public override void Because() { - Results = Service.upgrade_run(Configuration); + Results = Service.Upgrade(Configuration); } [Fact] - public void should_report_for_all_installed_packages() + public void Should_report_for_all_installed_packages() { Results.Count().ShouldEqual(3); } [Fact] - public void should_upgrade_packages_with_upgrades() + public void Should_upgrade_packages_with_upgrades() { var upgradePackageResult = Results.Where(x => x.Key == "upgradepackage").ToList(); upgradePackageResult.Count.ShouldEqual(1, "upgradepackage must be there once"); @@ -3974,20 +4014,20 @@ public void should_upgrade_packages_with_upgrades() } [Fact] - public void should_upgrade_upgradepackage() + public void Should_upgrade_upgradepackage() { var packageFile = Path.Combine(Scenario.get_top_level(), "lib", "upgradepackage", "upgradepackage" + NuGetConstants.PackageExtension); using (var packageReader = new PackageArchiveReader(packageFile)) { var version = packageReader.NuspecReader.GetVersion(); - version.Version.to_string().ShouldEqual("1.1.1.0"); + version.Version.ToStringSafe().ShouldEqual("1.1.1.0"); version.OriginalVersion.ShouldEqual("1.1.1-beta2"); - version.to_string().ShouldEqual("1.1.1-beta2"); + version.ToStringSafe().ShouldEqual("1.1.1-beta2"); } } [Fact] - public void should_skip_packages_without_upgrades() + public void Should_skip_packages_without_upgrades() { var installPackageResult = Results.Where(x => x.Key == "installpackage").ToList(); installPackageResult.Count.ShouldEqual(1, "installpackage must be there once"); @@ -3995,7 +4035,7 @@ public void should_skip_packages_without_upgrades() } } - public class when_upgrading_all_packages_with_prereleases_installed_with_excludeprerelease_specified : ScenariosBase + public class When_upgrading_all_packages_with_prereleases_installed_with_excludeprerelease_specified : ScenariosBase { public override void Context() { @@ -4010,17 +4050,17 @@ public override void Context() public override void Because() { - Results = Service.upgrade_run(Configuration); + Results = Service.Upgrade(Configuration); } [Fact] - public void should_report_for_all_installed_packages() + public void Should_report_for_all_installed_packages() { Results.Count().ShouldEqual(3); } [Fact] - public void should_upgrade_packages_with_upgrades() + public void Should_upgrade_packages_with_upgrades() { var upgradePackageResult = Results.Where(x => x.Key == "upgradepackage").ToList(); upgradePackageResult.Count.ShouldEqual(1, "upgradepackage must be there once"); @@ -4029,20 +4069,20 @@ public void should_upgrade_packages_with_upgrades() } [Fact] - public void should_not_upgrade_upgradepackage() + public void Should_not_upgrade_upgradepackage() { var packageFile = Path.Combine(Scenario.get_top_level(), "lib", "upgradepackage", "upgradepackage" + NuGetConstants.PackageExtension); using (var packageReader = new PackageArchiveReader(packageFile)) { var version = packageReader.NuspecReader.GetVersion(); - version.Version.to_string().ShouldEqual("1.1.1.0"); + version.Version.ToStringSafe().ShouldEqual("1.1.1.0"); version.OriginalVersion.ShouldEqual("1.1.1-beta"); - version.to_string().ShouldEqual("1.1.1-beta"); + version.ToStringSafe().ShouldEqual("1.1.1-beta"); } } [Fact] - public void should_skip_packages_without_upgrades() + public void Should_skip_packages_without_upgrades() { var installPackageResult = Results.Where(x => x.Key == "installpackage").ToList(); installPackageResult.Count.ShouldEqual(1, "installpackage must be there once"); @@ -4051,7 +4091,7 @@ public void should_skip_packages_without_upgrades() } [Categories.SemVer20] - public class when_upgrading_package_to_an_explicit_semver_2_0_version : ScenariosBase + public class When_upgrading_package_to_an_explicit_semver_2_0_version : ScenariosBase { private PackageResult _packageResult; @@ -4065,24 +4105,24 @@ public override void Context() public override void Because() { - Results = Service.upgrade_run(Configuration); + Results = Service.Upgrade(Configuration); _packageResult = Results.Select(r => r.Value).FirstOrDefault(); } [Fact] - public void should_have_a_single_package_result() + public void Should_have_a_single_package_result() { Results.Count.ShouldEqual(1, "The returned package results do not have a single value!"); } [Fact] - public void should_upgrade_where_install_location_reports() + public void Should_upgrade_where_install_location_reports() { DirectoryAssert.Exists(_packageResult.InstallLocation); } [Fact] - public void should_upgrade_a_package_in_the_lib_directory() + public void Should_upgrade_a_package_in_the_lib_directory() { var packageDir = Path.Combine(Scenario.get_top_level(), "lib", Configuration.PackageNames); @@ -4090,7 +4130,7 @@ public void should_upgrade_a_package_in_the_lib_directory() } [Fact] - public void should_delete_the_rollback() + public void Should_delete_the_rollback() { var packageDir = Path.Combine(Scenario.get_top_level(), "lib-bkp", Configuration.PackageNames); @@ -4098,7 +4138,7 @@ public void should_delete_the_rollback() } [Fact] - public void should_contain_newer_version_in_directory() + public void Should_contain_newer_version_in_directory() { var shimFile = Path.Combine(Scenario.get_top_level(), "lib", Configuration.PackageNames, "tools", "console.exe"); @@ -4108,20 +4148,20 @@ public void should_contain_newer_version_in_directory() } [Fact] - public void should_upgrade_the_package() + public void Should_upgrade_the_package() { var packageFile = Path.Combine(Scenario.get_top_level(), "lib", Configuration.PackageNames, Configuration.PackageNames + NuGetConstants.PackageExtension); using (var packageReader = new PackageArchiveReader(packageFile)) { - packageReader.NuspecReader.GetVersion().to_string().ShouldEqual("1.1.1-beta.1"); + packageReader.NuspecReader.GetVersion().ToStringSafe().ShouldEqual("1.1.1-beta.1"); } } [Fact] - public void should_contain_a_warning_message_that_it_upgraded_successfully() + public void Should_contain_a_warning_message_that_it_upgraded_successfully() { bool upgradedSuccessMessage = false; - foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).or_empty_list_if_null()) + foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).OrEmpty()) { if (message.Contains("upgraded 1/1")) upgradedSuccessMessage = true; } @@ -4130,10 +4170,10 @@ public void should_contain_a_warning_message_that_it_upgraded_successfully() } [Fact] - public void should_contain_a_warning_message_with_old_and_new_versions() + public void Should_contain_a_warning_message_with_old_and_new_versions() { bool upgradeMessage = false; - foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).or_empty_list_if_null()) + foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).OrEmpty()) { if (message.Contains("You have upgradepackage v1.0.0 installed. Version 1.1.1-beta.1 is available based on your source")) upgradeMessage = true; } @@ -4142,31 +4182,34 @@ public void should_contain_a_warning_message_with_old_and_new_versions() } [Fact] - public void should_have_a_successful_package_result() + public void Should_have_a_successful_package_result() { _packageResult.Success.ShouldBeTrue(); } [Fact] - public void should_not_have_inconclusive_package_result() + public void Should_not_have_inconclusive_package_result() { _packageResult.Inconclusive.ShouldBeFalse(); } [Fact] - public void should_not_have_warning_package_result() + public void Should_not_have_warning_package_result_other_than_before_modify_failures() { - _packageResult.Warning.ShouldBeFalse(); + // For before modify scripts that fail, we add a warning message. + // So we will ignore any such warnings. + var messages = _packageResult.Messages.Where(m => m.MessageType == ResultType.Warn && !m.Message.ContainsSafe("chocolateyBeforeModify")); + messages.ShouldBeEmpty(); } [Fact] - public void config_should_match_package_result_name() + public void Config_should_match_package_result_name() { _packageResult.Name.ShouldEqual(Configuration.PackageNames); } [Fact] - public void should_match_the_upgrade_version_of_one_dot_one_dot_zero() + public void Should_match_the_upgrade_version_of_one_dot_one_dot_zero() { _packageResult.Version.ShouldEqual("1.1.1-beta.1"); } @@ -4174,46 +4217,46 @@ public void should_match_the_upgrade_version_of_one_dot_one_dot_zero() [Fact] [WindowsOnly] [Platform(Exclude = "Mono")] - public void should_have_executed_chocolateyBeforeModify_script_for_original_package() + public void Should_have_executed_chocolateyBeforeModify_script_for_original_package() { - MockLogger.contains_message("upgradepackage 1.0.0 Before Modification", LogLevel.Info).ShouldBeTrue(); + MockLogger.ContainsMessage("upgradepackage 1.0.0 Before Modification", LogLevel.Info).ShouldBeTrue(); } [Fact] [WindowsOnly] [Platform(Exclude = "Mono")] - public void should_have_executed_chocolateyBeforeModify_before_chocolateyInstall() + public void Should_have_executed_chocolateyBeforeModify_before_chocolateyInstall() { - MockLogger.MessagesFor(LogLevel.Info).or_empty_list_if_null() + MockLogger.MessagesFor(LogLevel.Info).OrEmpty() .SkipWhile(p => !p.Contains("upgradepackage 1.0.0 Before Modification")) .Any(p => p.EndsWith("upgradepackage 1.1.1-beta.1 Installed")) .ShouldBeTrue(); } [Fact] - public void should_not_have_executed_chocolateyUninstall_script_for_original_package() + public void Should_not_have_executed_chocolateyUninstall_script_for_original_package() { - MockLogger.contains_message("upgradepackage 1.0.0 Uninstalled", LogLevel.Info).ShouldBeFalse(); + MockLogger.ContainsMessage("upgradepackage 1.0.0 Uninstalled", LogLevel.Info).ShouldBeFalse(); } [Fact] - public void should_not_have_executed_chocolateyBeforeModify_script_for_new_package() + public void Should_not_have_executed_chocolateyBeforeModify_script_for_new_package() { - MockLogger.contains_message("upgradepackage 1.1.0 Before Modification", LogLevel.Info).ShouldBeFalse(); + MockLogger.ContainsMessage("upgradepackage 1.1.0 Before Modification", LogLevel.Info).ShouldBeFalse(); } [Fact] [WindowsOnly] [Platform(Exclude = "Mono")] - public void should_have_executed_chocolateyInstall_script_for_new_package() + public void Should_have_executed_chocolateyInstall_script_for_new_package() { const string expectedMessage = "upgradepackage 1.1.1-beta.1 Installed"; - MockLogger.contains_message(expectedMessage, LogLevel.Info).ShouldBeTrue("No log message containing the sentence '{0}' could be found!".format_with(expectedMessage)); + MockLogger.ContainsMessage(expectedMessage, LogLevel.Info).ShouldBeTrue("No log message containing the sentence '{0}' could be found!".FormatWith(expectedMessage)); } } - public class when_upgrading_all_packages_with_except : ScenariosBase + public class When_upgrading_all_packages_with_except : ScenariosBase { public override void Context() { @@ -4224,25 +4267,25 @@ public override void Context() public override void Because() { - Results = Service.upgrade_run(Configuration); + Results = Service.Upgrade(Configuration); } [Fact] - public void should_report_for_all_non_skipped_packages() + public void Should_report_for_all_non_skipped_packages() { Results.Count().ShouldEqual(1); Results.First().Key.ShouldEqual("installpackage"); } [Fact] - public void should_skip_packages_in_except_list() + public void Should_skip_packages_in_except_list() { var upgradePackageResult = Results.Where(x => x.Key == "upgradepackage").ToList(); upgradePackageResult.Count.ShouldEqual(0, "upgradepackage should not be in the results list"); } } - public class when_upgrading_an_existing_hook_package : ScenariosBase + public class When_upgrading_an_existing_hook_package : ScenariosBase { private PackageResult _packageResult; @@ -4257,18 +4300,18 @@ public override void Context() public override void Because() { - Results = Service.upgrade_run(Configuration); + Results = Service.Upgrade(Configuration); _packageResult = Results.FirstOrDefault().Value; } [Fact] - public void should_upgrade_where_install_location_reports() + public void Should_upgrade_where_install_location_reports() { DirectoryAssert.Exists(_packageResult.InstallLocation); } [Fact] - public void should_upgrade_a_package_in_the_lib_directory() + public void Should_upgrade_a_package_in_the_lib_directory() { var packageDir = Path.Combine(Scenario.get_top_level(), "lib", Configuration.PackageNames); @@ -4276,7 +4319,7 @@ public void should_upgrade_a_package_in_the_lib_directory() } [Fact] - public void should_delete_the_rollback() + public void Should_delete_the_rollback() { var packageDir = Path.Combine(Scenario.get_top_level(), "lib-bkp", Configuration.PackageNames); @@ -4284,20 +4327,20 @@ public void should_delete_the_rollback() } [Fact] - public void should_upgrade_the_package() + public void Should_upgrade_the_package() { var packageFile = Path.Combine(Scenario.get_top_level(), "lib", Configuration.PackageNames, Configuration.PackageNames + NuGetConstants.PackageExtension); using (var packageReader = new PackageArchiveReader(packageFile)) { - packageReader.NuspecReader.GetVersion().to_string().ShouldEqual("2.0.0"); + packageReader.NuspecReader.GetVersion().ToStringSafe().ShouldEqual("2.0.0"); } } [Fact] - public void should_contain_a_warning_message_that_it_upgraded_successfully() + public void Should_contain_a_warning_message_that_it_upgraded_successfully() { bool upgradedSuccessMessage = false; - foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).or_empty_list_if_null()) + foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).OrEmpty()) { if (message.Contains("upgraded 1/1")) upgradedSuccessMessage = true; } @@ -4306,10 +4349,10 @@ public void should_contain_a_warning_message_that_it_upgraded_successfully() } [Fact] - public void should_contain_a_warning_message_with_old_and_new_versions() + public void Should_contain_a_warning_message_with_old_and_new_versions() { bool upgradeMessage = false; - foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).or_empty_list_if_null()) + foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).OrEmpty()) { if (message.Contains("You have scriptpackage.hook v1.0.0 installed. Version 2.0.0 is available based on your source")) upgradeMessage = true; } @@ -4318,37 +4361,37 @@ public void should_contain_a_warning_message_with_old_and_new_versions() } [Fact] - public void should_have_a_successful_package_result() + public void Should_have_a_successful_package_result() { _packageResult.Success.ShouldBeTrue(); } [Fact] - public void should_not_have_inconclusive_package_result() + public void Should_not_have_inconclusive_package_result() { _packageResult.Inconclusive.ShouldBeFalse(); } [Fact] - public void should_not_have_warning_package_result() + public void Should_not_have_warning_package_result() { _packageResult.Warning.ShouldBeFalse(); } [Fact] - public void config_should_match_package_result_name() + public void Config_should_match_package_result_name() { _packageResult.Name.ShouldEqual(Configuration.PackageNames); } [Fact] - public void should_match_the_upgrade_version_of_two_dot_zero_dot_zero() + public void Should_match_the_upgrade_version_of_two_dot_zero_dot_zero() { _packageResult.Version.ShouldEqual("2.0.0"); } [Fact] - public void should_have_a_hooks_folder_for_the_package() + public void Should_have_a_hooks_folder_for_the_package() { var hooksDirectory = Path.Combine(Scenario.get_top_level(), "hooks", Configuration.PackageNames.Replace(".hook", string.Empty)); @@ -4356,7 +4399,7 @@ public void should_have_a_hooks_folder_for_the_package() } [Fact] - public void should_install_hook_scripts_to_folder() + public void Should_install_hook_scripts_to_folder() { var hookScripts = new List { "pre-install-all.ps1", "post-install-all.ps1", "pre-upgrade-all.ps1", "post-upgrade-all.ps1", "pre-uninstall-all.ps1", "post-uninstall-all.ps1" }; foreach (string scriptName in hookScripts) @@ -4367,21 +4410,21 @@ public void should_install_hook_scripts_to_folder() } [Fact] - public void should_remove_files_not_in_upgrade_version() + public void Should_remove_files_not_in_upgrade_version() { var hookScriptPath = Path.Combine(Scenario.get_top_level(), "hooks", Configuration.PackageNames.Replace(".hook", string.Empty), "pre-install-doesnotexist.ps1"); FileAssert.DoesNotExist(hookScriptPath); } [Fact] - public void should_install_new_files_in_upgrade_version() + public void Should_install_new_files_in_upgrade_version() { var hookScriptPath = Path.Combine(Scenario.get_top_level(), "hooks", Configuration.PackageNames.Replace(".hook", string.Empty), "post-install-doesnotexist.ps1"); FileAssert.Exists(hookScriptPath); } } - public class when_upgrading_an_existing_package_happy_path_with_hooks : ScenariosBase + public class When_upgrading_an_existing_package_happy_path_with_hooks : ScenariosBase { private PackageResult _packageResult; @@ -4395,18 +4438,18 @@ public override void Context() public override void Because() { - Results = Service.upgrade_run(Configuration); + Results = Service.Upgrade(Configuration); _packageResult = Results.FirstOrDefault().Value; } [Fact] - public void should_upgrade_where_install_location_reports() + public void Should_upgrade_where_install_location_reports() { DirectoryAssert.Exists(_packageResult.InstallLocation); } [Fact] - public void should_upgrade_a_package_in_the_lib_directory() + public void Should_upgrade_a_package_in_the_lib_directory() { var packageDir = Path.Combine(Scenario.get_top_level(), "lib", Configuration.PackageNames); @@ -4414,7 +4457,7 @@ public void should_upgrade_a_package_in_the_lib_directory() } [Fact] - public void should_delete_the_rollback() + public void Should_delete_the_rollback() { var packageDir = Path.Combine(Scenario.get_top_level(), "lib-bkp", Configuration.PackageNames); @@ -4422,7 +4465,7 @@ public void should_delete_the_rollback() } [Fact] - public void should_contain_newer_version_in_directory() + public void Should_contain_newer_version_in_directory() { var shimFile = Path.Combine(Scenario.get_top_level(), "lib", Configuration.PackageNames, "tools", "console.exe"); @@ -4430,20 +4473,20 @@ public void should_contain_newer_version_in_directory() } [Fact] - public void should_upgrade_the_package() + public void Should_upgrade_the_package() { var packageFile = Path.Combine(Scenario.get_top_level(), "lib", Configuration.PackageNames, Configuration.PackageNames + NuGetConstants.PackageExtension); using (var packageReader = new PackageArchiveReader(packageFile)) { - packageReader.NuspecReader.GetVersion().to_string().ShouldEqual("1.1.0"); + packageReader.NuspecReader.GetVersion().ToStringSafe().ShouldEqual("1.1.0"); } } [Fact] - public void should_contain_a_warning_message_that_it_upgraded_successfully() + public void Should_contain_a_warning_message_that_it_upgraded_successfully() { bool upgradedSuccessMessage = false; - foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).or_empty_list_if_null()) + foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).OrEmpty()) { if (message.Contains("upgraded 1/1")) upgradedSuccessMessage = true; } @@ -4452,10 +4495,10 @@ public void should_contain_a_warning_message_that_it_upgraded_successfully() } [Fact] - public void should_contain_a_warning_message_with_old_and_new_versions() + public void Should_contain_a_warning_message_with_old_and_new_versions() { bool upgradeMessage = false; - foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).or_empty_list_if_null()) + foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).OrEmpty()) { if (message.Contains("You have upgradepackage v1.0.0 installed. Version 1.1.0 is available based on your source")) upgradeMessage = true; } @@ -4464,31 +4507,34 @@ public void should_contain_a_warning_message_with_old_and_new_versions() } [Fact] - public void should_have_a_successful_package_result() + public void Should_have_a_successful_package_result() { _packageResult.Success.ShouldBeTrue(); } [Fact] - public void should_not_have_inconclusive_package_result() + public void Should_not_have_inconclusive_package_result() { _packageResult.Inconclusive.ShouldBeFalse(); } [Fact] - public void should_not_have_warning_package_result() + public void Should_not_have_warning_package_result_other_than_before_modify_failures() { - _packageResult.Warning.ShouldBeFalse(); + // For before modify scripts that fail, we add a warning message. + // So we will ignore any such warnings. + var messages = _packageResult.Messages.Where(m => m.MessageType == ResultType.Warn && !m.Message.ContainsSafe("chocolateyBeforeModify")); + messages.ShouldBeEmpty(); } [Fact] - public void config_should_match_package_result_name() + public void Config_should_match_package_result_name() { _packageResult.Name.ShouldEqual(Configuration.PackageNames); } [Fact] - public void should_match_the_upgrade_version_of_one_dot_one_dot_zero() + public void Should_match_the_upgrade_version_of_one_dot_one_dot_zero() { _packageResult.Version.ShouldEqual("1.1.0"); } @@ -4496,107 +4542,107 @@ public void should_match_the_upgrade_version_of_one_dot_one_dot_zero() [Fact] [WindowsOnly] [Platform(Exclude = "Mono")] - public void should_have_executed_chocolateyBeforeModify_script_for_original_package() + public void Should_have_executed_chocolateyBeforeModify_script_for_original_package() { - MockLogger.contains_message("upgradepackage 1.0.0 Before Modification", LogLevel.Info).ShouldBeTrue(); + MockLogger.ContainsMessage("upgradepackage 1.0.0 Before Modification", LogLevel.Info).ShouldBeTrue(); } [Fact] [WindowsOnly] [Platform(Exclude = "Mono")] - public void should_have_executed_chocolateyBeforeModify_before_chocolateyInstall() + public void Should_have_executed_chocolateyBeforeModify_before_chocolateyInstall() { - MockLogger.MessagesFor(LogLevel.Info).or_empty_list_if_null() + MockLogger.MessagesFor(LogLevel.Info).OrEmpty() .SkipWhile(p => !p.Contains("upgradepackage 1.0.0 Before Modification")) .Any(p => p.EndsWith("upgradepackage 1.1.0 Installed")) .ShouldBeTrue(); } [Fact] - public void should_not_have_executed_chocolateyUninstall_script_for_original_package() + public void Should_not_have_executed_chocolateyUninstall_script_for_original_package() { - MockLogger.contains_message("upgradepackage 1.0.0 Uninstalled", LogLevel.Info).ShouldBeFalse(); + MockLogger.ContainsMessage("upgradepackage 1.0.0 Uninstalled", LogLevel.Info).ShouldBeFalse(); } [Fact] - public void should_not_have_executed_chocolateyBeforeModify_script_for_new_package() + public void Should_not_have_executed_chocolateyBeforeModify_script_for_new_package() { - MockLogger.contains_message("upgradepackage 1.1.0 Before Modification", LogLevel.Info).ShouldBeFalse(); + MockLogger.ContainsMessage("upgradepackage 1.1.0 Before Modification", LogLevel.Info).ShouldBeFalse(); } [Fact] [WindowsOnly] [Platform(Exclude = "Mono")] - public void should_have_executed_chocolateyInstall_script_for_new_package() + public void Should_have_executed_chocolateyInstall_script_for_new_package() { - MockLogger.contains_message("upgradepackage 1.1.0 Installed", LogLevel.Info).ShouldBeTrue(); + MockLogger.ContainsMessage("upgradepackage 1.1.0 Installed", LogLevel.Info).ShouldBeTrue(); } [Fact] [WindowsOnly] [Platform(Exclude = "Mono")] - public void should_have_executed_pre_all_hook_script() + public void Should_have_executed_pre_all_hook_script() { - MockLogger.contains_message("pre-install-all.ps1 hook ran for upgradepackage 1.1.0", LogLevel.Info).ShouldBeTrue(); + MockLogger.ContainsMessage("pre-install-all.ps1 hook ran for upgradepackage 1.1.0", LogLevel.Info).ShouldBeTrue(); } [Fact] [WindowsOnly] [Platform(Exclude = "Mono")] - public void should_have_executed_post_all_hook_script() + public void Should_have_executed_post_all_hook_script() { - MockLogger.contains_message("post-install-all.ps1 hook ran for upgradepackage 1.1.0", LogLevel.Info).ShouldBeTrue(); + MockLogger.ContainsMessage("post-install-all.ps1 hook ran for upgradepackage 1.1.0", LogLevel.Info).ShouldBeTrue(); } [Fact] [WindowsOnly] [Platform(Exclude = "Mono")] - public void should_have_executed_pre_upgradepackage_hook_script() + public void Should_have_executed_pre_upgradepackage_hook_script() { - MockLogger.contains_message("pre-install-upgradepackage.ps1 hook ran for upgradepackage 1.1.0", LogLevel.Info).ShouldBeTrue(); + MockLogger.ContainsMessage("pre-install-upgradepackage.ps1 hook ran for upgradepackage 1.1.0", LogLevel.Info).ShouldBeTrue(); } [Fact] [WindowsOnly] [Platform(Exclude = "Mono")] - public void should_have_executed_post_upgradepackage_hook_script() + public void Should_have_executed_post_upgradepackage_hook_script() { - MockLogger.contains_message("post-install-upgradepackage.ps1 hook ran for upgradepackage 1.1.0", LogLevel.Info).ShouldBeTrue(); + MockLogger.ContainsMessage("post-install-upgradepackage.ps1 hook ran for upgradepackage 1.1.0", LogLevel.Info).ShouldBeTrue(); } [Fact] [WindowsOnly] [Platform(Exclude = "Mono")] - public void should_not_have_executed_uninstall_hook_script() + public void Should_not_have_executed_uninstall_hook_script() { - MockLogger.contains_message("post-uninstall-all.ps1 hook ran for upgradepackage 1.1.0", LogLevel.Info).ShouldBeFalse(); + MockLogger.ContainsMessage("post-uninstall-all.ps1 hook ran for upgradepackage 1.1.0", LogLevel.Info).ShouldBeFalse(); } [Fact] [WindowsOnly] [Platform(Exclude = "Mono")] - public void should_not_have_executed_installpackage_hook_script() + public void Should_not_have_executed_installpackage_hook_script() { - MockLogger.contains_message("pre-install-installpackage.ps1 hook ran for upgradepackage 1.1.0", LogLevel.Info).ShouldBeFalse(); + MockLogger.ContainsMessage("pre-install-installpackage.ps1 hook ran for upgradepackage 1.1.0", LogLevel.Info).ShouldBeFalse(); } [Fact] [WindowsOnly] [Platform(Exclude = "Mono")] - public void should_have_executed_beforemodify_hook_script_for_previous_version() + public void Should_have_executed_beforemodify_hook_script_for_previous_version() { - MockLogger.contains_message("pre-beforemodify-all.ps1 hook ran for upgradepackage 1.0.0", LogLevel.Info).ShouldBeTrue(); + MockLogger.ContainsMessage("pre-beforemodify-all.ps1 hook ran for upgradepackage 1.0.0", LogLevel.Info).ShouldBeTrue(); } [Fact] [WindowsOnly] [Platform(Exclude = "Mono")] - public void should_not_have_executed_beforemodify_hook_script_for_upgrade_version() + public void Should_not_have_executed_beforemodify_hook_script_for_upgrade_version() { - MockLogger.contains_message("pre-beforemodify-all.ps1 hook ran for upgradepackage 1.1.0", LogLevel.Info).ShouldBeFalse(); + MockLogger.ContainsMessage("pre-beforemodify-all.ps1 hook ran for upgradepackage 1.1.0", LogLevel.Info).ShouldBeFalse(); } } - public class when_upgrading_an_existing_package_with_uppercase_id : ScenariosBase + public class When_upgrading_an_existing_package_with_uppercase_id : ScenariosBase { private PackageResult _packageResult; @@ -4611,25 +4657,25 @@ public override void Context() public override void Because() { - Results = Service.upgrade_run(Configuration); + Results = Service.Upgrade(Configuration); _packageResult = Results.FirstOrDefault().Value; } [Fact] - public void should_have_the_correct_casing_for_the_nuspec() + public void Should_have_the_correct_casing_for_the_nuspec() { var nuspecFile = Path.Combine(Scenario.get_top_level(), "lib", Configuration.PackageNames, Configuration.PackageNames + NuGetConstants.ManifestExtension); FileAssert.Exists(nuspecFile); } [Fact] - public void should_upgrade_where_install_location_reports() + public void Should_upgrade_where_install_location_reports() { DirectoryAssert.Exists(_packageResult.InstallLocation); } [Fact] - public void should_upgrade_a_package_in_the_lib_directory() + public void Should_upgrade_a_package_in_the_lib_directory() { var packageDir = Path.Combine(Scenario.get_top_level(), "lib", Configuration.PackageNames); @@ -4637,20 +4683,20 @@ public void should_upgrade_a_package_in_the_lib_directory() } [Fact] - public void should_upgrade_the_package() + public void Should_upgrade_the_package() { var packageFile = Path.Combine(Scenario.get_top_level(), "lib", Configuration.PackageNames, Configuration.PackageNames + NuGetConstants.PackageExtension); using (var packageReader = new PackageArchiveReader(packageFile)) { - packageReader.NuspecReader.GetVersion().to_string().ShouldEqual("1.1.0"); + packageReader.NuspecReader.GetVersion().ToStringSafe().ShouldEqual("1.1.0"); } } [Fact] - public void should_contain_a_warning_message_that_it_upgraded_successfully() + public void Should_contain_a_warning_message_that_it_upgraded_successfully() { bool upgradedSuccessMessage = false; - foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).or_empty_list_if_null()) + foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).OrEmpty()) { if (message.Contains("upgraded 1/1")) upgradedSuccessMessage = true; } @@ -4659,10 +4705,10 @@ public void should_contain_a_warning_message_that_it_upgraded_successfully() } [Fact] - public void should_contain_a_warning_message_with_old_and_new_versions() + public void Should_contain_a_warning_message_with_old_and_new_versions() { bool upgradeMessage = false; - foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).or_empty_list_if_null()) + foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).OrEmpty()) { if (message.Contains("You have UpperCase v1.0.0 installed. Version 1.1.0 is available based on your source")) upgradeMessage = true; } @@ -4671,31 +4717,31 @@ public void should_contain_a_warning_message_with_old_and_new_versions() } [Fact] - public void should_have_a_successful_package_result() + public void Should_have_a_successful_package_result() { _packageResult.Success.ShouldBeTrue(); } [Fact] - public void should_not_have_inconclusive_package_result() + public void Should_not_have_inconclusive_package_result() { _packageResult.Inconclusive.ShouldBeFalse(); } [Fact] - public void should_not_have_warning_package_result() + public void Should_not_have_warning_package_result() { _packageResult.Warning.ShouldBeFalse(); } [Fact] - public void config_should_match_package_result_name() + public void Config_should_match_package_result_name() { _packageResult.Name.ShouldEqual(Configuration.PackageNames); } [Fact] - public void should_match_the_upgrade_version_of_one_dot_one_dot_zero() + public void Should_match_the_upgrade_version_of_one_dot_one_dot_zero() { _packageResult.Version.ShouldEqual("1.1.0"); } @@ -4703,44 +4749,44 @@ public void should_match_the_upgrade_version_of_one_dot_one_dot_zero() [Fact] [WindowsOnly] [Platform(Exclude = "Mono")] - public void should_have_executed_chocolateyBeforeModify_script_for_original_package() + public void Should_have_executed_chocolateyBeforeModify_script_for_original_package() { - MockLogger.contains_message("UpperCase 1.0.0 Before Modification", LogLevel.Info).ShouldBeTrue(); + MockLogger.ContainsMessage("UpperCase 1.0.0 Before Modification", LogLevel.Info).ShouldBeTrue(); } [Fact] [WindowsOnly] [Platform(Exclude = "Mono")] - public void should_have_executed_chocolateyBeforeModify_before_chocolateyInstall() + public void Should_have_executed_chocolateyBeforeModify_before_chocolateyInstall() { - MockLogger.MessagesFor(LogLevel.Info).or_empty_list_if_null() + MockLogger.MessagesFor(LogLevel.Info).OrEmpty() .SkipWhile(p => !p.Contains("UpperCase 1.0.0 Before Modification")) .Any(p => p.EndsWith("UpperCase 1.1.0 Installed")) .ShouldBeTrue(); } [Fact] - public void should_not_have_executed_chocolateyUninstall_script_for_original_package() + public void Should_not_have_executed_chocolateyUninstall_script_for_original_package() { - MockLogger.contains_message("UpperCase 1.0.0 Uninstalled", LogLevel.Info).ShouldBeFalse(); + MockLogger.ContainsMessage("UpperCase 1.0.0 Uninstalled", LogLevel.Info).ShouldBeFalse(); } [Fact] - public void should_not_have_executed_chocolateyBeforeModify_script_for_new_package() + public void Should_not_have_executed_chocolateyBeforeModify_script_for_new_package() { - MockLogger.contains_message("UpperCase 1.1.0 Before Modification", LogLevel.Info).ShouldBeFalse(); + MockLogger.ContainsMessage("UpperCase 1.1.0 Before Modification", LogLevel.Info).ShouldBeFalse(); } [Fact] [WindowsOnly] [Platform(Exclude = "Mono")] - public void should_have_executed_chocolateyInstall_script_for_new_package() + public void Should_have_executed_chocolateyInstall_script_for_new_package() { - MockLogger.contains_message("UpperCase 1.1.0 Installed", LogLevel.Info).ShouldBeTrue(); + MockLogger.ContainsMessage("UpperCase 1.1.0 Installed", LogLevel.Info).ShouldBeTrue(); } } - public class when_upgrading_an_existing_package_with_unsupported_metadata_elements : ScenariosBase + public class When_upgrading_an_existing_package_with_unsupported_metadata_elements : ScenariosBase { private PackageResult _packageResult; @@ -4754,18 +4800,18 @@ public override void Context() public override void Because() { - Results = Service.upgrade_run(Configuration); + Results = Service.Upgrade(Configuration); _packageResult = Results.FirstOrDefault().Value; } [Fact] - public void should_upgrade_where_install_location_reports() + public void Should_upgrade_where_install_location_reports() { DirectoryAssert.Exists(_packageResult.InstallLocation); } [Fact] - public void should_upgrade_a_package_in_the_lib_directory() + public void Should_upgrade_a_package_in_the_lib_directory() { var packageDir = Path.Combine(Scenario.get_top_level(), "lib", Configuration.PackageNames); @@ -4773,20 +4819,20 @@ public void should_upgrade_a_package_in_the_lib_directory() } [Fact] - public void should_upgrade_the_package() + public void Should_upgrade_the_package() { var packageFile = Path.Combine(Scenario.get_top_level(), "lib", Configuration.PackageNames, Configuration.PackageNames + NuGetConstants.PackageExtension); using (var packageReader = new PackageArchiveReader(packageFile)) { - packageReader.NuspecReader.GetVersion().to_string().ShouldEqual("1.1.0"); + packageReader.NuspecReader.GetVersion().ToStringSafe().ShouldEqual("1.1.0"); } } [Fact] - public void should_contain_a_warning_message_that_it_upgraded_successfully() + public void Should_contain_a_warning_message_that_it_upgraded_successfully() { bool upgradedSuccessMessage = false; - foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).or_empty_list_if_null()) + foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).OrEmpty()) { if (message.Contains("upgraded 1/1")) upgradedSuccessMessage = true; } @@ -4795,10 +4841,10 @@ public void should_contain_a_warning_message_that_it_upgraded_successfully() } [Fact] - public void should_contain_a_warning_message_with_old_and_new_versions() + public void Should_contain_a_warning_message_with_old_and_new_versions() { bool upgradeMessage = false; - foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).or_empty_list_if_null()) + foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).OrEmpty()) { if (message.Contains("You have unsupportedelements v1.0.0 installed. Version 1.1.0 is available based on your source")) upgradeMessage = true; } @@ -4807,10 +4853,10 @@ public void should_contain_a_warning_message_with_old_and_new_versions() } [Fact] - public void should_contain_a_warning_message_about_unsupported_elements() + public void Should_contain_a_warning_message_about_unsupported_elements() { bool upgradeMessage = false; - foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).or_empty_list_if_null()) + foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).OrEmpty()) { if (message.Contains("Issues found with nuspec elements")) upgradeMessage = true; } @@ -4818,31 +4864,31 @@ public void should_contain_a_warning_message_about_unsupported_elements() } [Fact] - public void should_have_a_successful_package_result() + public void Should_have_a_successful_package_result() { _packageResult.Success.ShouldBeTrue(); } [Fact] - public void should_not_have_inconclusive_package_result() + public void Should_not_have_inconclusive_package_result() { _packageResult.Inconclusive.ShouldBeFalse(); } [Fact] - public void should_have_warning_package_result() + public void Should_have_warning_package_result() { _packageResult.Warning.ShouldBeTrue(); } [Fact] - public void config_should_match_package_result_name() + public void Config_should_match_package_result_name() { _packageResult.Name.ShouldEqual(Configuration.PackageNames); } [Fact] - public void should_match_the_upgrade_version_of_one_dot_one_dot_zero() + public void Should_match_the_upgrade_version_of_one_dot_one_dot_zero() { _packageResult.Version.ShouldEqual("1.1.0"); } @@ -4850,44 +4896,44 @@ public void should_match_the_upgrade_version_of_one_dot_one_dot_zero() [Fact] [WindowsOnly] [Platform(Exclude = "Mono")] - public void should_have_executed_chocolateyBeforeModify_script_for_original_package() + public void Should_have_executed_chocolateyBeforeModify_script_for_original_package() { - MockLogger.contains_message("unsupportedelements 1.0.0 Before Modification", LogLevel.Info).ShouldBeTrue(); + MockLogger.ContainsMessage("unsupportedelements 1.0.0 Before Modification", LogLevel.Info).ShouldBeTrue(); } [Fact] [WindowsOnly] [Platform(Exclude = "Mono")] - public void should_have_executed_chocolateyBeforeModify_before_chocolateyInstall() + public void Should_have_executed_chocolateyBeforeModify_before_chocolateyInstall() { - MockLogger.MessagesFor(LogLevel.Info).or_empty_list_if_null() + MockLogger.MessagesFor(LogLevel.Info).OrEmpty() .SkipWhile(p => !p.Contains("unsupportedelements 1.0.0 Before Modification")) .Any(p => p.EndsWith("unsupportedelements 1.1.0 Installed")) .ShouldBeTrue(); } [Fact] - public void should_not_have_executed_chocolateyUninstall_script_for_original_package() + public void Should_not_have_executed_chocolateyUninstall_script_for_original_package() { - MockLogger.contains_message("unsupportedelements 1.0.0 Uninstalled", LogLevel.Info).ShouldBeFalse(); + MockLogger.ContainsMessage("unsupportedelements 1.0.0 Uninstalled", LogLevel.Info).ShouldBeFalse(); } [Fact] - public void should_not_have_executed_chocolateyBeforeModify_script_for_new_package() + public void Should_not_have_executed_chocolateyBeforeModify_script_for_new_package() { - MockLogger.contains_message("unsupportedelements 1.1.0 Before Modification", LogLevel.Info).ShouldBeFalse(); + MockLogger.ContainsMessage("unsupportedelements 1.1.0 Before Modification", LogLevel.Info).ShouldBeFalse(); } [Fact] [WindowsOnly] [Platform(Exclude = "Mono")] - public void should_have_executed_chocolateyInstall_script_for_new_package() + public void Should_have_executed_chocolateyInstall_script_for_new_package() { - MockLogger.contains_message("unsupportedelements 1.1.0 Installed", LogLevel.Info).ShouldBeTrue(); + MockLogger.ContainsMessage("unsupportedelements 1.1.0 Installed", LogLevel.Info).ShouldBeTrue(); } } - public class when_upgrading_an_existing_package_non_normalized_version : ScenariosBase + public class When_upgrading_an_existing_package_non_normalized_version : ScenariosBase { private PackageResult _packageResult; @@ -4903,18 +4949,18 @@ public override void Context() public override void Because() { - Results = Service.upgrade_run(Configuration); + Results = Service.Upgrade(Configuration); _packageResult = Results.FirstOrDefault().Value; } [Fact] - public void should_upgrade_where_install_location_reports() + public void Should_upgrade_where_install_location_reports() { DirectoryAssert.Exists(_packageResult.InstallLocation); } [Fact] - public void should_upgrade_a_package_in_the_lib_directory() + public void Should_upgrade_a_package_in_the_lib_directory() { var packageDir = Path.Combine(Scenario.get_top_level(), "lib", Configuration.PackageNames); @@ -4922,7 +4968,7 @@ public void should_upgrade_a_package_in_the_lib_directory() } [Fact] - public void should_delete_the_rollback() + public void Should_delete_the_rollback() { var packageDir = Path.Combine(Scenario.get_top_level(), "lib-bkp", Configuration.PackageNames); @@ -4930,20 +4976,20 @@ public void should_delete_the_rollback() } [Fact] - public void should_upgrade_the_package() + public void Should_upgrade_the_package() { var packageFile = Path.Combine(Scenario.get_top_level(), "lib", Configuration.PackageNames, Configuration.PackageNames + NuGetConstants.PackageExtension); using (var packageReader = new PackageArchiveReader(packageFile)) { - packageReader.NuspecReader.GetVersion().to_string().ShouldEqual(NonNormalizedVersion); + packageReader.NuspecReader.GetVersion().ToStringSafe().ShouldEqual(NonNormalizedVersion); } } [Fact] - public void should_contain_a_warning_message_that_it_upgraded_successfully() + public void Should_contain_a_warning_message_that_it_upgraded_successfully() { bool upgradedSuccessMessage = false; - foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).or_empty_list_if_null()) + foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).OrEmpty()) { if (message.Contains("upgraded 1/1")) upgradedSuccessMessage = true; } @@ -4952,43 +4998,46 @@ public void should_contain_a_warning_message_that_it_upgraded_successfully() } [Fact] - public void should_contain_a_warning_message_with_old_and_new_versions() + public void Should_contain_a_warning_message_with_old_and_new_versions() { bool upgradeMessage = false; - foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).or_empty_list_if_null()) + foreach (var message in MockLogger.MessagesFor(LogLevel.Warn).OrEmpty()) { - if (message.Contains("You have upgradepackage v1.0.0 installed. Version {0} is available based on your source".format_with(NonNormalizedVersion))) upgradeMessage = true; + if (message.Contains("You have upgradepackage v1.0.0 installed. Version {0} is available based on your source".FormatWith(NonNormalizedVersion))) upgradeMessage = true; } upgradeMessage.ShouldBeTrue(); } [Fact] - public void should_have_a_successful_package_result() + public void Should_have_a_successful_package_result() { _packageResult.Success.ShouldBeTrue(); } [Fact] - public void should_not_have_inconclusive_package_result() + public void Should_not_have_inconclusive_package_result() { _packageResult.Inconclusive.ShouldBeFalse(); } [Fact] - public void should_not_have_warning_package_result() + public void Should_not_have_warning_package_result_other_than_before_modify_failures() { - _packageResult.Warning.ShouldBeFalse(); + // For before modify scripts that fail, we add a warning message. + // So we will ignore any such warnings. + var messages = _packageResult.Messages.Where(m => m.MessageType == ResultType.Warn && !m.Message.ContainsSafe("chocolateyBeforeModify")); + messages.ShouldBeEmpty(); } [Fact] - public void config_should_match_package_result_name() + public void Config_should_match_package_result_name() { _packageResult.Name.ShouldEqual(Configuration.PackageNames); } [Fact] - public void should_match_the_upgrade_version() + public void Should_match_the_upgrade_version() { _packageResult.Version.ShouldEqual(NonNormalizedVersion); } @@ -4996,44 +5045,44 @@ public void should_match_the_upgrade_version() [Fact] [WindowsOnly] [Platform(Exclude = "Mono")] - public void should_have_executed_chocolateyBeforeModify_script_for_original_package() + public void Should_have_executed_chocolateyBeforeModify_script_for_original_package() { - MockLogger.contains_message("upgradepackage 1.0.0 Before Modification", LogLevel.Info).ShouldBeTrue(); + MockLogger.ContainsMessage("upgradepackage 1.0.0 Before Modification", LogLevel.Info).ShouldBeTrue(); } [Fact] [WindowsOnly] [Platform(Exclude = "Mono")] - public void should_have_executed_chocolateyBeforeModify_before_chocolateyInstall() + public void Should_have_executed_chocolateyBeforeModify_before_chocolateyInstall() { - MockLogger.MessagesFor(LogLevel.Info).or_empty_list_if_null() + MockLogger.MessagesFor(LogLevel.Info).OrEmpty() .SkipWhile(p => !p.Contains("upgradepackage 1.0.0 Before Modification")) - .Any(p => p.EndsWith("upgradepackage {0} Installed".format_with(NonNormalizedVersion))) + .Any(p => p.EndsWith("upgradepackage {0} Installed".FormatWith(NonNormalizedVersion))) .ShouldBeTrue(); } [Fact] - public void should_not_have_executed_chocolateyUninstall_script_for_original_package() + public void Should_not_have_executed_chocolateyUninstall_script_for_original_package() { - MockLogger.contains_message("upgradepackage 1.0.0 Uninstalled", LogLevel.Info).ShouldBeFalse(); + MockLogger.ContainsMessage("upgradepackage 1.0.0 Uninstalled", LogLevel.Info).ShouldBeFalse(); } [Fact] - public void should_not_have_executed_chocolateyBeforeModify_script_for_new_package() + public void Should_not_have_executed_chocolateyBeforeModify_script_for_new_package() { - MockLogger.contains_message("upgradepackage {0} Before Modification".format_with(NonNormalizedVersion), LogLevel.Info).ShouldBeFalse(); + MockLogger.ContainsMessage("upgradepackage {0} Before Modification".FormatWith(NonNormalizedVersion), LogLevel.Info).ShouldBeFalse(); } [Fact] [WindowsOnly] [Platform(Exclude = "Mono")] - public void should_have_executed_chocolateyInstall_script_for_new_package() + public void Should_have_executed_chocolateyInstall_script_for_new_package() { - MockLogger.contains_message("upgradepackage {0} Installed".format_with(NonNormalizedVersion), LogLevel.Info).ShouldBeTrue(); + MockLogger.ContainsMessage("upgradepackage {0} Installed".FormatWith(NonNormalizedVersion), LogLevel.Info).ShouldBeTrue(); } } - public class when_upgrading_an_existing_package_specifying_normalized_version : when_upgrading_an_existing_package_non_normalized_version + public class When_upgrading_an_existing_package_specifying_normalized_version : When_upgrading_an_existing_package_non_normalized_version { protected override string NormalizedVersion => "2.2.0"; protected override string NonNormalizedVersion => "2.02.0.0"; @@ -5045,7 +5094,7 @@ public override void Context() } } - public class when_upgrading_an_existing_package_specifying_non_normalized_version : when_upgrading_an_existing_package_non_normalized_version + public class When_upgrading_an_existing_package_specifying_non_normalized_version : When_upgrading_an_existing_package_non_normalized_version { protected override string NormalizedVersion => "2.2.0"; protected override string NonNormalizedVersion => "2.02.0.0"; @@ -5057,13 +5106,13 @@ public override void Context() } } - public class when_upgrading_an_existing_package_with_multiple_leading_zeros : when_upgrading_an_existing_package_non_normalized_version + public class When_upgrading_an_existing_package_with_multiple_leading_zeros : When_upgrading_an_existing_package_non_normalized_version { protected override string NormalizedVersion => "4.4.5.1"; protected override string NonNormalizedVersion => "0004.0004.00005.01"; } - public class when_upgrading_an_existing_package_with_multiple_leading_zeros_specifying_normalized_version : when_upgrading_an_existing_package_non_normalized_version + public class When_upgrading_an_existing_package_with_multiple_leading_zeros_specifying_normalized_version : When_upgrading_an_existing_package_non_normalized_version { protected override string NormalizedVersion => "4.4.5.1"; protected override string NonNormalizedVersion => "0004.0004.00005.01"; @@ -5075,7 +5124,7 @@ public override void Context() } } - public class when_upgrading_an_existing_package_with_multiple_leading_zeros_specifying_non_normalized_version : when_upgrading_an_existing_package_non_normalized_version + public class When_upgrading_an_existing_package_with_multiple_leading_zeros_specifying_non_normalized_version : When_upgrading_an_existing_package_non_normalized_version { protected override string NormalizedVersion => "4.4.5.1"; protected override string NonNormalizedVersion => "0004.0004.00005.01"; @@ -5087,8 +5136,8 @@ public override void Context() } } - - public class when_upgrading_a_package_with_beforeModify_script_with_dependencies_with_beforeModify_scripts_and_hooks : ScenariosBase + + public class When_upgrading_a_package_with_beforeModify_script_with_dependencies_with_beforeModify_scripts_and_hooks : ScenariosBase { private const string TargetPackageName = "hasdependencywithbeforemodify"; private const string DependencyName = "isdependencywithbeforemodify"; @@ -5097,8 +5146,8 @@ public override void Context() { base.Context(); - Scenario.add_packages_to_source_location(Configuration, "{0}.*".format_with(TargetPackageName) + NuGetConstants.PackageExtension); - Scenario.add_packages_to_source_location(Configuration, "{0}.*".format_with(DependencyName) + NuGetConstants.PackageExtension); + Scenario.add_packages_to_source_location(Configuration, "{0}.*".FormatWith(TargetPackageName) + NuGetConstants.PackageExtension); + Scenario.add_packages_to_source_location(Configuration, "{0}.*".FormatWith(DependencyName) + NuGetConstants.PackageExtension); Scenario.add_packages_to_source_location(Configuration, "scriptpackage.hook" + "*" + NuGetConstants.PackageExtension); Scenario.install_package(Configuration, DependencyName, "1.0.0"); Scenario.install_package(Configuration, TargetPackageName, "1.0.0"); @@ -5109,123 +5158,123 @@ public override void Context() public override void Because() { - Results = Service.upgrade_run(Configuration); + Results = Service.Upgrade(Configuration); } [Fact] - public void should_upgrade_the_minimum_version_dependency() + public void Should_upgrade_the_minimum_version_dependency() { - var packageFile = Path.Combine(Scenario.get_top_level(), "lib", DependencyName, "{0}.nupkg".format_with(DependencyName)); + var packageFile = Path.Combine(Scenario.get_top_level(), "lib", DependencyName, "{0}.nupkg".FormatWith(DependencyName)); using (var packageReader = new PackageArchiveReader(packageFile)) { - packageReader.NuspecReader.GetVersion().to_string().ShouldEqual("2.0.0"); + packageReader.NuspecReader.GetVersion().ToStringSafe().ShouldEqual("2.0.0"); } } [Fact] - public void should_contain_a_message_that_everything_upgraded_successfully() + public void Should_contain_a_message_that_everything_upgraded_successfully() { - MockLogger.contains_message("upgraded 2/2", LogLevel.Warn).ShouldBeTrue(); + MockLogger.ContainsMessage("upgraded 2/2", LogLevel.Warn).ShouldBeTrue(); } [Fact] [WindowsOnly] [Platform(Exclude = "Mono")] - public void should_run_beforemodify_hook_script_for_previous_version_of_target() + public void Should_run_beforemodify_hook_script_for_previous_version_of_target() { - MockLogger.contains_message("pre-beforemodify-all.ps1 hook ran for {0} {1}".format_with(TargetPackageName, "1.0.0"), LogLevel.Info).ShouldBeTrue(); + MockLogger.ContainsMessage("pre-beforemodify-all.ps1 hook ran for {0} {1}".FormatWith(TargetPackageName, "1.0.0"), LogLevel.Info).ShouldBeTrue(); } [Fact] [WindowsOnly] [Platform(Exclude = "Mono")] - public void should_run_already_installed_target_package_beforeModify() + public void Should_run_already_installed_target_package_beforeModify() { - MockLogger.contains_message("Ran BeforeModify: {0} {1}".format_with(TargetPackageName, "1.0.0"), LogLevel.Info).ShouldBeTrue(); + MockLogger.ContainsMessage("Ran BeforeModify: {0} {1}".FormatWith(TargetPackageName, "1.0.0"), LogLevel.Info).ShouldBeTrue(); } [Fact] [WindowsOnly] [Platform(Exclude = "Mono")] - public void should_not_run_beforemodify_hook_script_for_upgrade_version_of_target() + public void Should_not_run_beforemodify_hook_script_for_upgrade_version_of_target() { - MockLogger.contains_message("pre-beforemodify-all.ps1 hook ran for {0} {1}".format_with(TargetPackageName, "2.0.0"), LogLevel.Info).ShouldBeFalse(); + MockLogger.ContainsMessage("pre-beforemodify-all.ps1 hook ran for {0} {1}".FormatWith(TargetPackageName, "2.0.0"), LogLevel.Info).ShouldBeFalse(); } [Fact] [WindowsOnly] [Platform(Exclude = "Mono")] - public void should_not_run_target_package_beforeModify_for_upgraded_version() + public void Should_not_run_target_package_beforeModify_for_upgraded_version() { - MockLogger.contains_message("Ran BeforeModify: {0} {1}".format_with(TargetPackageName, "2.0.0"), LogLevel.Info).ShouldBeFalse(); + MockLogger.ContainsMessage("Ran BeforeModify: {0} {1}".FormatWith(TargetPackageName, "2.0.0"), LogLevel.Info).ShouldBeFalse(); } [Fact] [WindowsOnly] [Platform(Exclude = "Mono")] - public void should_run_pre_all_hook_script_for_upgraded_version_of_target() + public void Should_run_pre_all_hook_script_for_upgraded_version_of_target() { - MockLogger.contains_message("pre-install-all.ps1 hook ran for {0} {1}".format_with(TargetPackageName, "2.0.0"), LogLevel.Info).ShouldBeTrue(); + MockLogger.ContainsMessage("pre-install-all.ps1 hook ran for {0} {1}".FormatWith(TargetPackageName, "2.0.0"), LogLevel.Info).ShouldBeTrue(); } [Fact] [WindowsOnly] [Platform(Exclude = "Mono")] - public void should_run_post_all_hook_script_for_upgraded_version_of_target() + public void Should_run_post_all_hook_script_for_upgraded_version_of_target() { - MockLogger.contains_message("post-install-all.ps1 hook ran for {0} {1}".format_with(TargetPackageName, "2.0.0"), LogLevel.Info).ShouldBeTrue(); + MockLogger.ContainsMessage("post-install-all.ps1 hook ran for {0} {1}".FormatWith(TargetPackageName, "2.0.0"), LogLevel.Info).ShouldBeTrue(); } [Fact] [WindowsOnly] [Platform(Exclude = "Mono")] - public void should_run_beforemodify_hook_script_for_previous_version_of_dependency() + public void Should_run_beforemodify_hook_script_for_previous_version_of_dependency() { - MockLogger.contains_message("pre-beforemodify-all.ps1 hook ran for {0} {1}".format_with(DependencyName, "1.0.0"), LogLevel.Info).ShouldBeTrue(); + MockLogger.ContainsMessage("pre-beforemodify-all.ps1 hook ran for {0} {1}".FormatWith(DependencyName, "1.0.0"), LogLevel.Info).ShouldBeTrue(); } [Fact] [WindowsOnly] [Platform(Exclude = "Mono")] - public void should_run_already_installed_dependency_package_beforeModify() + public void Should_run_already_installed_dependency_package_beforeModify() { - MockLogger.contains_message("Ran BeforeModify: {0} {1}".format_with(DependencyName, "1.0.0"), LogLevel.Info).ShouldBeTrue(); + MockLogger.ContainsMessage("Ran BeforeModify: {0} {1}".FormatWith(DependencyName, "1.0.0"), LogLevel.Info).ShouldBeTrue(); } [Fact] [WindowsOnly] [Platform(Exclude = "Mono")] - public void should_not_run_beforemodify_hook_script_for_upgrade_version_of_dependency() + public void Should_not_run_beforemodify_hook_script_for_upgrade_version_of_dependency() { - MockLogger.contains_message("pre-beforemodify-all.ps1 hook ran for {0} {1}".format_with(DependencyName, "2.0.0"), LogLevel.Info).ShouldBeFalse(); + MockLogger.ContainsMessage("pre-beforemodify-all.ps1 hook ran for {0} {1}".FormatWith(DependencyName, "2.0.0"), LogLevel.Info).ShouldBeFalse(); } [Fact] [WindowsOnly] [Platform(Exclude = "Mono")] - public void should_not_run_dependency_package_beforeModify_for_upgraded_version() + public void Should_not_run_dependency_package_beforeModify_for_upgraded_version() { - MockLogger.contains_message("Ran BeforeModify: {0} {1}".format_with(DependencyName, "2.0.0"), LogLevel.Info).ShouldBeFalse(); + MockLogger.ContainsMessage("Ran BeforeModify: {0} {1}".FormatWith(DependencyName, "2.0.0"), LogLevel.Info).ShouldBeFalse(); } [Fact] [WindowsOnly] [Platform(Exclude = "Mono")] - public void should_run_pre_all_hook_script_for_upgraded_version_of_dependency() + public void Should_run_pre_all_hook_script_for_upgraded_version_of_dependency() { - MockLogger.contains_message("pre-install-all.ps1 hook ran for {0} {1}".format_with(DependencyName, "2.0.0"), LogLevel.Info).ShouldBeTrue(); + MockLogger.ContainsMessage("pre-install-all.ps1 hook ran for {0} {1}".FormatWith(DependencyName, "2.0.0"), LogLevel.Info).ShouldBeTrue(); } [Fact] [WindowsOnly] [Platform(Exclude = "Mono")] - public void should_run_post_all_hook_script_for_upgraded_version_of_dependency() + public void Should_run_post_all_hook_script_for_upgraded_version_of_dependency() { - MockLogger.contains_message("post-install-all.ps1 hook ran for {0} {1}".format_with(DependencyName, "2.0.0"), LogLevel.Info).ShouldBeTrue(); + MockLogger.ContainsMessage("post-install-all.ps1 hook ran for {0} {1}".FormatWith(DependencyName, "2.0.0"), LogLevel.Info).ShouldBeTrue(); } [Fact] - public void should_have_a_successful_package_result() + public void Should_have_a_successful_package_result() { foreach (var packageResult in Results) { @@ -5234,7 +5283,7 @@ public void should_have_a_successful_package_result() } [Fact] - public void should_not_have_inconclusive_package_result() + public void Should_not_have_inconclusive_package_result() { foreach (var packageResult in Results) { @@ -5243,7 +5292,7 @@ public void should_not_have_inconclusive_package_result() } [Fact] - public void should_not_have_warning_package_result() + public void Should_not_have_warning_package_result() { foreach (var packageResult in Results) { diff --git a/src/chocolatey.tests/MockLogger.cs b/src/chocolatey.tests/MockLogger.cs index cb96721e45..21b9bbcc04 100644 --- a/src/chocolatey.tests/MockLogger.cs +++ b/src/chocolatey.tests/MockLogger.cs @@ -38,7 +38,7 @@ public MockLogger() LoggerNames = new HashSet(); } - public void reset() + public void Reset() { Messages.Clear(); this.ResetCalls(); @@ -46,22 +46,22 @@ public void reset() LoggerNames.Clear(); } - public bool contains_message(string expectedMessage) + public bool ContainsMessage(string expectedMessage) { - return contains_message_count(expectedMessage) != 0; + return ContainsMessageCount(expectedMessage) != 0; } - public bool contains_message(string expectedMessage, LogLevel level) + public bool ContainsMessage(string expectedMessage, LogLevel level) { - return contains_message_count(expectedMessage, level) != 0; + return ContainsMessageCount(expectedMessage, level) != 0; } - public int contains_message_count(string expectedMessage) + public int ContainsMessageCount(string expectedMessage) { int messageCount = 0; foreach (var messageLevel in Messages) { - foreach (var message in messageLevel.Value.or_empty_list_if_null()) + foreach (var message in messageLevel.Value.OrEmpty()) { if (message.Contains(expectedMessage)) messageCount++; } @@ -70,10 +70,10 @@ public int contains_message_count(string expectedMessage) return messageCount; } - public int contains_message_count(string expectedMessage, LogLevel level) + public int ContainsMessageCount(string expectedMessage, LogLevel level) { int messageCount = 0; - foreach (var message in MessagesFor(level).or_empty_list_if_null()) + foreach (var message in MessagesFor(level).OrEmpty()) { if (message.Contains(expectedMessage)) messageCount++; } @@ -116,14 +116,14 @@ public void LogMessage(LogLevel logLevel, string message) list.Add(message); if (LogMessagesToConsole) { - Console.WriteLine("[{0}] {1}".format_with(logLevel.to_string(), message)); + Console.WriteLine("[{0}] {1}".FormatWith(logLevel.ToStringSafe(), message)); } } public void Debug(string message, params object[] formatting) { - Object.Debug(message.format_with(formatting)); - LogMessage(LogLevel.Debug, message.format_with(formatting)); + Object.Debug(message.FormatWith(formatting)); + LogMessage(LogLevel.Debug, message.FormatWith(formatting)); } public void Debug(Func message) @@ -134,8 +134,8 @@ public void Debug(Func message) public void Info(string message, params object[] formatting) { - Object.Info(message.format_with(formatting)); - LogMessage(LogLevel.Info, message.format_with(formatting)); + Object.Info(message.FormatWith(formatting)); + LogMessage(LogLevel.Info, message.FormatWith(formatting)); } public void Info(Func message) @@ -146,8 +146,8 @@ public void Info(Func message) public void Warn(string message, params object[] formatting) { - Object.Warn(message.format_with(formatting)); - LogMessage(LogLevel.Warn, message.format_with(formatting)); + Object.Warn(message.FormatWith(formatting)); + LogMessage(LogLevel.Warn, message.FormatWith(formatting)); } public void Warn(Func message) @@ -158,8 +158,8 @@ public void Warn(Func message) public void Error(string message, params object[] formatting) { - Object.Error(message.format_with(formatting)); - LogMessage(LogLevel.Error, message.format_with(formatting)); + Object.Error(message.FormatWith(formatting)); + LogMessage(LogLevel.Error, message.FormatWith(formatting)); } public void Error(Func message) @@ -170,8 +170,8 @@ public void Error(Func message) public void Fatal(string message, params object[] formatting) { - Object.Fatal(message.format_with(formatting)); - LogMessage(LogLevel.Fatal, message.format_with(formatting)); + Object.Fatal(message.FormatWith(formatting)); + LogMessage(LogLevel.Fatal, message.FormatWith(formatting)); } public void Fatal(Func message) diff --git a/src/chocolatey.tests/TinySpec.cs b/src/chocolatey.tests/TinySpec.cs index 546eb72268..ddb01b022f 100644 --- a/src/chocolatey.tests/TinySpec.cs +++ b/src/chocolatey.tests/TinySpec.cs @@ -45,10 +45,6 @@ public virtual void BeforeEverything() Directory.SetCurrentDirectory(AppDomain.CurrentDomain.BaseDirectory); } - public virtual void before_everything() - { - } - [OneTimeTearDown] public void AfterEverything() { @@ -67,7 +63,7 @@ public MockLogger MockLogger [OneTimeSetUp] public void Setup() { - if (MockLogger != null) MockLogger.reset(); + if (MockLogger != null) MockLogger.Reset(); //Log.InitializeWith(MockLogger); NugetCommon.ClearRepositoriesCache(); Context(); @@ -125,7 +121,7 @@ public class ExplicitAttribute : NUnit.Framework.ExplicitAttribute public class ConcernForAttribute : CategoryAttribute { public ConcernForAttribute(string name) - : base("ConcernFor - {0}".format_with(name)) + : base("ConcernFor - {0}".FormatWith(name)) { } } @@ -144,7 +140,7 @@ public NotWorkingAttribute(string reason) public class PendingAttribute : IgnoreAttribute { public PendingAttribute(string reason) - : base("Pending test - {0}".format_with(reason)) + : base("Pending test - {0}".FormatWith(reason)) { } } diff --git a/src/chocolatey.tests/chocolatey.tests.csproj b/src/chocolatey.tests/chocolatey.tests.csproj index 84217fc960..c99dad6fd2 100644 --- a/src/chocolatey.tests/chocolatey.tests.csproj +++ b/src/chocolatey.tests/chocolatey.tests.csproj @@ -77,44 +77,44 @@ MinimumRecommendedRules.ruleset - - ..\packages\Chocolatey.NuGet.Commands.3.0.0-alpha-20230315-204\lib\net472\Chocolatey.NuGet.Commands.dll + + ..\packages\Chocolatey.NuGet.Commands.3.1.0\lib\net472\Chocolatey.NuGet.Commands.dll - - ..\packages\Chocolatey.NuGet.Common.3.0.0-alpha-20230315-204\lib\net472\Chocolatey.NuGet.Common.dll + + ..\packages\Chocolatey.NuGet.Common.3.1.0\lib\net472\Chocolatey.NuGet.Common.dll - - ..\packages\Chocolatey.NuGet.Configuration.3.0.0-alpha-20230315-204\lib\net472\Chocolatey.NuGet.Configuration.dll + + ..\packages\Chocolatey.NuGet.Configuration.3.1.0\lib\net472\Chocolatey.NuGet.Configuration.dll - - ..\packages\Chocolatey.NuGet.Credentials.3.0.0-alpha-20230315-204\lib\net472\Chocolatey.NuGet.Credentials.dll + + ..\packages\Chocolatey.NuGet.Credentials.3.1.0\lib\net472\Chocolatey.NuGet.Credentials.dll - - ..\packages\Chocolatey.NuGet.DependencyResolver.Core.3.0.0-alpha-20230315-204\lib\net472\Chocolatey.NuGet.DependencyResolver.Core.dll + + ..\packages\Chocolatey.NuGet.DependencyResolver.Core.3.1.0\lib\net472\Chocolatey.NuGet.DependencyResolver.Core.dll - - ..\packages\Chocolatey.NuGet.Frameworks.3.0.0-alpha-20230315-204\lib\net472\Chocolatey.NuGet.Frameworks.dll + + ..\packages\Chocolatey.NuGet.Frameworks.3.1.0\lib\net472\Chocolatey.NuGet.Frameworks.dll - - ..\packages\Chocolatey.NuGet.LibraryModel.3.0.0-alpha-20230315-204\lib\net472\Chocolatey.NuGet.LibraryModel.dll + + ..\packages\Chocolatey.NuGet.LibraryModel.3.1.0\lib\net472\Chocolatey.NuGet.LibraryModel.dll - - ..\packages\Chocolatey.NuGet.PackageManagement.3.0.0-alpha-20230315-204\lib\net472\Chocolatey.NuGet.PackageManagement.dll + + ..\packages\Chocolatey.NuGet.PackageManagement.3.1.0\lib\net472\Chocolatey.NuGet.PackageManagement.dll - - ..\packages\Chocolatey.NuGet.Packaging.3.0.0-alpha-20230315-204\lib\net472\Chocolatey.NuGet.Packaging.dll + + ..\packages\Chocolatey.NuGet.Packaging.3.1.0\lib\net472\Chocolatey.NuGet.Packaging.dll - - ..\packages\Chocolatey.NuGet.ProjectModel.3.0.0-alpha-20230315-204\lib\net472\Chocolatey.NuGet.ProjectModel.dll + + ..\packages\Chocolatey.NuGet.ProjectModel.3.1.0\lib\net472\Chocolatey.NuGet.ProjectModel.dll - - ..\packages\Chocolatey.NuGet.Protocol.3.0.0-alpha-20230315-204\lib\net472\Chocolatey.NuGet.Protocol.dll + + ..\packages\Chocolatey.NuGet.Protocol.3.1.0\lib\net472\Chocolatey.NuGet.Protocol.dll - - ..\packages\Chocolatey.NuGet.Resolver.3.0.0-alpha-20230315-204\lib\net472\Chocolatey.NuGet.Resolver.dll + + ..\packages\Chocolatey.NuGet.Resolver.3.1.0\lib\net472\Chocolatey.NuGet.Resolver.dll - - ..\packages\Chocolatey.NuGet.Versioning.3.0.0-alpha-20230315-204\lib\net472\Chocolatey.NuGet.Versioning.dll + + ..\packages\Chocolatey.NuGet.Versioning.3.1.0\lib\net472\Chocolatey.NuGet.Versioning.dll ..\packages\log4net.2.0.12\lib\net45\log4net.dll @@ -186,6 +186,7 @@ + diff --git a/src/chocolatey.tests/infrastructure.app/attributes/CommandForAttributeSpecs.cs b/src/chocolatey.tests/infrastructure.app/attributes/CommandForAttributeSpecs.cs index cfb9982993..b4cb255a0c 100644 --- a/src/chocolatey.tests/infrastructure.app/attributes/CommandForAttributeSpecs.cs +++ b/src/chocolatey.tests/infrastructure.app/attributes/CommandForAttributeSpecs.cs @@ -26,7 +26,7 @@ public abstract class CommandForAttributeSpecsBase : TinySpec protected CommandForAttribute attribute; } - public class when_CommandForAttribute_is_set_with_string : CommandForAttributeSpecsBase + public class When_CommandForAttribute_is_set_with_string : CommandForAttributeSpecsBase { private string result; @@ -41,7 +41,7 @@ public override void Because() } [Fact] - public void should_be_set_to_the_string() + public void Should_be_set_to_the_string() { result.ShouldEqual("bob"); } diff --git a/src/chocolatey.tests/infrastructure.app/commands/ChocolateyApiKeyCommandSpecs.cs b/src/chocolatey.tests/infrastructure.app/commands/ChocolateyApiKeyCommandSpecs.cs index 1f3f571f14..d3e20399bf 100644 --- a/src/chocolatey.tests/infrastructure.app/commands/ChocolateyApiKeyCommandSpecs.cs +++ b/src/chocolatey.tests/infrastructure.app/commands/ChocolateyApiKeyCommandSpecs.cs @@ -44,7 +44,7 @@ public override void Context() } } - public class when_implementing_command_for : ChocolateyApiKeyCommandSpecsBase + public class When_implementing_command_for : ChocolateyApiKeyCommandSpecsBase { private List results; @@ -54,19 +54,19 @@ public override void Because() } [Fact] - public void should_implement_apikey() + public void Should_implement_apikey() { results.ShouldContain("apikey"); } [Fact] - public void should_implement_setapikey() + public void Should_implement_setapikey() { results.ShouldContain("setapikey"); } } - public class when_configuring_the_argument_parser : ChocolateyApiKeyCommandSpecsBase + public class When_configuring_the_argument_parser : ChocolateyApiKeyCommandSpecsBase { private OptionSet optionSet; @@ -78,48 +78,48 @@ public override void Context() public override void Because() { - command.configure_argument_parser(optionSet, configuration); + command.ConfigureArgumentParser(optionSet, configuration); } [Fact] - public void should_clear_previously_set_Source() + public void Should_clear_previously_set_Source() { configuration.Sources.ShouldBeNull(); } [Fact] - public void should_add_source_to_the_option_set() + public void Should_add_source_to_the_option_set() { optionSet.Contains("source").ShouldBeTrue(); } [Fact] - public void should_add_short_version_of_source_to_the_option_set() + public void Should_add_short_version_of_source_to_the_option_set() { optionSet.Contains("s").ShouldBeTrue(); } [Fact] - public void should_add_apikey_to_the_option_set() + public void Should_add_apikey_to_the_option_set() { optionSet.Contains("apikey").ShouldBeTrue(); } [Fact] - public void should_add_short_version_of_apikey_to_the_option_set() + public void Should_add_short_version_of_apikey_to_the_option_set() { optionSet.Contains("k").ShouldBeTrue(); } } - public class when_handling_validation : ChocolateyApiKeyCommandSpecsBase + public class When_validating : ChocolateyApiKeyCommandSpecsBase { public override void Because() { } [Fact] - public void should_throw_when_key_is_set_without_a_source() + public void Should_throw_when_key_is_set_without_a_source() { configuration.ApiKeyCommand.Key = "bob"; configuration.Sources = ""; @@ -128,7 +128,7 @@ public void should_throw_when_key_is_set_without_a_source() try { - command.handle_validation(configuration); + command.Validate(configuration); } catch (Exception ex) { @@ -142,23 +142,23 @@ public void should_throw_when_key_is_set_without_a_source() } [Fact] - public void should_continue_when_source_is_set_but_no_key_set() + public void Should_continue_when_source_is_set_but_no_key_set() { configuration.ApiKeyCommand.Key = ""; configuration.Sources = "bob"; - command.handle_validation(configuration); + command.Validate(configuration); } [Fact] - public void should_continue_when_both_source_and_key_are_set() + public void Should_continue_when_both_source_and_key_are_set() { configuration.ApiKeyCommand.Key = "bob"; configuration.Sources = "bob"; - command.handle_validation(configuration); + command.Validate(configuration); } [Fact] - public void should_throw_when_key_is_removed_without_a_source() + public void Should_throw_when_key_is_removed_without_a_source() { configuration.ApiKeyCommand.Command = ApiKeyCommandType.Remove; configuration.Sources = ""; @@ -167,7 +167,7 @@ public void should_throw_when_key_is_removed_without_a_source() try { - command.handle_validation(configuration); + command.Validate(configuration); } catch (Exception ex) { @@ -181,29 +181,29 @@ public void should_throw_when_key_is_removed_without_a_source() } [Fact] - public void should_continue_when_removing_and_source_is_set() + public void Should_continue_when_removing_and_source_is_set() { configuration.ApiKeyCommand.Command = ApiKeyCommandType.Remove; configuration.Sources = "bob"; - command.handle_validation(configuration); + command.Validate(configuration); } } - public class when_noop_is_called : ChocolateyApiKeyCommandSpecsBase + public class When_noop_is_called : ChocolateyApiKeyCommandSpecsBase { public override void Because() { - command.noop(configuration); + command.DryRun(configuration); } [Fact] - public void should_call_service_noop() + public void Should_call_service_noop() { - configSettingsService.Verify(c => c.noop(configuration), Times.Once); + configSettingsService.Verify(c => c.DryRun(configuration), Times.Once); } } - public class when_run_is_called_without_key_set : ChocolateyApiKeyCommandSpecsBase + public class When_run_is_called_without_key_set : ChocolateyApiKeyCommandSpecsBase { public override void Context() { @@ -214,17 +214,17 @@ public override void Context() public override void Because() { - command.run(configuration); + command.Run(configuration); } [Fact] - public void should_call_service_get_api_key() + public void Should_call_service_get_api_key() { - configSettingsService.Verify(c => c.get_api_key(configuration, It.IsAny>()), Times.Once); + configSettingsService.Verify(c => c.GetApiKey(configuration, It.IsAny>()), Times.Once); } } - public class when_run_is_called_with_key_set : ChocolateyApiKeyCommandSpecsBase + public class When_run_is_called_with_key_set : ChocolateyApiKeyCommandSpecsBase { public override void Context() { @@ -236,13 +236,13 @@ public override void Context() public override void Because() { - command.run(configuration); + command.Run(configuration); } [Fact] - public void should_call_service_set_api_key() + public void Should_call_service_set_api_key() { - configSettingsService.Verify(c => c.set_api_key(configuration), Times.Once); + configSettingsService.Verify(c => c.SetApiKey(configuration), Times.Once); } } } diff --git a/src/chocolatey.tests/infrastructure.app/commands/ChocolateyConfigCommandSpecs.cs b/src/chocolatey.tests/infrastructure.app/commands/ChocolateyConfigCommandSpecs.cs index b8ffce6201..2a2493450a 100644 --- a/src/chocolatey.tests/infrastructure.app/commands/ChocolateyConfigCommandSpecs.cs +++ b/src/chocolatey.tests/infrastructure.app/commands/ChocolateyConfigCommandSpecs.cs @@ -33,113 +33,113 @@ public class ChocolateyConfigCommandSpecs [ConcernFor("config")] public abstract class ChocolateyConfigCommandSpecsBase : TinySpec { - protected ChocolateyConfigCommand command; - protected Mock configSettingsService = new Mock(); - protected ChocolateyConfiguration configuration = new ChocolateyConfiguration(); + protected ChocolateyConfigCommand Command; + protected Mock ConfigSettingsService = new Mock(); + protected ChocolateyConfiguration Configuration = new ChocolateyConfiguration(); public override void Context() { - command = new ChocolateyConfigCommand(configSettingsService.Object); + Command = new ChocolateyConfigCommand(ConfigSettingsService.Object); } } - public class when_implementing_command_for : ChocolateyConfigCommandSpecsBase + public class When_implementing_command_for : ChocolateyConfigCommandSpecsBase { - private List results; + private List _results; public override void Because() { - results = command.GetType().GetCustomAttributes(typeof(CommandForAttribute), false).Cast().Select(a => a.CommandName).ToList(); + _results = Command.GetType().GetCustomAttributes(typeof(CommandForAttribute), false).Cast().Select(a => a.CommandName).ToList(); } [Fact] - public void should_implement_config() + public void Should_implement_config() { - results.ShouldContain("config"); + _results.ShouldContain("config"); } } - public class when_configurating_the_argument_parser : ChocolateyConfigCommandSpecsBase + public class When_configurating_the_argument_parser : ChocolateyConfigCommandSpecsBase { - private OptionSet optionSet; + private OptionSet _optionSet; public override void Context() { base.Context(); - optionSet = new OptionSet(); + _optionSet = new OptionSet(); } public override void Because() { - command.configure_argument_parser(optionSet, configuration); + Command.ConfigureArgumentParser(_optionSet, Configuration); } [Fact] - public void should_add_name_to_the_option_set() + public void Should_add_name_to_the_option_set() { - optionSet.Contains("name").ShouldBeTrue(); + _optionSet.Contains("name").ShouldBeTrue(); } [Fact] - public void should_add_value_to_the_option_set() + public void Should_add_value_to_the_option_set() { - optionSet.Contains("value").ShouldBeTrue(); + _optionSet.Contains("value").ShouldBeTrue(); } } - public class when_noop_is_called : ChocolateyConfigCommandSpecsBase + public class When_noop_is_called : ChocolateyConfigCommandSpecsBase { public override void Because() { - command.noop(configuration); + Command.DryRun(Configuration); } [Fact] - public void should_call_service_noop() + public void Should_call_service_noop() { - configSettingsService.Verify(c => c.noop(configuration), Times.Once); + ConfigSettingsService.Verify(c => c.DryRun(Configuration), Times.Once); } } - public class when_run_is_called : ChocolateyConfigCommandSpecsBase + public class When_run_is_called : ChocolateyConfigCommandSpecsBase { - private Action because; + private Action _because; public override void Because() { - because = () => command.run(configuration); + _because = () => Command.Run(Configuration); } [Fact] - public void should_call_service_source_list_when_command_is_list() + public void Should_call_service_config_list_when_command_is_list() { - configuration.ConfigCommand.Command = ConfigCommandType.list; - because(); - configSettingsService.Verify(c => c.config_list(configuration), Times.Once); + Configuration.ConfigCommand.Command = ConfigCommandType.List; + _because(); + ConfigSettingsService.Verify(c => c.ListConfig(Configuration), Times.Once); } [Fact] - public void should_call_service_source_disable_when_command_is_disable() + public void Should_call_service_config_get_when_command_is_get() { - configuration.ConfigCommand.Command = ConfigCommandType.get; - because(); - configSettingsService.Verify(c => c.config_get(configuration), Times.Once); + Configuration.ConfigCommand.Command = ConfigCommandType.Get; + _because(); + ConfigSettingsService.Verify(c => c.GetConfig(Configuration), Times.Once); } [Fact] - public void should_call_service_source_enable_when_command_is_enable() + public void Should_call_service_config_set_when_command_is_set() { - configuration.ConfigCommand.Command = ConfigCommandType.set; - because(); - configSettingsService.Verify(c => c.config_set(configuration), Times.Once); + Configuration.ConfigCommand.Command = ConfigCommandType.Set; + _because(); + ConfigSettingsService.Verify(c => c.SetConfig(Configuration), Times.Once); } [Fact] - public void should_call_service_source_unset_when_command_is_unset() + public void Should_call_service_config_unset_when_command_is_unset() { - configuration.ConfigCommand.Command = ConfigCommandType.unset; - because(); - configSettingsService.Verify(c => c.config_unset(configuration), Times.Once); + Configuration.ConfigCommand.Command = ConfigCommandType.Unset; + _because(); + ConfigSettingsService.Verify(c => c.UnsetConfig(Configuration), Times.Once); } } } diff --git a/src/chocolatey.tests/infrastructure.app/commands/ChocolateyExportCommandSpecs.cs b/src/chocolatey.tests/infrastructure.app/commands/ChocolateyExportCommandSpecs.cs index 42dc887944..3eafdd6757 100644 --- a/src/chocolatey.tests/infrastructure.app/commands/ChocolateyExportCommandSpecs.cs +++ b/src/chocolatey.tests/infrastructure.app/commands/ChocolateyExportCommandSpecs.cs @@ -43,14 +43,14 @@ public override void Context() command = new ChocolateyExportCommand(nugetService.Object, fileSystem.Object); } - public void reset() + public void Reset() { nugetService.ResetCalls(); fileSystem.ResetCalls(); } } - public class when_implementing_command_for : ChocolateyExportCommandSpecsBase + public class When_implementing_command_for : ChocolateyExportCommandSpecsBase { private List results; @@ -60,13 +60,13 @@ public override void Because() } [Fact] - public void should_implement_help() + public void Should_implement_help() { results.ShouldContain("export"); } } - public class when_configurating_the_argument_parser : ChocolateyExportCommandSpecsBase + public class When_configurating_the_argument_parser : ChocolateyExportCommandSpecsBase { private OptionSet optionSet; @@ -78,55 +78,55 @@ public override void Context() public override void Because() { - command.configure_argument_parser(optionSet, configuration); + command.ConfigureArgumentParser(optionSet, configuration); } [Fact] - public void should_add_output_file_path_to_the_option_set() + public void Should_add_output_file_path_to_the_option_set() { optionSet.Contains("output-file-path").ShouldBeTrue(); } [Fact] - public void should_add_short_version_of_output_file_path_to_the_option_set() + public void Should_add_short_version_of_output_file_path_to_the_option_set() { optionSet.Contains("o").ShouldBeTrue(); } [Fact] - public void should_add_include_version_numbers_to_the_option_set() + public void Should_add_include_version_numbers_to_the_option_set() { optionSet.Contains("include-version-numbers").ShouldBeTrue(); } [Fact] - public void should_add_include_version_to_the_option_set() + public void Should_add_include_version_to_the_option_set() { optionSet.Contains("include-version").ShouldBeTrue(); } } - public class when_handling_additional_argument_parsing : ChocolateyExportCommandSpecsBase + public class When_handling_additional_argument_parsing : ChocolateyExportCommandSpecsBase { private readonly IList unparsedArgs = new List(); private Action because; public override void Because() { - because = () => command.handle_additional_argument_parsing(unparsedArgs, configuration); + because = () => command.ParseAdditionalArguments(unparsedArgs, configuration); } - public new void reset() + public new void Reset() { configuration.ExportCommand.OutputFilePath = string.Empty; unparsedArgs.Clear(); - base.reset(); + base.Reset(); } [Fact] - public void should_handle_passing_in_an_empty_string_for_output_file_path() + public void Should_handle_passing_in_an_empty_string_for_output_file_path() { - reset(); + Reset(); unparsedArgs.Add(" "); because(); @@ -134,9 +134,9 @@ public void should_handle_passing_in_an_empty_string_for_output_file_path() } [Fact] - public void should_handle_passing_in_a_string_for_output_file_path() + public void Should_handle_passing_in_a_string_for_output_file_path() { - reset(); + Reset(); unparsedArgs.Add("custompackages.config"); because(); @@ -144,21 +144,21 @@ public void should_handle_passing_in_a_string_for_output_file_path() } } - public class when_noop_is_called : ChocolateyExportCommandSpecsBase + public class When_noop_is_called : ChocolateyExportCommandSpecsBase { public override void Because() { - command.noop(configuration); + command.DryRun(configuration); } [Fact] - public void should_log_a_message() + public void Should_log_a_message() { MockLogger.Verify(l => l.Info(It.IsAny()), Times.AtLeastOnce); } [Fact] - public void should_log_the_message_we_expect() + public void Should_log_the_message_we_expect() { var messages = MockLogger.MessagesFor(LogLevel.Info); messages.ShouldNotBeEmpty(); @@ -167,12 +167,12 @@ public void should_log_the_message_we_expect() } } - public class when_run_is_called : ChocolateyExportCommandSpecsBase + public class When_run_is_called : ChocolateyExportCommandSpecsBase { - public new void reset() + public new void Reset() { Context(); - base.reset(); + base.Reset(); } public override void AfterEachSpec() @@ -187,34 +187,34 @@ public override void Because() } [Fact] - public void should_call_nuget_service_get_all_installed_packages() + public void Should_call_nuget_service_get_all_installed_packages() { - reset(); - command.run(configuration); + Reset(); + command.Run(configuration); - nugetService.Verify(n => n.get_all_installed_packages(It.IsAny()), Times.Once); + nugetService.Verify(n => n.GetInstalledPackages(It.IsAny()), Times.Once); } [Fact] - public void should_call_replace_file_when_file_already_exists() + public void Should_call_replace_file_when_file_already_exists() { - fileSystem.Setup(f => f.file_exists(It.IsAny())).Returns(true); + fileSystem.Setup(f => f.FileExists(It.IsAny())).Returns(true); - reset(); - command.run(configuration); + Reset(); + command.Run(configuration); - fileSystem.Verify(n => n.replace_file(It.IsAny(), It.IsAny(), It.IsAny()), Times.Once); + fileSystem.Verify(n => n.ReplaceFile(It.IsAny(), It.IsAny(), It.IsAny()), Times.Once); } [Fact] - public void should_not_call_replace_file_when_file_doesnt_exist() + public void Should_not_call_replace_file_when_file_doesnt_exist() { - fileSystem.Setup(f => f.file_exists(It.IsAny())).Returns(false); + fileSystem.Setup(f => f.FileExists(It.IsAny())).Returns(false); - reset(); - command.run(configuration); + Reset(); + command.Run(configuration); - fileSystem.Verify(n => n.replace_file(It.IsAny(), It.IsAny(), It.IsAny()), Times.Never); + fileSystem.Verify(n => n.ReplaceFile(It.IsAny(), It.IsAny(), It.IsAny()), Times.Never); } } } diff --git a/src/chocolatey.tests/infrastructure.app/commands/ChocolateyFeatureCommandSpecs.cs b/src/chocolatey.tests/infrastructure.app/commands/ChocolateyFeatureCommandSpecs.cs index 84e3c858c3..6a8547b6e9 100644 --- a/src/chocolatey.tests/infrastructure.app/commands/ChocolateyFeatureCommandSpecs.cs +++ b/src/chocolatey.tests/infrastructure.app/commands/ChocolateyFeatureCommandSpecs.cs @@ -33,106 +33,106 @@ public class ChocolateyFeatureCommandSpecs [ConcernFor("feature")] public abstract class ChocolateyFeatureCommandSpecsBase : TinySpec { - protected ChocolateyFeatureCommand command; - protected Mock configSettingsService = new Mock(); - protected ChocolateyConfiguration configuration = new ChocolateyConfiguration(); + protected ChocolateyFeatureCommand Command; + protected Mock ConfigSettingsService = new Mock(); + protected ChocolateyConfiguration Configuration = new ChocolateyConfiguration(); public override void Context() { - configuration.Sources = "https://localhost/somewhere/out/there"; - command = new ChocolateyFeatureCommand(configSettingsService.Object); + Configuration.Sources = "https://localhost/somewhere/out/there"; + Command = new ChocolateyFeatureCommand(ConfigSettingsService.Object); } } - public class when_implementing_command_for : ChocolateyFeatureCommandSpecsBase + public class When_implementing_command_for : ChocolateyFeatureCommandSpecsBase { - private List results; + private List _results; public override void Because() { - results = command.GetType().GetCustomAttributes(typeof(CommandForAttribute), false).Cast().Select(a => a.CommandName).ToList(); + _results = Command.GetType().GetCustomAttributes(typeof(CommandForAttribute), false).Cast().Select(a => a.CommandName).ToList(); } [Fact] - public void should_implement_feature() + public void Should_implement_feature() { - results.ShouldContain("feature"); + _results.ShouldContain("feature"); } [Fact] - public void should_implement_features() + public void Should_implement_features() { - results.ShouldContain("features"); + _results.ShouldContain("features"); } } - public class when_configurating_the_argument_parser : ChocolateyFeatureCommandSpecsBase + public class When_configurating_the_argument_parser : ChocolateyFeatureCommandSpecsBase { - private OptionSet optionSet; + private OptionSet _optionSet; public override void Context() { base.Context(); - optionSet = new OptionSet(); - configuration.Sources = "https://localhost/somewhere/out/there"; + _optionSet = new OptionSet(); + Configuration.Sources = "https://localhost/somewhere/out/there"; } public override void Because() { - command.configure_argument_parser(optionSet, configuration); + Command.ConfigureArgumentParser(_optionSet, Configuration); } [Fact] - public void should_add_name_to_the_option_set() + public void Should_add_name_to_the_option_set() { - optionSet.Contains("name").ShouldBeTrue(); + _optionSet.Contains("name").ShouldBeTrue(); } [Fact] - public void should_add_short_version_of_name_to_the_option_set() + public void Should_add_short_version_of_name_to_the_option_set() { - optionSet.Contains("n").ShouldBeTrue(); + _optionSet.Contains("n").ShouldBeTrue(); } } - public class when_handling_additional_argument_parsing : ChocolateyFeatureCommandSpecsBase + public class When_handling_additional_argument_parsing : ChocolateyFeatureCommandSpecsBase { - private readonly IList unparsedArgs = new List(); - private Action because; + private readonly IList _unparsedArgs = new List(); + private Action _because; public override void Because() { - because = () => command.handle_additional_argument_parsing(unparsedArgs, configuration); + _because = () => Command.ParseAdditionalArguments(_unparsedArgs, Configuration); } - public void reset() + public void Reset() { - unparsedArgs.Clear(); - configSettingsService.ResetCalls(); + _unparsedArgs.Clear(); + ConfigSettingsService.ResetCalls(); } [Fact] - public void should_use_the_first_unparsed_arg_as_the_subcommand() + public void Should_use_the_first_unparsed_arg_as_the_subcommand() { - reset(); - unparsedArgs.Add("list"); - because(); + Reset(); + _unparsedArgs.Add("list"); + _because(); - configuration.FeatureCommand.Command.ShouldEqual(FeatureCommandType.list); + Configuration.FeatureCommand.Command.ShouldEqual(FeatureCommandType.List); } [Fact] - public void should_throw_when_more_than_one_unparsed_arg_is_passed() + public void Should_throw_when_more_than_one_unparsed_arg_is_passed() { - reset(); - unparsedArgs.Add("wtf"); - unparsedArgs.Add("bbq"); + Reset(); + _unparsedArgs.Add("wtf"); + _unparsedArgs.Add("bbq"); var errored = false; Exception error = null; try { - because(); + _because(); } catch (Exception ex) { @@ -147,75 +147,75 @@ public void should_throw_when_more_than_one_unparsed_arg_is_passed() } [Fact] - public void should_accept_enable_as_the_subcommand() + public void Should_accept_enable_as_the_subcommand() { - reset(); - unparsedArgs.Add("enable"); - because(); + Reset(); + _unparsedArgs.Add("enable"); + _because(); - configuration.FeatureCommand.Command.ShouldEqual(FeatureCommandType.enable); + Configuration.FeatureCommand.Command.ShouldEqual(FeatureCommandType.Enable); } [Fact] - public void should_accept_disable_as_the_subcommand() + public void Should_accept_disable_as_the_subcommand() { - reset(); - unparsedArgs.Add("disable"); - because(); + Reset(); + _unparsedArgs.Add("disable"); + _because(); - configuration.FeatureCommand.Command.ShouldEqual(FeatureCommandType.disable); + Configuration.FeatureCommand.Command.ShouldEqual(FeatureCommandType.Disable); } [Fact] - public void should_set_unrecognized_values_to_list_as_the_subcommand() + public void Should_set_unrecognized_values_to_list_as_the_subcommand() { - reset(); - unparsedArgs.Add("wtf"); - because(); + Reset(); + _unparsedArgs.Add("wtf"); + _because(); - configuration.FeatureCommand.Command.ShouldEqual(FeatureCommandType.list); + Configuration.FeatureCommand.Command.ShouldEqual(FeatureCommandType.List); } [Fact] - public void should_default_to_list_as_the_subcommand() + public void Should_default_to_list_as_the_subcommand() { - reset(); - because(); + Reset(); + _because(); - configuration.FeatureCommand.Command.ShouldEqual(FeatureCommandType.list); + Configuration.FeatureCommand.Command.ShouldEqual(FeatureCommandType.List); } [Fact] - public void should_handle_passing_in_an_empty_string() + public void Should_handle_passing_in_an_empty_string() { - reset(); - unparsedArgs.Add(" "); - because(); + Reset(); + _unparsedArgs.Add(" "); + _because(); - configuration.FeatureCommand.Command.ShouldEqual(FeatureCommandType.list); + Configuration.FeatureCommand.Command.ShouldEqual(FeatureCommandType.List); } } - public class when_handling_validation : ChocolateyFeatureCommandSpecsBase + public class When_validating : ChocolateyFeatureCommandSpecsBase { - private Action because; + private Action _because; public override void Because() { - because = () => command.handle_validation(configuration); + _because = () => Command.Validate(Configuration); } [Fact] - public void should_throw_when_command_is_not_list_and_name_is_not_set() + public void Should_throw_when_command_is_not_list_and_name_is_not_set() { - configuration.FeatureCommand.Command = FeatureCommandType.unknown; - configuration.FeatureCommand.Name = ""; + Configuration.FeatureCommand.Command = FeatureCommandType.Unknown; + Configuration.FeatureCommand.Name = ""; var errored = false; Exception error = null; try { - because(); + _because(); } catch (Exception ex) { @@ -226,71 +226,79 @@ public void should_throw_when_command_is_not_list_and_name_is_not_set() errored.ShouldBeTrue(); error.ShouldNotBeNull(); error.ShouldBeType(); - error.Message.ShouldEqual("When specifying the subcommand '{0}', you must also specify --name.".format_with(configuration.FeatureCommand.Command.to_string())); + error.Message.ShouldEqual("When specifying the subcommand '{0}', you must also specify --name.".FormatWith(Configuration.FeatureCommand.Command.ToStringSafe().ToLower())); } [Fact] - public void should_continue_when_command_is_list_and_name_is_not_set() + public void Should_continue_when_command_is_list_and_name_is_not_set() { - configuration.FeatureCommand.Command = FeatureCommandType.list; - configuration.SourceCommand.Name = ""; - because(); + Configuration.FeatureCommand.Command = FeatureCommandType.List; + Configuration.SourceCommand.Name = ""; + _because(); } [Fact] - public void should_continue_when_command_is_not_list_and_name_is_set() + public void Should_continue_when_command_is_not_list_and_name_is_set() { - configuration.FeatureCommand.Command = FeatureCommandType.list; - configuration.SourceCommand.Name = "bob"; - because(); + Configuration.FeatureCommand.Command = FeatureCommandType.List; + Configuration.SourceCommand.Name = "bob"; + _because(); } } - public class when_noop_is_called : ChocolateyFeatureCommandSpecsBase + public class When_noop_is_called : ChocolateyFeatureCommandSpecsBase { public override void Because() { - command.noop(configuration); + Command.DryRun(Configuration); } [Fact] - public void should_call_service_noop() + public void Should_call_service_noop() { - configSettingsService.Verify(c => c.noop(configuration), Times.Once); + ConfigSettingsService.Verify(c => c.DryRun(Configuration), Times.Once); } } - public class when_run_is_called : ChocolateyFeatureCommandSpecsBase + public class When_run_is_called : ChocolateyFeatureCommandSpecsBase { - private Action because; + private Action _because; public override void Because() { - because = () => command.run(configuration); + _because = () => Command.Run(Configuration); } [Fact] - public void should_call_service_source_list_when_command_is_list() + public void Should_call_service_feature_list_when_command_is_list() { - configuration.FeatureCommand.Command = FeatureCommandType.list; - because(); - configSettingsService.Verify(c => c.feature_list(configuration), Times.Once); + Configuration.FeatureCommand.Command = FeatureCommandType.List; + _because(); + ConfigSettingsService.Verify(c => c.ListFeatures(Configuration), Times.Once); } [Fact] - public void should_call_service_source_disable_when_command_is_disable() + public void Should_call_service_feature_get_when_command_is_get() { - configuration.FeatureCommand.Command = FeatureCommandType.disable; - because(); - configSettingsService.Verify(c => c.feature_disable(configuration), Times.Once); + Configuration.FeatureCommand.Command = FeatureCommandType.Get; + _because(); + ConfigSettingsService.Verify(c => c.GetFeature(Configuration), Times.Once); } [Fact] - public void should_call_service_source_enable_when_command_is_enable() + public void Should_call_service_feature_disable_when_command_is_disable() { - configuration.FeatureCommand.Command = FeatureCommandType.enable; - because(); - configSettingsService.Verify(c => c.feature_enable(configuration), Times.Once); + Configuration.FeatureCommand.Command = FeatureCommandType.Disable; + _because(); + ConfigSettingsService.Verify(c => c.DisableFeature(Configuration), Times.Once); + } + + [Fact] + public void Should_call_service_feature_enable_when_command_is_enable() + { + Configuration.FeatureCommand.Command = FeatureCommandType.Enable; + _because(); + ConfigSettingsService.Verify(c => c.EnableFeature(Configuration), Times.Once); } } } diff --git a/src/chocolatey.tests/infrastructure.app/commands/ChocolateyHelpCommandSpecs.cs b/src/chocolatey.tests/infrastructure.app/commands/ChocolateyHelpCommandSpecs.cs index 6f4a4939b9..856235f681 100644 --- a/src/chocolatey.tests/infrastructure.app/commands/ChocolateyHelpCommandSpecs.cs +++ b/src/chocolatey.tests/infrastructure.app/commands/ChocolateyHelpCommandSpecs.cs @@ -37,7 +37,7 @@ public override void Context() } } - public class when_implementing_command_for : ChocolateyHelpCommandSpecsBase + public class When_implementing_command_for : ChocolateyHelpCommandSpecsBase { private List results; @@ -47,7 +47,7 @@ public override void Because() } [Fact] - public void should_implement_help() + public void Should_implement_help() { results.ShouldContain("help"); } diff --git a/src/chocolatey.tests/infrastructure.app/commands/ChocolateyInfoCommandSpecs.cs b/src/chocolatey.tests/infrastructure.app/commands/ChocolateyInfoCommandSpecs.cs index 308b8db85e..7c7b96e406 100644 --- a/src/chocolatey.tests/infrastructure.app/commands/ChocolateyInfoCommandSpecs.cs +++ b/src/chocolatey.tests/infrastructure.app/commands/ChocolateyInfoCommandSpecs.cs @@ -32,185 +32,240 @@ public class ChocolateyInfoCommandSpecs [ConcernFor("info")] public abstract class ChocolateyInfoCommandSpecsBase : TinySpec { - protected ChocolateyInfoCommand command; - protected Mock packageService = new Mock(); - protected ChocolateyConfiguration configuration = new ChocolateyConfiguration(); + protected ChocolateyInfoCommand Command; + protected Mock PackageService = new Mock(); + protected ChocolateyConfiguration Configuration = new ChocolateyConfiguration(); public override void Context() { - configuration.Sources = "bob"; - command = new ChocolateyInfoCommand(packageService.Object); + Configuration.Sources = "bob"; + Command = new ChocolateyInfoCommand(PackageService.Object); } } - public class when_implementing_command_for : ChocolateyInfoCommandSpecsBase + public class When_implementing_command_for : ChocolateyInfoCommandSpecsBase { - private List results; + private List _results; public override void Because() { - results = command.GetType().GetCustomAttributes(typeof(CommandForAttribute), false).Cast().Select(a => a.CommandName).ToList(); + _results = Command.GetType().GetCustomAttributes(typeof(CommandForAttribute), false).Cast().Select(a => a.CommandName).ToList(); } [Fact] - public void should_implement_info() + public void Should_implement_info() { - results.ShouldContain("info"); + _results.ShouldContain("info"); } } - public class when_configurating_the_argument_parser : ChocolateyInfoCommandSpecsBase + public class When_configurating_the_argument_parser : ChocolateyInfoCommandSpecsBase { - private OptionSet optionSet; + private OptionSet _optionSet; public override void Context() { base.Context(); - optionSet = new OptionSet(); + _optionSet = new OptionSet(); } public override void Because() { - command.configure_argument_parser(optionSet, configuration); + Command.ConfigureArgumentParser(_optionSet, Configuration); } [Fact] - public void should_add_source_to_the_option_set() + public void Should_add_source_to_the_option_set() { - optionSet.Contains("source").ShouldBeTrue(); + _optionSet.Contains("source").ShouldBeTrue(); } [Fact] - public void should_add_short_version_of_source_to_the_option_set() + public void Should_add_short_version_of_source_to_the_option_set() { - optionSet.Contains("s").ShouldBeTrue(); + _optionSet.Contains("s").ShouldBeTrue(); } [Fact] - public void should_add_localonly_to_the_option_set() + public void Should_add_localonly_to_the_option_set() { - optionSet.Contains("localonly").ShouldBeTrue(); + _optionSet.Contains("localonly").ShouldBeTrue(); } [Fact] - public void should_add_short_version_of_localonly_to_the_option_set() + public void Should_add_short_version_of_localonly_to_the_option_set() { - optionSet.Contains("l").ShouldBeTrue(); + _optionSet.Contains("l").ShouldBeTrue(); } [Fact] - public void should_add_prerelease_to_the_option_set() + public void Should_add_prerelease_to_the_option_set() { - optionSet.Contains("prerelease").ShouldBeTrue(); + _optionSet.Contains("prerelease").ShouldBeTrue(); } [Fact] - public void should_add_short_version_of_prerelease_to_the_option_set() + public void Should_add_short_version_of_prerelease_to_the_option_set() { - optionSet.Contains("pre").ShouldBeTrue(); + _optionSet.Contains("pre").ShouldBeTrue(); } [Fact] - public void should_add_user_to_the_option_set() + public void Should_add_user_to_the_option_set() { - optionSet.Contains("user").ShouldBeTrue(); + _optionSet.Contains("user").ShouldBeTrue(); } [Fact] - public void should_add_short_version_of_user_to_the_option_set() + public void Should_add_short_version_of_user_to_the_option_set() { - optionSet.Contains("u").ShouldBeTrue(); + _optionSet.Contains("u").ShouldBeTrue(); } [Fact] - public void should_add_password_to_the_option_set() + public void Should_add_password_to_the_option_set() { - optionSet.Contains("password").ShouldBeTrue(); + _optionSet.Contains("password").ShouldBeTrue(); } [Fact] - public void should_add_short_version_of_password_to_the_option_set() + public void Should_add_short_version_of_password_to_the_option_set() { - optionSet.Contains("p").ShouldBeTrue(); + _optionSet.Contains("p").ShouldBeTrue(); } } - public class when_handling_additional_argument_parsing : ChocolateyInfoCommandSpecsBase + public class When_handling_validation : ChocolateyInfoCommandSpecsBase { - private readonly IList unparsedArgs = new List(); - private readonly string source = "https://somewhereoutthere"; - private Action because; + private Exception _error = null; + private Action _because; public override void Context() { base.Context(); - unparsedArgs.Add("pkg1"); - unparsedArgs.Add("pkg2"); - configuration.Sources = source; } public override void Because() { - because = () => command.handle_additional_argument_parsing(unparsedArgs, configuration); + _because = () => Command.Validate(Configuration); } [Fact] - public void should_set_unparsed_arguments_to_configuration_input() + public void Show_throw_when_package_id_is_not_set() { - because(); - configuration.Input.ShouldEqual("pkg1 pkg2"); + Configuration.Input = ""; + _error = null; + + try + { + _because(); + } + catch (Exception ex) + { + _error = ex; + } + + _error.ShouldNotBeNull(); + _error.ShouldBeType(); + _error.Message.ShouldContain("A single package name is required to run the choco info command."); + } + + [Fact] + public void Should_throw_when_multiple_package_ids_set() + { + Configuration.Input = "foo bar"; + _error = null; + + try + { + _because(); + } + catch (Exception ex) + { + _error = ex; + } + + _error.ShouldNotBeNull(); + _error.ShouldBeType(); + _error.Message.ShouldContain("Only a single package name can be passed to the choco info command."); + } + } + public class When_handling_additional_argument_parsing : ChocolateyInfoCommandSpecsBase + { + private readonly IList _unparsedArgs = new List(); + private readonly string _source = "https://somewhereoutthere"; + private Action _because; + + public override void Context() + { + base.Context(); + _unparsedArgs.Add("pkg1"); + _unparsedArgs.Add("pkg2"); + Configuration.Sources = _source; + } + + public override void Because() + { + _because = () => Command.ParseAdditionalArguments(_unparsedArgs, Configuration); + } + + [Fact] + public void Should_set_unparsed_arguments_to_configuration_input() + { + _because(); + Configuration.Input.ShouldEqual("pkg1 pkg2"); } [Fact] - public void should_leave_source_as_set() + public void Should_leave_source_as_set() { - configuration.ListCommand.LocalOnly = false; - because(); - configuration.Sources.ShouldEqual(source); + Configuration.ListCommand.LocalOnly = false; + _because(); + Configuration.Sources.ShouldEqual(_source); } [Fact] - public void should_set_exact_to_true() + public void Should_set_exact_to_true() { - configuration.ListCommand.Exact = false; - because(); - configuration.ListCommand.Exact.ShouldBeTrue(); + Configuration.ListCommand.Exact = false; + _because(); + Configuration.ListCommand.Exact.ShouldBeTrue(); } [Fact] - public void should_set_verbose_to_true() + public void Should_set_verbose_to_true() { - configuration.Verbose = false; - because(); - configuration.Verbose.ShouldBeTrue(); + Configuration.Verbose = false; + _because(); + Configuration.Verbose.ShouldBeTrue(); } } - public class when_noop_is_called : ChocolateyInfoCommandSpecsBase + public class When_noop_is_called : ChocolateyInfoCommandSpecsBase { public override void Because() { - command.noop(configuration); + Command.DryRun(Configuration); } [Fact] - public void should_call_service_list_noop() + public void Should_call_service_list_noop() { - packageService.Verify(c => c.list_noop(configuration), Times.Once); + PackageService.Verify(c => c.ListDryRun(Configuration), Times.Once); } } - public class when_run_is_called : ChocolateyInfoCommandSpecsBase + public class When_run_is_called : ChocolateyInfoCommandSpecsBase { public override void Because() { - command.run(configuration); + Command.Run(Configuration); } [Fact] - public void should_call_service_list_run() + public void Should_call_service_list_run() { - packageService.Verify(c => c.list_run(configuration), Times.Once); + PackageService.Verify(c => c.List(Configuration), Times.Once); } } } diff --git a/src/chocolatey.tests/infrastructure.app/commands/ChocolateyInstallCommandSpecs.cs b/src/chocolatey.tests/infrastructure.app/commands/ChocolateyInstallCommandSpecs.cs index f010beb6c8..7a97bbf86d 100644 --- a/src/chocolatey.tests/infrastructure.app/commands/ChocolateyInstallCommandSpecs.cs +++ b/src/chocolatey.tests/infrastructure.app/commands/ChocolateyInstallCommandSpecs.cs @@ -44,7 +44,7 @@ public override void Context() } } - public class when_implementing_command_for : ChocolateyInstallCommandSpecsBase + public class When_implementing_command_for : ChocolateyInstallCommandSpecsBase { private List results; @@ -54,13 +54,13 @@ public override void Because() } [Fact] - public void should_implement_install() + public void Should_implement_install() { - results.ShouldContain(CommandNameType.install.to_string()); + results.ShouldContain("install"); } } - public class when_configurating_the_argument_parser : ChocolateyInstallCommandSpecsBase + public class When_configurating_the_argument_parser : ChocolateyInstallCommandSpecsBase { private OptionSet optionSet; @@ -72,191 +72,191 @@ public override void Context() public override void Because() { - command.configure_argument_parser(optionSet, configuration); + command.ConfigureArgumentParser(optionSet, configuration); } [Fact] - public void should_add_source_to_the_option_set() + public void Should_add_source_to_the_option_set() { optionSet.Contains("source").ShouldBeTrue(); } [Fact] - public void should_add_short_version_of_source_to_the_option_set() + public void Should_add_short_version_of_source_to_the_option_set() { optionSet.Contains("s").ShouldBeTrue(); } [Fact] - public void should_add_version_to_the_option_set() + public void Should_add_version_to_the_option_set() { optionSet.Contains("version").ShouldBeTrue(); } [Fact] - public void should_allow_insensitive_case_Version_to_the_option_set() + public void Should_allow_insensitive_case_Version_to_the_option_set() { optionSet.Contains("Version").ShouldBeTrue(); } [Fact] - public void should_add_prerelease_to_the_option_set() + public void Should_add_prerelease_to_the_option_set() { optionSet.Contains("prerelease").ShouldBeTrue(); } [Fact] - public void should_add_short_version_of_prerelease_to_the_option_set() + public void Should_add_short_version_of_prerelease_to_the_option_set() { optionSet.Contains("pre").ShouldBeTrue(); } [Fact] - public void should_add_installargs_to_the_option_set() + public void Should_add_installargs_to_the_option_set() { optionSet.Contains("installarguments").ShouldBeTrue(); } [Fact] - public void should_add_short_version_of_installargs_to_the_option_set() + public void Should_add_short_version_of_installargs_to_the_option_set() { optionSet.Contains("ia").ShouldBeTrue(); } [Fact] - public void should_add_overrideargs_to_the_option_set() + public void Should_add_overrideargs_to_the_option_set() { optionSet.Contains("overridearguments").ShouldBeTrue(); } [Fact] - public void should_add_short_version_of_overrideargs_to_the_option_set() + public void Should_add_short_version_of_overrideargs_to_the_option_set() { optionSet.Contains("o").ShouldBeTrue(); } [Fact] - public void should_add_notsilent_to_the_option_set() + public void Should_add_notsilent_to_the_option_set() { optionSet.Contains("notsilent").ShouldBeTrue(); } [Fact] - public void should_add_packageparameters_to_the_option_set() + public void Should_add_packageparameters_to_the_option_set() { optionSet.Contains("packageparameters").ShouldBeTrue(); } [Fact] - public void should_add_short_version_of_packageparameters_to_the_option_set() + public void Should_add_short_version_of_packageparameters_to_the_option_set() { optionSet.Contains("params").ShouldBeTrue(); } [Fact] - public void should_add_applyPackageParametersToDependencies_to_the_option_set() + public void Should_add_applyPackageParametersToDependencies_to_the_option_set() { optionSet.Contains("apply-package-parameters-to-dependencies").ShouldBeTrue(); } [Fact] - public void should_add_applyInstallArgumentsToDependencies_to_the_option_set() + public void Should_add_applyInstallArgumentsToDependencies_to_the_option_set() { optionSet.Contains("apply-install-arguments-to-dependencies").ShouldBeTrue(); } [Fact] - public void should_add_ignoredependencies_to_the_option_set() + public void Should_add_ignoredependencies_to_the_option_set() { optionSet.Contains("ignoredependencies").ShouldBeTrue(); } [Fact] - public void should_add_short_version_of_ignoredependencies_to_the_option_set() + public void Should_add_short_version_of_ignoredependencies_to_the_option_set() { optionSet.Contains("i").ShouldBeTrue(); } [Fact] - public void should_add_forcedependencies_to_the_option_set() + public void Should_add_forcedependencies_to_the_option_set() { optionSet.Contains("forcedependencies").ShouldBeTrue(); } [Fact] - public void should_add_short_version_of_forcedependencies_to_the_option_set() + public void Should_add_short_version_of_forcedependencies_to_the_option_set() { optionSet.Contains("x").ShouldBeTrue(); } [Fact] - public void should_add_skippowershell_to_the_option_set() + public void Should_add_skippowershell_to_the_option_set() { optionSet.Contains("skippowershell").ShouldBeTrue(); } [Fact] - public void should_add_short_version_of_skippowershell_to_the_option_set() + public void Should_add_short_version_of_skippowershell_to_the_option_set() { optionSet.Contains("n").ShouldBeTrue(); } [Fact] - public void should_add_user_to_the_option_set() + public void Should_add_user_to_the_option_set() { optionSet.Contains("user").ShouldBeTrue(); } [Fact] - public void should_add_short_version_of_user_to_the_option_set() + public void Should_add_short_version_of_user_to_the_option_set() { optionSet.Contains("u").ShouldBeTrue(); } [Fact] - public void should_add_password_to_the_option_set() + public void Should_add_password_to_the_option_set() { optionSet.Contains("password").ShouldBeTrue(); } [Fact] - public void should_add_short_version_of_password_to_the_option_set() + public void Should_add_short_version_of_password_to_the_option_set() { optionSet.Contains("p").ShouldBeTrue(); } [Fact] - public void should_add_pin_to_the_option_set() + public void Should_add_pin_to_the_option_set() { optionSet.Contains("pinpackage").ShouldBeTrue(); } [Fact] - public void should_add_long_version_of_pin_to_the_option_set() + public void Should_add_long_version_of_pin_to_the_option_set() { optionSet.Contains("pin-package").ShouldBeTrue(); } [Fact] - public void should_add_short_version_of_pin_to_the_option_set() + public void Should_add_short_version_of_pin_to_the_option_set() { optionSet.Contains("pin").ShouldBeTrue(); } - + [Fact] - public void should_add_skip_hooks_to_the_option_set() + public void Should_add_skip_hooks_to_the_option_set() { optionSet.Contains("skip-hooks").ShouldBeTrue(); } [Fact] - public void should_add_short_version_of_skip_hooks_to_the_option_set() + public void Should_add_short_version_of_skip_hooks_to_the_option_set() { optionSet.Contains("skiphooks").ShouldBeTrue(); } } - public class when_handling_additional_argument_parsing : ChocolateyInstallCommandSpecsBase + public class When_handling_additional_argument_parsing : ChocolateyInstallCommandSpecsBase { private readonly IList unparsedArgs = new List(); @@ -269,24 +269,24 @@ public override void Context() public override void Because() { - command.handle_additional_argument_parsing(unparsedArgs, configuration); + command.ParseAdditionalArguments(unparsedArgs, configuration); } [Fact] - public void should_set_unparsed_arguments_to_the_package_names() + public void Should_set_unparsed_arguments_to_the_package_names() { configuration.PackageNames.ShouldEqual("pkg1;pkg2"); } } - public class when_handling_validation : ChocolateyInstallCommandSpecsBase + public class When_validating : ChocolateyInstallCommandSpecsBase { public override void Because() { } [Fact] - public void should_throw_when_packagenames_is_not_set() + public void Should_throw_when_packagenames_is_not_set() { configuration.PackageNames = ""; var errored = false; @@ -294,7 +294,7 @@ public void should_throw_when_packagenames_is_not_set() try { - command.handle_validation(configuration); + command.Validate(configuration); } catch (Exception ex) { @@ -308,38 +308,38 @@ public void should_throw_when_packagenames_is_not_set() } [Fact] - public void should_continue_when_packagenames_is_set() + public void Should_continue_when_packagenames_is_set() { configuration.PackageNames = "bob"; - command.handle_validation(configuration); + command.Validate(configuration); } } - public class when_noop_is_called : ChocolateyInstallCommandSpecsBase + public class When_noop_is_called : ChocolateyInstallCommandSpecsBase { public override void Because() { - command.noop(configuration); + command.DryRun(configuration); } [Fact] - public void should_call_service_install_noop() + public void Should_call_service_install_noop() { - packageService.Verify(c => c.install_noop(configuration), Times.Once); + packageService.Verify(c => c.InstallDryRun(configuration), Times.Once); } } - public class when_run_is_called : ChocolateyInstallCommandSpecsBase + public class When_run_is_called : ChocolateyInstallCommandSpecsBase { public override void Because() { - command.run(configuration); + command.Run(configuration); } [Fact] - public void should_call_service_install_run() + public void Should_call_service_install_run() { - packageService.Verify(c => c.install_run(configuration), Times.Once); + packageService.Verify(c => c.Install(configuration), Times.Once); } } } diff --git a/src/chocolatey.tests/infrastructure.app/commands/ChocolateyListCommandSpecs.cs b/src/chocolatey.tests/infrastructure.app/commands/ChocolateyListCommandSpecs.cs index 525814f770..8ec8ce9876 100644 --- a/src/chocolatey.tests/infrastructure.app/commands/ChocolateyListCommandSpecs.cs +++ b/src/chocolatey.tests/infrastructure.app/commands/ChocolateyListCommandSpecs.cs @@ -31,69 +31,69 @@ public static class ChocolateyListCommandSpecs [ConcernFor("list")] public abstract class ChocolateyListCommandSpecsBase : TinySpec { - protected ChocolateyListCommand command; - protected Mock packageService = new Mock(); - protected ChocolateyConfiguration configuration = new ChocolateyConfiguration(); + protected ChocolateyListCommand Command; + protected Mock PackageService = new Mock(); + protected ChocolateyConfiguration Configuration = new ChocolateyConfiguration(); public override void Context() { - command = new ChocolateyListCommand(packageService.Object); + Command = new ChocolateyListCommand(PackageService.Object); } } - public class when_implementing_command_for : ChocolateyListCommandSpecsBase + public class When_implementing_command_for : ChocolateyListCommandSpecsBase { - private List results; + private List _results; public override void Because() { - results = command.GetType().GetCustomAttributes(typeof(CommandForAttribute), false).Cast().Select(a => a.CommandName).ToList(); + _results = Command.GetType().GetCustomAttributes(typeof(CommandForAttribute), false).Cast().Select(a => a.CommandName).ToList(); } [Fact] - public void should_implement_list() + public void Should_implement_list() { - results.ShouldContain("list"); + _results.ShouldContain("list"); } [Fact] - public void should_not_implement_search() + public void Should_not_implement_search() { - results.ShouldNotContain("search"); + _results.ShouldNotContain("search"); } [Fact] - public void should_not_implement_find() + public void Should_not_implement_find() { - results.ShouldNotContain("find"); + _results.ShouldNotContain("find"); } - public class when_configurating_the_argument_parser : ChocolateyListCommandSpecsBase + public class When_configurating_the_argument_parser : ChocolateyListCommandSpecsBase { - private OptionSet optionSet; + private OptionSet _optionSet; public override void Context() { base.Context(); - optionSet = new OptionSet(); + _optionSet = new OptionSet(); } public override void Because() { - command.configure_argument_parser(optionSet, configuration); + Command.ConfigureArgumentParser(_optionSet, Configuration); } + [NUnit.Framework.TestCase("source")] + [NUnit.Framework.TestCase("s")] [NUnit.Framework.TestCase("prerelease")] [NUnit.Framework.TestCase("pre")] [NUnit.Framework.TestCase("includeprograms")] [NUnit.Framework.TestCase("i")] - public void should_add_to_option_set(string option) + public void Should_add_to_option_set(string option) { - optionSet.Contains(option).ShouldBeTrue(); + _optionSet.Contains(option).ShouldBeTrue(); } - [NUnit.Framework.TestCase("source")] - [NUnit.Framework.TestCase("s")] [NUnit.Framework.TestCase("localonly")] [NUnit.Framework.TestCase("l")] [NUnit.Framework.TestCase("user")] @@ -102,101 +102,143 @@ public void should_add_to_option_set(string option) [NUnit.Framework.TestCase("p")] [NUnit.Framework.TestCase("allversions")] [NUnit.Framework.TestCase("a")] - public void should_not_add_to_option_set(string option) + public void Should_not_add_to_option_set(string option) { - optionSet.Contains(option).ShouldBeFalse(); + _optionSet.Contains(option).ShouldBeFalse(); } } - public class when_handling_additional_argument_parsing : ChocolateyListCommandSpecsBase + public class When_handling_additional_argument_parsing : ChocolateyListCommandSpecsBase { - private readonly IList unparsedArgs = new List(); - private readonly string source = "https://somewhereoutthere"; - private Action because; + private readonly IList _unparsedArgs = new List(); + private readonly string _source = "https://somewhereoutthere"; + private Action _because; public override void Context() { base.Context(); - unparsedArgs.Add("pkg1"); - unparsedArgs.Add("pkg2"); - unparsedArgs.Add("-l"); - unparsedArgs.Add("--local-only"); - unparsedArgs.Add("--localonly"); - configuration.Sources = source; + _unparsedArgs.Add("pkg1"); + _unparsedArgs.Add("pkg2"); + _unparsedArgs.Add("-l"); + _unparsedArgs.Add("-lo"); + _unparsedArgs.Add("--local-only"); + _unparsedArgs.Add("--localonly"); + _unparsedArgs.Add("-li"); + _unparsedArgs.Add("-lai"); + Configuration.Sources = _source; } public override void Because() { - because = () => command.handle_additional_argument_parsing(unparsedArgs, configuration); + _because = () => Command.ParseAdditionalArguments(_unparsedArgs, Configuration); + } + + [NUnit.Framework.TestCase("-l")] + [NUnit.Framework.TestCase("-lo")] + [NUnit.Framework.TestCase("--local-only")] + [NUnit.Framework.TestCase("--localonly")] + [NUnit.Framework.TestCase("-li")] + [NUnit.Framework.TestCase("-lai")] + public void Should_throw_on_unsupported_argument(string argument) + { + Configuration.RegularOutput = true; + var errored = false; + Exception error = null; + try + { + _because(); + } + catch (Exception ex) + { + errored = true; + error = ex; + } + + errored.ShouldBeTrue(); + error.ShouldNotBeNull(); + error.ShouldBeType(); } [Fact] - public void should_set_unparsed_arguments_to_configuration_input() + public void Should_set_unparsed_arguments_to_configuration_input_with_limit_output() { - because(); - configuration.Input.ShouldEqual("pkg1 pkg2"); + Configuration.RegularOutput = false; + _because(); + Configuration.Input.ShouldEqual("pkg1 pkg2"); } [NUnit.Framework.TestCase("-l")] + [NUnit.Framework.TestCase("-lo")] [NUnit.Framework.TestCase("--local-only")] [NUnit.Framework.TestCase("--localonly")] - public void should_output_warning_message_about_unsupported_argument(string argument) + public void Should_output_warning_message_about_unsupported_argument_with_limit_output(string argument) + { + Configuration.RegularOutput = false; + _because(); + MockLogger.Messages.Keys.ShouldContain("Warn"); + MockLogger.Messages["Warn"].ShouldContain("Ignoring the argument {0}. This argument is unsupported for locally installed packages.".FormatWith(argument)); + } + + [NUnit.Framework.TestCase("-li")] + [NUnit.Framework.TestCase("-lai")] + public void Should_output_warning_message_about_unsupported_argument_and_set_include_programs_with_limit_output(string argument) { - because(); + Configuration.RegularOutput = false; + _because(); MockLogger.Messages.Keys.ShouldContain("Warn"); - MockLogger.Messages["Warn"].ShouldContain(@" -UNSUPPORTED ARGUMENT: Ignoring the argument {0}. This argument is unsupported for locally installed packages, and will be treated as a package name in Chocolatey CLI v3!".format_with(argument)); + MockLogger.Messages["Warn"].ShouldContain("Ignoring the argument {0}. This argument is unsupported for locally installed packages.".FormatWith(argument)); + Configuration.ListCommand.IncludeRegistryPrograms.ShouldBeTrue(); } } - public class when_noop_is_called_with_list_command : ChocolateyListCommandSpecsBase + public class When_noop_is_called_with_list_command : ChocolateyListCommandSpecsBase { public override void Context() { base.Context(); - configuration.CommandName = "search"; - configuration.ListCommand.LocalOnly = false; + Configuration.CommandName = "search"; + Configuration.ListCommand.LocalOnly = false; } public override void Because() { - command.noop(configuration); + Command.DryRun(Configuration); } [Fact] - public void should_call_service_list_noop() + public void Should_call_service_list_noop() { - packageService.Verify(c => c.list_noop(configuration), Times.Once); + PackageService.Verify(c => c.ListDryRun(Configuration), Times.Once); } [Fact] - public void should_not_report_any_warning_messages() + public void Should_not_report_any_warning_messages() { MockLogger.Messages.Keys.ShouldNotContain("Warn"); } } - public class when_run_is_called_with_search_command_and_local_only : ChocolateyListCommandSpecsBase + public class When_run_is_called_with_search_command_and_local_only : ChocolateyListCommandSpecsBase { public override void Context() { base.Context(); - configuration.CommandName = "list"; + Configuration.CommandName = "list"; } public override void Because() { - command.run(configuration); + Command.Run(Configuration); } [Fact] - public void should_call_service_list_run() + public void Should_call_service_list_run() { - packageService.Verify(c => c.list_run(configuration), Times.Once); + PackageService.Verify(c => c.List(Configuration), Times.Once); } [Fact] - public void should_not_report_any_warning_messages() + public void Should_not_report_any_warning_messages() { MockLogger.Messages.Keys.ShouldNotContain("Warn"); } diff --git a/src/chocolatey.tests/infrastructure.app/commands/ChocolateyNewCommandSpecs.cs b/src/chocolatey.tests/infrastructure.app/commands/ChocolateyNewCommandSpecs.cs index 0cb53ee051..371236f196 100644 --- a/src/chocolatey.tests/infrastructure.app/commands/ChocolateyNewCommandSpecs.cs +++ b/src/chocolatey.tests/infrastructure.app/commands/ChocolateyNewCommandSpecs.cs @@ -43,7 +43,7 @@ public override void Context() } } - public class when_implementing_command_for : ChocolateyNewCommandSpecsBase + public class When_implementing_command_for : ChocolateyNewCommandSpecsBase { private List results; @@ -53,13 +53,13 @@ public override void Because() } [Fact] - public void should_implement_new() + public void Should_implement_new() { results.ShouldContain("new"); } } - public class when_configurating_the_argument_parser : ChocolateyNewCommandSpecsBase + public class When_configurating_the_argument_parser : ChocolateyNewCommandSpecsBase { private OptionSet optionSet; @@ -71,54 +71,54 @@ public override void Context() public override void Because() { - command.configure_argument_parser(optionSet, configuration); + command.ConfigureArgumentParser(optionSet, configuration); } [Fact] - public void should_add_automaticpackage_to_the_option_set() + public void Should_add_automaticpackage_to_the_option_set() { optionSet.Contains("automaticpackage").ShouldBeTrue(); } [Fact] - public void should_add_short_version_of_automaticpackage_to_the_option_set() + public void Should_add_short_version_of_automaticpackage_to_the_option_set() { optionSet.Contains("a").ShouldBeTrue(); } [Fact] - public void should_add_name_to_the_option_set() + public void Should_add_name_to_the_option_set() { optionSet.Contains("name").ShouldBeTrue(); } [Fact] - public void should_add_version_to_the_option_set() + public void Should_add_version_to_the_option_set() { optionSet.Contains("version").ShouldBeTrue(); } [Fact] - public void should_add_maintainer_to_the_option_set() + public void Should_add_maintainer_to_the_option_set() { optionSet.Contains("maintainer").ShouldBeTrue(); } [Fact] - public void should_add_outputdirectory_to_the_option_set() + public void Should_add_outputdirectory_to_the_option_set() { optionSet.Contains("outputdirectory").ShouldBeTrue(); } } - public class when_handling_additional_argument_parsing : ChocolateyNewCommandSpecsBase + public class When_handling_additional_argument_parsing : ChocolateyNewCommandSpecsBase { private readonly IList unparsedArgs = new List(); private Action because; public override void Because() { - because = () => command.handle_additional_argument_parsing(unparsedArgs, configuration); + because = () => command.ParseAdditionalArguments(unparsedArgs, configuration); } private void reset() @@ -129,7 +129,7 @@ private void reset() } [Fact] - public void should_not_set_template_properties_if_none_have_been_defined() + public void Should_not_set_template_properties_if_none_have_been_defined() { reset(); because(); @@ -137,7 +137,7 @@ public void should_not_set_template_properties_if_none_have_been_defined() } [Fact] - public void should_set_template_properties_when_args_are_separated_by_equals() + public void Should_set_template_properties_when_args_are_separated_by_equals() { reset(); unparsedArgs.Add("bob=new"); @@ -151,7 +151,7 @@ public void should_set_template_properties_when_args_are_separated_by_equals() } [Fact] - public void should_set_template_properties_only_once() + public void Should_set_template_properties_only_once() { reset(); unparsedArgs.Add("bob=one"); @@ -166,7 +166,7 @@ public void should_set_template_properties_only_once() } [Fact] - public void should_ignore_casing_differences_when_setting_template_properties() + public void Should_ignore_casing_differences_when_setting_template_properties() { reset(); unparsedArgs.Add("bob=one"); @@ -181,7 +181,7 @@ public void should_ignore_casing_differences_when_setting_template_properties() } [Fact] - public void should_not_set_template_properties_when_args_are_not_separated_by_equals() + public void Should_not_set_template_properties_when_args_are_not_separated_by_equals() { reset(); configuration.NewCommand.Name = "bill"; @@ -197,7 +197,7 @@ public void should_not_set_template_properties_when_args_are_not_separated_by_eq } [Fact] - public void should_not_set_override_configuration_Name_when_unparsed_without_equals() + public void Should_not_set_override_configuration_Name_when_unparsed_without_equals() { reset(); configuration.NewCommand.Name = "bill"; @@ -213,7 +213,7 @@ public void should_not_set_override_configuration_Name_when_unparsed_without_equ } [Fact] - public void should_not_set_override_configuration_Name_when_package_name_is_also_passed() + public void Should_not_set_override_configuration_Name_when_package_name_is_also_passed() { reset(); configuration.NewCommand.Name = "bill"; @@ -228,7 +228,7 @@ public void should_not_set_override_configuration_Name_when_package_name_is_also } [Fact] - public void should_set_template_properties_when_args_are_separated_by_equals_with_spaces() + public void Should_set_template_properties_when_args_are_separated_by_equals_with_spaces() { reset(); unparsedArgs.Add("bob = new"); @@ -242,7 +242,7 @@ public void should_set_template_properties_when_args_are_separated_by_equals_wit } [Fact] - public void should_set_template_properties_without_surrounding_quotes() + public void Should_set_template_properties_without_surrounding_quotes() { reset(); unparsedArgs.Add("bob = \"new this\""); @@ -256,7 +256,7 @@ public void should_set_template_properties_without_surrounding_quotes() } [Fact] - public void should_set_template_properties_without_removing_quote() + public void Should_set_template_properties_without_removing_quote() { reset(); unparsedArgs.Add("bob = 'new \"this'"); @@ -270,7 +270,7 @@ public void should_set_template_properties_without_removing_quote() } [Fact] - public void should_set_template_properties_without_surrounding_apostrophes() + public void Should_set_template_properties_without_surrounding_apostrophes() { reset(); unparsedArgs.Add("bob = 'new this'"); @@ -284,7 +284,7 @@ public void should_set_template_properties_without_surrounding_apostrophes() } [Fact] - public void should_set_template_properties_without_removing_apostrophe() + public void Should_set_template_properties_without_removing_apostrophe() { reset(); unparsedArgs.Add("bob = \"new 'this\""); @@ -298,14 +298,14 @@ public void should_set_template_properties_without_removing_apostrophe() } } - public class when_handling_validation : ChocolateyNewCommandSpecsBase + public class When_validating : ChocolateyNewCommandSpecsBase { public override void Because() { } [Fact] - public void should_throw_when_Name_is_not_set() + public void Should_throw_when_Name_is_not_set() { configuration.NewCommand.Name = ""; var errored = false; @@ -313,7 +313,7 @@ public void should_throw_when_Name_is_not_set() try { - command.handle_validation(configuration); + command.Validate(configuration); } catch (Exception ex) { @@ -327,42 +327,42 @@ public void should_throw_when_Name_is_not_set() } [Fact] - public void should_continue_when_Name_is_set() + public void Should_continue_when_Name_is_set() { configuration.NewCommand.Name = "bob"; - command.handle_validation(configuration); + command.Validate(configuration); } } - public class when_noop_is_called : ChocolateyNewCommandSpecsBase + public class When_noop_is_called : ChocolateyNewCommandSpecsBase { public override void Because() { - command.noop(configuration); + command.DryRun(configuration); } [Fact] - public void should_call_service_noop() + public void Should_call_service_noop() { - templateService.Verify(c => c.generate_noop(configuration), Times.Once); + templateService.Verify(c => c.GenerateDryRun(configuration), Times.Once); } } - public class when_run_is_called : ChocolateyNewCommandSpecsBase + public class When_run_is_called : ChocolateyNewCommandSpecsBase { public override void Because() { - command.run(configuration); + command.Run(configuration); } [Fact] - public void should_call_service_generate() + public void Should_call_service_generate() { - templateService.Verify(c => c.generate(configuration), Times.Once); + templateService.Verify(c => c.Generate(configuration), Times.Once); } } - public class when_handling_arguments_parsing : ChocolateyNewCommandSpecsBase + public class When_handling_arguments_parsing : ChocolateyNewCommandSpecsBase { private OptionSet optionSet; @@ -370,7 +370,7 @@ public override void Context() { base.Context(); optionSet = new OptionSet(); - command.configure_argument_parser(optionSet, configuration); + command.ConfigureArgumentParser(optionSet, configuration); } public override void Because() @@ -379,38 +379,38 @@ public override void Because() } [Fact] - public void should_name_equal_to_Bob() + public void Should_name_equal_to_Bob() { configuration.NewCommand.Name.ShouldEqual("Bob"); configuration.NewCommand.TemplateProperties[TemplateValues.NamePropertyName].ShouldEqual("Bob"); } [Fact] - public void should_automaticpackage_equal_to_true() + public void Should_automaticpackage_equal_to_true() { configuration.NewCommand.AutomaticPackage.ShouldBeTrue(); } [Fact] - public void should_templatename_equal_to_custom() + public void Should_templatename_equal_to_custom() { configuration.NewCommand.TemplateName.ShouldEqual("custom"); } [Fact] - public void should_version_equal_to_42() + public void Should_version_equal_to_42() { configuration.NewCommand.TemplateProperties[TemplateValues.VersionPropertyName].ShouldEqual("0.42.0"); } [Fact] - public void should_maintainer_equal_to_Loyd() + public void Should_maintainer_equal_to_Loyd() { configuration.NewCommand.TemplateProperties[TemplateValues.MaintainerPropertyName].ShouldEqual("Loyd"); } [Fact] - public void should_outputdirectory_equal_packages() + public void Should_outputdirectory_equal_packages() { configuration.OutputDirectory.ShouldEqual("c:\\packages"); } diff --git a/src/chocolatey.tests/infrastructure.app/commands/ChocolateyOutdatedCommandSpecs.cs b/src/chocolatey.tests/infrastructure.app/commands/ChocolateyOutdatedCommandSpecs.cs index 29ee7f966d..a626cdc3d7 100644 --- a/src/chocolatey.tests/infrastructure.app/commands/ChocolateyOutdatedCommandSpecs.cs +++ b/src/chocolatey.tests/infrastructure.app/commands/ChocolateyOutdatedCommandSpecs.cs @@ -42,7 +42,7 @@ public override void Context() } } - public class when_implementing_command_for : ChocolateyOutdatedCommandSpecsBase + public class When_implementing_command_for : ChocolateyOutdatedCommandSpecsBase { private List results; @@ -52,13 +52,13 @@ public override void Because() } [Fact] - public void should_implement_outdated() + public void Should_implement_outdated() { results.ShouldContain("outdated"); } } - public class when_configurating_the_argument_parser : ChocolateyOutdatedCommandSpecsBase + public class When_configurating_the_argument_parser : ChocolateyOutdatedCommandSpecsBase { private OptionSet optionSet; @@ -70,77 +70,77 @@ public override void Context() public override void Because() { - command.configure_argument_parser(optionSet, configuration); + command.ConfigureArgumentParser(optionSet, configuration); } [Fact] - public void should_add_source_to_the_option_set() + public void Should_add_source_to_the_option_set() { optionSet.Contains("source").ShouldBeTrue(); } [Fact] - public void should_add_short_version_of_source_to_the_option_set() + public void Should_add_short_version_of_source_to_the_option_set() { optionSet.Contains("s").ShouldBeTrue(); } [Fact] - public void should_add_user_to_the_option_set() + public void Should_add_user_to_the_option_set() { optionSet.Contains("user").ShouldBeTrue(); } [Fact] - public void should_add_short_version_of_user_to_the_option_set() + public void Should_add_short_version_of_user_to_the_option_set() { optionSet.Contains("u").ShouldBeTrue(); } [Fact] - public void should_add_password_to_the_option_set() + public void Should_add_password_to_the_option_set() { optionSet.Contains("password").ShouldBeTrue(); } [Fact] - public void should_add_short_version_of_password_to_the_option_set() + public void Should_add_short_version_of_password_to_the_option_set() { optionSet.Contains("p").ShouldBeTrue(); } [Fact] - public void should_add_ignore_pinned_to_the_option_set() + public void Should_add_ignore_pinned_to_the_option_set() { optionSet.Contains("ignore-pinned").ShouldBeTrue(); } } - public class when_noop_is_called : ChocolateyOutdatedCommandSpecsBase + public class When_noop_is_called : ChocolateyOutdatedCommandSpecsBase { public override void Because() { - command.noop(configuration); + command.DryRun(configuration); } [Fact] - public void should_call_service_outdated_noop() + public void Should_call_service_outdated_noop() { - packageService.Verify(c => c.outdated_noop(configuration), Times.Once); + packageService.Verify(c => c.OutdatedDryRun(configuration), Times.Once); } } - public class when_run_is_called : ChocolateyOutdatedCommandSpecsBase + public class When_run_is_called : ChocolateyOutdatedCommandSpecsBase { public override void Because() { - command.run(configuration); + command.Run(configuration); } [Fact] - public void should_call_service_outdated_run() + public void Should_call_service_outdated_run() { - packageService.Verify(c => c.outdated_run(configuration), Times.Once); + packageService.Verify(c => c.Outdated(configuration), Times.Once); } } } diff --git a/src/chocolatey.tests/infrastructure.app/commands/ChocolateyPackCommandSpecs.cs b/src/chocolatey.tests/infrastructure.app/commands/ChocolateyPackCommandSpecs.cs index 4c6b130705..c99c89ae93 100644 --- a/src/chocolatey.tests/infrastructure.app/commands/ChocolateyPackCommandSpecs.cs +++ b/src/chocolatey.tests/infrastructure.app/commands/ChocolateyPackCommandSpecs.cs @@ -42,7 +42,7 @@ public override void Context() } } - public class when_implementing_command_for : ChocolateyPackCommandSpecsBase + public class When_implementing_command_for : ChocolateyPackCommandSpecsBase { private List results; @@ -52,13 +52,13 @@ public override void Because() } [Fact] - public void should_implement_pack() + public void Should_implement_pack() { results.ShouldContain("pack"); } } - public class when_configurating_the_argument_parser : ChocolateyPackCommandSpecsBase + public class When_configurating_the_argument_parser : ChocolateyPackCommandSpecsBase { private OptionSet optionSet; @@ -70,23 +70,23 @@ public override void Context() public override void Because() { - command.configure_argument_parser(optionSet, configuration); + command.ConfigureArgumentParser(optionSet, configuration); } [Fact] - public void should_add_version_to_the_option_set() + public void Should_add_version_to_the_option_set() { optionSet.Contains("version").ShouldBeTrue(); } [Fact] - public void should_add_outputdirectory_to_the_option_set() + public void Should_add_outputdirectory_to_the_option_set() { optionSet.Contains("outputdirectory").ShouldBeTrue(); } } - public class when_handling_additional_argument_parsing : ChocolateyPackCommandSpecsBase + public class When_handling_additional_argument_parsing : ChocolateyPackCommandSpecsBase { private readonly IList unparsedArgs = new List(); private const string nuspecPath = "./some/path/to.nuspec"; @@ -104,29 +104,29 @@ public override void Context() public override void Because() { - command.handle_additional_argument_parsing(unparsedArgs, configuration); + command.ParseAdditionalArguments(unparsedArgs, configuration); } [Fact] - public void should_allow_a_path_to_the_nuspec_to_be_passed_in() + public void Should_allow_a_path_to_the_nuspec_to_be_passed_in() { configuration.Input.ShouldEqual(nuspecPath); } [Fact] - public void should_property_foo_equal_1() + public void Should_property_foo_equal_1() { configuration.PackCommand.Properties["foo"].ShouldEqual("1"); } [Fact] - public void should_property_bar_equal_baz() + public void Should_property_bar_equal_baz() { configuration.PackCommand.Properties["bar"].ShouldEqual("baz"); } [Fact] - public void should_log_warning_on_duplicate_foo() + public void Should_log_warning_on_duplicate_foo() { var warnings = MockLogger.MessagesFor(LogLevel.Warn); warnings.Count.ShouldEqual(1); @@ -134,35 +134,35 @@ public void should_log_warning_on_duplicate_foo() } } - public class when_noop_is_called : ChocolateyPackCommandSpecsBase + public class When_noop_is_called : ChocolateyPackCommandSpecsBase { public override void Because() { - command.noop(configuration); + command.DryRun(configuration); } [Fact] - public void should_call_service_package_noop() + public void Should_call_service_package_noop() { - packageService.Verify(c => c.pack_noop(configuration), Times.Once); + packageService.Verify(c => c.PackDryRun(configuration), Times.Once); } } - public class when_run_is_called : ChocolateyPackCommandSpecsBase + public class When_run_is_called : ChocolateyPackCommandSpecsBase { public override void Because() { - command.run(configuration); + command.Run(configuration); } [Fact] - public void should_call_service_pack_run() + public void Should_call_service_pack_run() { - packageService.Verify(c => c.pack_run(configuration), Times.Once); + packageService.Verify(c => c.Pack(configuration), Times.Once); } } - public class when_handling_arguments_parsing : ChocolateyPackCommandSpecsBase + public class When_handling_arguments_parsing : ChocolateyPackCommandSpecsBase { private OptionSet optionSet; @@ -170,7 +170,7 @@ public override void Context() { base.Context(); optionSet = new OptionSet(); - command.configure_argument_parser(optionSet, configuration); + command.ConfigureArgumentParser(optionSet, configuration); } public override void Because() @@ -179,13 +179,13 @@ public override void Because() } [Fact] - public void should_version_equal_to_42() + public void Should_version_equal_to_42() { configuration.Version.ShouldEqual("0.42.0"); } [Fact] - public void should_outputdirectory_equal_packages() + public void Should_outputdirectory_equal_packages() { configuration.OutputDirectory.ShouldEqual("c:\\packages"); } diff --git a/src/chocolatey.tests/infrastructure.app/commands/ChocolateyPinCommandSpecs.cs b/src/chocolatey.tests/infrastructure.app/commands/ChocolateyPinCommandSpecs.cs index 5c2b3a0718..79ddbf0af4 100644 --- a/src/chocolatey.tests/infrastructure.app/commands/ChocolateyPinCommandSpecs.cs +++ b/src/chocolatey.tests/infrastructure.app/commands/ChocolateyPinCommandSpecs.cs @@ -59,7 +59,7 @@ public override void Context() package = new Mock(); package.Setup(p => p.Id).Returns("regular"); package.Setup(p => p.Version).Returns(new NuGetVersion("1.2.0")); - packageInfoService.Setup(s => s.get_package_information(package.Object)).Returns( + packageInfoService.Setup(s => s.Get(package.Object)).Returns( new ChocolateyPackageInformation(package.Object) { IsPinned = false @@ -67,21 +67,21 @@ public override void Context() pinnedPackage = new Mock(); pinnedPackage.Setup(p => p.Id).Returns("pinned"); pinnedPackage.Setup(p => p.Version).Returns(new NuGetVersion("1.1.0")); - packageInfoService.Setup(s => s.get_package_information(pinnedPackage.Object)).Returns( + packageInfoService.Setup(s => s.Get(pinnedPackage.Object)).Returns( new ChocolateyPackageInformation(pinnedPackage.Object) { IsPinned = true }); } - public void reset() + public void Reset() { packageInfoService.ResetCalls(); nugetService.ResetCalls(); } } - public class when_implementing_command_for : ChocolateyPinCommandSpecsBase + public class When_implementing_command_for : ChocolateyPinCommandSpecsBase { private List results; @@ -91,13 +91,13 @@ public override void Because() } [Fact] - public void should_implement_source() + public void Should_implement_source() { results.ShouldContain("pin"); } } - public class when_configurating_the_argument_parser : ChocolateyPinCommandSpecsBase + public class When_configurating_the_argument_parser : ChocolateyPinCommandSpecsBase { private OptionSet optionSet; @@ -109,58 +109,58 @@ public override void Context() public override void Because() { - command.configure_argument_parser(optionSet, configuration); + command.ConfigureArgumentParser(optionSet, configuration); } [Fact] - public void should_add_name_to_the_option_set() + public void Should_add_name_to_the_option_set() { optionSet.Contains("name").ShouldBeTrue(); } [Fact] - public void should_add_short_version_of_name_to_the_option_set() + public void Should_add_short_version_of_name_to_the_option_set() { optionSet.Contains("n").ShouldBeTrue(); } [Fact] - public void should_add_version_to_the_option_set() + public void Should_add_version_to_the_option_set() { optionSet.Contains("version").ShouldBeTrue(); } } - public class when_handling_additional_argument_parsing : ChocolateyPinCommandSpecsBase + public class When_handling_additional_argument_parsing : ChocolateyPinCommandSpecsBase { private readonly IList unparsedArgs = new List(); private Action because; public override void Because() { - because = () => command.handle_additional_argument_parsing(unparsedArgs, configuration); + because = () => command.ParseAdditionalArguments(unparsedArgs, configuration); } - public new void reset() + public new void Reset() { unparsedArgs.Clear(); - base.reset(); + base.Reset(); } [Fact] - public void should_use_the_first_unparsed_arg_as_the_subcommand() + public void Should_use_the_first_unparsed_arg_as_the_subcommand() { - reset(); + Reset(); unparsedArgs.Add("list"); because(); - configuration.PinCommand.Command.ShouldEqual(PinCommandType.list); + configuration.PinCommand.Command.ShouldEqual(PinCommandType.List); } [Fact] - public void should_throw_when_more_than_one_unparsed_arg_is_passed() + public void Should_throw_when_more_than_one_unparsed_arg_is_passed() { - reset(); + Reset(); unparsedArgs.Add("wtf"); unparsedArgs.Add("bbq"); var errored = false; @@ -183,105 +183,105 @@ public void should_throw_when_more_than_one_unparsed_arg_is_passed() } [Fact] - public void should_accept_add_as_the_subcommand() + public void Should_accept_add_as_the_subcommand() { - reset(); + Reset(); unparsedArgs.Add("add"); because(); - configuration.PinCommand.Command.ShouldEqual(PinCommandType.add); + configuration.PinCommand.Command.ShouldEqual(PinCommandType.Add); } [Fact] - public void should_accept_uppercase_add_as_the_subcommand() + public void Should_accept_uppercase_add_as_the_subcommand() { - reset(); + Reset(); unparsedArgs.Add("ADD"); because(); - configuration.PinCommand.Command.ShouldEqual(PinCommandType.add); + configuration.PinCommand.Command.ShouldEqual(PinCommandType.Add); } [Fact] - public void should_remove_add_as_the_subcommand() + public void Should_remove_add_as_the_subcommand() { - reset(); + Reset(); unparsedArgs.Add("remove"); because(); - configuration.PinCommand.Command.ShouldEqual(PinCommandType.remove); + configuration.PinCommand.Command.ShouldEqual(PinCommandType.Remove); } [Fact] - public void should_set_unrecognized_values_to_list_as_the_subcommand() + public void Should_set_unrecognized_values_to_list_as_the_subcommand() { - reset(); + Reset(); unparsedArgs.Add("wtf"); because(); - configuration.PinCommand.Command.ShouldEqual(PinCommandType.list); + configuration.PinCommand.Command.ShouldEqual(PinCommandType.List); } [Fact] - public void should_default_to_list_as_the_subcommand() + public void Should_default_to_list_as_the_subcommand() { - reset(); + Reset(); because(); - configuration.PinCommand.Command.ShouldEqual(PinCommandType.list); + configuration.PinCommand.Command.ShouldEqual(PinCommandType.List); } [Fact] - public void should_handle_passing_in_an_empty_string() + public void Should_handle_passing_in_an_empty_string() { - reset(); + Reset(); unparsedArgs.Add(" "); because(); - configuration.PinCommand.Command.ShouldEqual(PinCommandType.list); + configuration.PinCommand.Command.ShouldEqual(PinCommandType.List); } [Fact] - public void should_set_config_sources_to_local_only() + public void Should_set_config_sources_to_local_only() { - reset(); + Reset(); because(); configuration.Sources.ShouldEqual(ApplicationParameters.PackagesLocation); } [Fact] - public void should_set_config_local_only_to_true() + public void Should_set_config_local_only_to_true() { - reset(); + Reset(); because(); configuration.ListCommand.LocalOnly.ShouldBeTrue(); } [Fact] - public void should_set_config_all_versions_to_true() + public void Should_set_config_all_versions_to_true() { - reset(); + Reset(); because(); configuration.AllVersions.ShouldBeTrue(); } } - public class when_handling_validation : ChocolateyPinCommandSpecsBase + public class When_validating : ChocolateyPinCommandSpecsBase { private Action because; public override void Because() { - because = () => command.handle_validation(configuration); + because = () => command.Validate(configuration); } [Fact] - public void should_throw_when_command_is_not_list_and_name_is_not_set() + public void Should_throw_when_command_is_not_list_and_name_is_not_set() { - configuration.PinCommand.Command = PinCommandType.add; + configuration.PinCommand.Command = PinCommandType.Add; configuration.PinCommand.Name = ""; var errored = false; Exception error = null; @@ -299,41 +299,41 @@ public void should_throw_when_command_is_not_list_and_name_is_not_set() errored.ShouldBeTrue(); error.ShouldNotBeNull(); error.ShouldBeType(); - error.Message.ShouldEqual("When specifying the subcommand '{0}', you must also specify --name.".format_with(configuration.PinCommand.Command.to_string())); + error.Message.ShouldEqual("When specifying the subcommand '{0}', you must also specify --name.".FormatWith(configuration.PinCommand.Command.ToStringSafe().ToLower())); } [Fact] - public void should_continue_when_command_is_list_and_name_is_not_set() + public void Should_continue_when_command_is_list_and_name_is_not_set() { - configuration.PinCommand.Command = PinCommandType.list; + configuration.PinCommand.Command = PinCommandType.List; configuration.PinCommand.Name = ""; because(); } [Fact] - public void should_continue_when_command_is_not_list_and_name_is_set() + public void Should_continue_when_command_is_not_list_and_name_is_set() { - configuration.PinCommand.Command = PinCommandType.list; + configuration.PinCommand.Command = PinCommandType.List; configuration.PinCommand.Name = "bob"; because(); } } - public class when_noop_is_called : ChocolateyPinCommandSpecsBase + public class When_noop_is_called : ChocolateyPinCommandSpecsBase { public override void Because() { - command.noop(configuration); + command.DryRun(configuration); } [Fact] - public void should_log_a_message() + public void Should_log_a_message() { MockLogger.Verify(l => l.Info(It.IsAny()), Times.AtLeastOnce); } [Fact] - public void should_log_the_message_we_expect() + public void Should_log_the_message_we_expect() { var messages = MockLogger.MessagesFor(tests.LogLevel.Info); messages.ShouldNotBeEmpty(); @@ -342,7 +342,7 @@ public void should_log_the_message_we_expect() } } - public class when_list_is_called : ChocolateyPinCommandSpecsBase + public class When_list_is_called : ChocolateyPinCommandSpecsBase { public override void Context() { @@ -355,41 +355,41 @@ public override void Context() new PackageResult(package.Object, null), new PackageResult(pinnedPackage.Object, null) }; - nugetService.Setup(n => n.list_run(It.IsAny())).Returns(packageResults); - configuration.PinCommand.Command = PinCommandType.list; + nugetService.Setup(n => n.List(It.IsAny())).Returns(packageResults); + configuration.PinCommand.Command = PinCommandType.List; } public override void Because() { - command.run(configuration); + command.Run(configuration); } [Fact] - public void should_list_pinned_packages() + public void Should_list_pinned_packages() { MockLogger.Verify(l => l.Info("pinned|1.1.0"), Times.Once); } [Fact] - public void should_not_list_unpinned_packages() + public void Should_not_list_unpinned_packages() { MockLogger.Verify(l => l.Info("regular|1.2.0"), Times.Never); } [Fact] - public void should_log_a_message() + public void Should_log_a_message() { MockLogger.Verify(l => l.Info(It.IsAny()), Times.Once); } [Fact] - public void should_log_one_message() + public void Should_log_one_message() { MockLogger.Messages.Count.ShouldEqual(1); } } - public class when_run_is_called : ChocolateyPinCommandSpecsBase + public class When_run_is_called : ChocolateyPinCommandSpecsBase { //private Action because; @@ -405,13 +405,13 @@ public override void Context() new PackageResult(package.Object, null), new PackageResult(pinnedPackage.Object, null) }; - nugetService.Setup(n => n.list_run(It.IsAny())).Returns(packageResults); + nugetService.Setup(n => n.List(It.IsAny())).Returns(packageResults); } - public new void reset() + public new void Reset() { Context(); - base.reset(); + base.Reset(); } public override void AfterEachSpec() @@ -426,38 +426,38 @@ public override void Because() } [Fact] - public void should_call_nuget_service_list_run_when_command_is_list() + public void Should_call_nuget_service_list_run_when_command_is_list() { - reset(); - configuration.PinCommand.Command = PinCommandType.list; - command.run(configuration); + Reset(); + configuration.PinCommand.Command = PinCommandType.List; + command.Run(configuration); - nugetService.Verify(n => n.list_run(It.IsAny()), Times.Once); + nugetService.Verify(n => n.List(It.IsAny()), Times.Once); } [Fact] - public void should_set_pin_when_command_is_add() + public void Should_set_pin_when_command_is_add() { - reset(); + Reset(); configuration.PinCommand.Name = "regular"; - configuration.PinCommand.Command = PinCommandType.add; + configuration.PinCommand.Command = PinCommandType.Add; - command.set_pin(configuration); + command.SetPin(configuration); - packageInfoService.Verify(s => s.save_package_information(It.IsAny()), Times.Once); + packageInfoService.Verify(s => s.Save(It.IsAny()), Times.Once); } [Fact] - public void should_remove_pin_when_command_is_remove() + public void Should_remove_pin_when_command_is_remove() { - reset(); + Reset(); configuration.PinCommand.Name = "pinned"; - configuration.PinCommand.Command = PinCommandType.remove; + configuration.PinCommand.Command = PinCommandType.Remove; - command.set_pin(configuration); + command.SetPin(configuration); - packageInfoService.Verify(s => s.save_package_information(It.IsAny()), Times.Once); + packageInfoService.Verify(s => s.Save(It.IsAny()), Times.Once); } } diff --git a/src/chocolatey.tests/infrastructure.app/commands/ChocolateyPushCommandSpecs.cs b/src/chocolatey.tests/infrastructure.app/commands/ChocolateyPushCommandSpecs.cs index 77a66a4ec6..2bcd61bc69 100644 --- a/src/chocolatey.tests/infrastructure.app/commands/ChocolateyPushCommandSpecs.cs +++ b/src/chocolatey.tests/infrastructure.app/commands/ChocolateyPushCommandSpecs.cs @@ -34,149 +34,161 @@ public class ChocolateyPushCommandSpecs [ConcernFor("push")] public abstract class ChocolateyPushCommandSpecsBase : TinySpec { - protected ChocolateyPushCommand command; - protected Mock packageService = new Mock(); - protected Mock configSettingsService = new Mock(); - protected ChocolateyConfiguration configuration = new ChocolateyConfiguration(); + protected ChocolateyPushCommand Command; + protected Mock PackageService = new Mock(); + protected Mock ConfigSettingsService = new Mock(); + protected ChocolateyConfiguration Configuration = new ChocolateyConfiguration(); public override void Context() { - configuration.Sources = "https://localhost/somewhere/out/there"; - command = new ChocolateyPushCommand(packageService.Object, configSettingsService.Object); + Configuration.Sources = "https://localhost/somewhere/out/there"; + Command = new ChocolateyPushCommand(PackageService.Object, ConfigSettingsService.Object); } } - public class when_implementing_command_for : ChocolateyPushCommandSpecsBase + public class When_implementing_command_for : ChocolateyPushCommandSpecsBase { - private List results; + private List _results; public override void Because() { - results = command.GetType().GetCustomAttributes(typeof(CommandForAttribute), false).Cast().Select(a => a.CommandName).ToList(); + _results = Command.GetType().GetCustomAttributes(typeof(CommandForAttribute), false).Cast().Select(a => a.CommandName).ToList(); } [Fact] - public void should_implement_push() + public void Should_implement_push() { - results.ShouldContain("push"); + _results.ShouldContain("push"); } } //Yes, configurating [sic] - public class when_configurating_the_argument_parser : ChocolateyPushCommandSpecsBase + public class When_configurating_the_argument_parser : ChocolateyPushCommandSpecsBase { - private OptionSet optionSet; + private OptionSet _optionSet; public override void Context() { base.Context(); - optionSet = new OptionSet(); + _optionSet = new OptionSet(); } public override void Because() { - command.configure_argument_parser(optionSet, configuration); + Command.ConfigureArgumentParser(_optionSet, Configuration); } [Fact] - public void should_clear_previously_set_Source() + public void Should_clear_previously_set_Source() { - configuration.Sources.ShouldBeNull(); + Configuration.Sources.ShouldBeNull(); } [Fact] - public void should_add_source_to_the_option_set() + public void Should_add_source_to_the_option_set() { - optionSet.Contains("source").ShouldBeTrue(); + _optionSet.Contains("source").ShouldBeTrue(); } [Fact] - public void should_add_short_version_of_source_to_the_option_set() + public void Should_add_short_version_of_source_to_the_option_set() { - optionSet.Contains("s").ShouldBeTrue(); + _optionSet.Contains("s").ShouldBeTrue(); } [Fact] - public void should_add_apikey_to_the_option_set() + public void Should_add_apikey_to_the_option_set() { - optionSet.Contains("apikey").ShouldBeTrue(); + _optionSet.Contains("apikey").ShouldBeTrue(); } [Fact] - public void should_add_short_version_of_apikey_to_the_option_set() + public void Should_add_short_version_of_apikey_to_the_option_set() { - optionSet.Contains("k").ShouldBeTrue(); + _optionSet.Contains("k").ShouldBeTrue(); } [Fact] - public void should_not_add_short_version_of_timeout_to_the_option_set() + public void Should_not_add_short_version_of_timeout_to_the_option_set() { - optionSet.Contains("t").ShouldBeFalse(); + _optionSet.Contains("t").ShouldBeFalse(); } } - public class when_handling_additional_argument_parsing : ChocolateyPushCommandSpecsBase + public class When_handling_additional_argument_parsing : ChocolateyPushCommandSpecsBase { - private readonly IList unparsedArgs = new List(); - private const string apiKey = "bobdaf"; - private Action because; + private readonly IList _unparsedArgs = new List(); + private Action _because; public override void Because() { - because = () => command.handle_additional_argument_parsing(unparsedArgs, configuration); + _because = () => Command.ParseAdditionalArguments(_unparsedArgs, Configuration); } - public void reset() + public void Reset() { - unparsedArgs.Clear(); - configSettingsService.ResetCalls(); + _unparsedArgs.Clear(); + ConfigSettingsService.ResetCalls(); } [Fact] - public void should_allow_a_path_to_the_nupkg_to_be_passed_in() + public void Should_allow_a_path_to_the_nupkg_to_be_passed_in() { - reset(); + Reset(); string nupkgPath = "./some/path/to.nupkg"; - unparsedArgs.Add(nupkgPath); - because(); - configuration.Input.ShouldEqual(nupkgPath); + _unparsedArgs.Add(nupkgPath); + _because(); + Configuration.Input.ShouldEqual(nupkgPath); + } + } + + public class When_validating : ChocolateyPushCommandSpecsBase + { + private Action _because; + private string _apiKey = "abcdef"; + + public override void Because() + { + _because = () => Command.Validate(Configuration); } [Fact] - public void should_set_the_source_to_defaultpushsource_if_set_and_no_explicit_source() + public void Should_not_override_explicit_source_if_defaultpushsource_is_set() { - reset(); - configuration.Sources = ""; - configuration.PushCommand.DefaultSource = "https://localhost/default/source"; - because(); + Configuration.Sources = "https://localhost/somewhere/out/there"; + Configuration.PushCommand.Key = _apiKey; + Configuration.PushCommand.DefaultSource = "https://localhost/default/source"; + _because(); - configuration.Sources.ShouldEqual("https://localhost/default/source"); + Configuration.Sources.ShouldEqual("https://localhost/somewhere/out/there"); } + [Fact] - public void should_not_override_explicit_source_if_defaultpushsource_is_set() + public void Should_set_the_source_to_defaultpushsource_if_set_and_no_explicit_source() { - reset(); - configuration.Sources = "https://localhost/somewhere/out/there"; - configuration.PushCommand.DefaultSource = "https://localhost/default/source"; - because(); + Configuration.Sources = ""; + Configuration.PushCommand.DefaultSource = "https://localhost/default/source"; + ConfigSettingsService.Setup(s => s.GetApiKey(It.Is(c => c.Sources == "https://localhost/default/source"), null)) + .Returns(() => _apiKey); + + _because(); - configuration.Sources.ShouldEqual("https://localhost/somewhere/out/there"); + Configuration.Sources.ShouldEqual("https://localhost/default/source"); } [Fact] - public void should_throw_when_defaultpushsource_is_not_set_and_no_explicit_sources() + public void Should_throw_when_defaultpushsource_is_not_set_and_no_explicit_sources() { - reset(); - configuration.PushCommand.DefaultSource = ""; - configuration.Sources = ""; + Configuration.PushCommand.DefaultSource = ""; + Configuration.Sources = ""; var errorred = false; Exception error = null; try { - because(); + _because(); } catch (Exception ex) { @@ -191,77 +203,86 @@ public void should_throw_when_defaultpushsource_is_not_set_and_no_explicit_sourc } [Fact] - public void should_continue_when_defaultpushsource_is_not_set_and_explicit_sources_passed() + public void Should_continue_when_defaultpushsource_is_not_set_and_explicit_sources_passed() { - reset(); - configuration.Sources = "https://somewhere/out/there"; - configuration.PushCommand.Key = "bob"; - configuration.PushCommand.DefaultSource = ""; - because(); + Configuration.Sources = "https://somewhere/out/there"; + Configuration.PushCommand.Key = _apiKey; + Configuration.PushCommand.DefaultSource = ""; + _because(); } [Fact] - public void should_not_set_the_apiKey_if_source_is_not_found() + public void Should_throw_if_apikey_is_not_found_for_source() { - reset(); - configSettingsService.Setup(c => c.get_api_key(configuration, null)).Returns(""); - configuration.PushCommand.Key = ""; - configuration.Sources = "https://localhost/somewhere/out/there"; - because(); + ConfigSettingsService.Setup(c => c.GetApiKey(Configuration, null)).Returns(""); + Configuration.PushCommand.Key = ""; + Configuration.Sources = "https://localhost/somewhere/out/there"; + + var errorred = false; + Exception error = null; - configuration.PushCommand.Key.ShouldEqual(""); + try + { + _because(); + } + catch (Exception ex) + { + errorred = true; + error = ex; + } + + errorred.ShouldBeTrue(); + error.ShouldNotBeNull(); + error.ShouldBeType(); + error.Message.ShouldContain($"An API key was not found for '{Configuration.Sources}'"); } [Fact] - public void should_not_try_to_determine_the_key_if_passed_in_as_an_argument() + public void Should_not_try_to_determine_the_key_if_passed_in_as_an_argument() { - reset(); - configSettingsService.Setup(c => c.get_api_key(configuration, null)).Returns(""); - configuration.PushCommand.Key = "bob"; - configuration.Sources = "https://localhost/somewhere/out/there"; - because(); + ConfigSettingsService.Setup(c => c.GetApiKey(Configuration, null)).Returns(""); + Configuration.PushCommand.Key = _apiKey; + Configuration.Sources = "https://localhost/somewhere/out/there"; + _because(); - configuration.PushCommand.Key.ShouldEqual("bob"); - configSettingsService.Verify(c => c.get_api_key(It.IsAny(), It.IsAny>()), Times.Never); + Configuration.PushCommand.Key.ShouldEqual(_apiKey); + ConfigSettingsService.Verify(c => c.GetApiKey(It.IsAny(), It.IsAny>()), Times.Never); } [Fact] - public void should_not_try_to_determine_the_key_if_source_is_set_for_a_local_source() + public void Should_not_try_to_determine_the_key_if_source_is_set_for_a_local_source() { - reset(); - configuration.Sources = "c:\\packages"; - configuration.PushCommand.Key = ""; - because(); + Configuration.Sources = "c:\\packages"; + Configuration.PushCommand.Key = ""; + _because(); - configSettingsService.Verify(c => c.get_api_key(It.IsAny(), It.IsAny>()), Times.Never); + ConfigSettingsService.Verify(c => c.GetApiKey(It.IsAny(), It.IsAny>()), Times.Never); } [Fact] - public void should_not_try_to_determine_the_key_if_source_is_set_for_an_unc_source() + public void Should_not_try_to_determine_the_key_if_source_is_set_for_an_unc_source() { - reset(); - configuration.Sources = "\\\\someserver\\packages"; - configuration.PushCommand.Key = ""; - because(); + Configuration.Sources = "\\\\someserver\\packages"; + Configuration.PushCommand.Key = ""; + _because(); - configSettingsService.Verify(c => c.get_api_key(It.IsAny(), It.IsAny>()), Times.Never); + ConfigSettingsService.Verify(c => c.GetApiKey(It.IsAny(), It.IsAny>()), Times.Never); } [Fact] - public void should_throw_if_multiple_sources_are_passed() + public void Should_throw_if_multiple_sources_are_passed() { - reset(); - configuration.Sources = "https://localhost/somewhere/out/there;https://localhost/somewhere/out/there"; + Configuration.Sources = "https://localhost/somewhere/out/there;https://localhost/somewhere/out/there"; - Assert.Throws(() => because(), "Multiple sources are not support by push command."); + Assert.Throws(() => _because(), "Multiple sources are not supported by push command."); } [Fact] - public void should_update_source_if_alias_is_passed() + [Pending("This functionality is not yet implemented. See https://github.com/chocolatey/choco/issues/63")] + public void Should_update_source_if_alias_is_passed() { - reset(); - configuration.Sources = "chocolatey"; - configuration.MachineSources = new List + Configuration.Sources = "chocolatey"; + Configuration.MachineSources = new List { new MachineSourceConfiguration { @@ -269,18 +290,18 @@ public void should_update_source_if_alias_is_passed() Key = "https://localhost/somewhere/out/there" } }; - because(); + _because(); - configuration.Sources.ShouldEqual("https://localhost/somewhere/out/there"); + Configuration.Sources.ShouldEqual("https://localhost/somewhere/out/there"); } [Fact] - public void should_update_source_if_alias_is_passed_via_defaultpushsource() + [Pending("This functionality is not yet implemented. See https://github.com/chocolatey/choco/issues/63")] + public void Should_update_source_if_alias_is_passed_via_defaultpushsource() { - reset(); - configuration.Sources = ""; - configuration.PushCommand.DefaultSource = "myrepo"; - configuration.MachineSources = new List + Configuration.Sources = ""; + Configuration.PushCommand.DefaultSource = "myrepo"; + Configuration.MachineSources = new List { new MachineSourceConfiguration { @@ -288,55 +309,22 @@ public void should_update_source_if_alias_is_passed_via_defaultpushsource() Key = "https://localhost/somewhere/out/there" } }; - because(); - - configuration.Sources.ShouldEqual("https://localhost/somewhere/out/there"); - } - } - - public class when_handling_validation : ChocolateyPushCommandSpecsBase - { - private Action because; - - public override void Because() - { - because = () => command.handle_validation(configuration); - } - - [Fact] - public void should_throw_when_source_is_not_set() - { - configuration.Sources = ""; - var errored = false; - Exception error = null; + _because(); - try - { - because(); - } - catch (Exception ex) - { - errored = true; - error = ex; - } - - errored.ShouldBeTrue(); - error.ShouldNotBeNull(); - error.ShouldBeType(); - error.Message.ShouldContain("Source is required."); + Configuration.Sources.ShouldEqual("https://localhost/somewhere/out/there"); } [Fact] - public void should_throw_when_apiKey_has_not_been_set_or_determined_for_a_https_source() + public void Should_throw_when_apiKey_has_not_been_set_or_determined_for_a_https_source() { - configuration.Sources = "https://somewhere/out/there"; - configuration.PushCommand.Key = ""; + Configuration.Sources = "https://somewhere/out/there"; + Configuration.PushCommand.Key = ""; var errored = false; Exception error = null; try { - because(); + _because(); } catch (Exception ex) { @@ -351,41 +339,41 @@ public void should_throw_when_apiKey_has_not_been_set_or_determined_for_a_https_ } [Fact] - public void should_continue_when_source_and_apikey_is_set_for_a_https_source() + public void Should_continue_when_source_and_apikey_is_set_for_a_https_source() { - configuration.Sources = "https://somewhere/out/there"; - configuration.PushCommand.Key = "bob"; - because(); + Configuration.Sources = "https://somewhere/out/there"; + Configuration.PushCommand.Key = _apiKey; + _because(); } [Fact] - public void should_continue_when_source_is_set_for_a_local_source() + public void Should_continue_when_source_is_set_for_a_local_source() { - configuration.Sources = "c:\\packages"; - configuration.PushCommand.Key = ""; - because(); + Configuration.Sources = "c:\\packages"; + Configuration.PushCommand.Key = ""; + _because(); } [Fact] - public void should_continue_when_source_is_set_for_an_unc_source() + public void Should_continue_when_source_is_set_for_an_unc_source() { - configuration.Sources = "\\\\someserver\\packages"; - configuration.PushCommand.Key = ""; - because(); + Configuration.Sources = "\\\\someserver\\packages"; + Configuration.PushCommand.Key = ""; + _because(); } [Fact] - public void should_throw_when_source_is_http_and_not_secure() + public void Should_throw_when_source_is_http_and_not_secure() { - configuration.Sources = "http://somewhere/out/there"; - configuration.PushCommand.Key = "bob"; - configuration.Force = false; + Configuration.Sources = "http://somewhere/out/there"; + Configuration.PushCommand.Key = _apiKey; + Configuration.Force = false; var errored = false; Exception error = null; try { - because(); + _because(); } catch (Exception ex) { @@ -396,45 +384,45 @@ public void should_throw_when_source_is_http_and_not_secure() errored.ShouldBeTrue(); error.ShouldNotBeNull(); error.ShouldBeType(); - error.Message.ShouldContain("WARNING! The specified source '{0}' is not secure".format_with(configuration.Sources)); + error.Message.ShouldContain("WARNING! The specified source '{0}' is not secure".FormatWith(Configuration.Sources)); } [Fact] - public void should_continue_when_source_is_http_and_not_secure_if_force_is_passed() + public void Should_continue_when_source_is_http_and_not_secure_if_force_is_passed() { - configuration.Sources = "http://somewhere/out/there"; - configuration.PushCommand.Key = "bob"; - configuration.Force = true; + Configuration.Sources = "http://somewhere/out/there"; + Configuration.PushCommand.Key = _apiKey; + Configuration.Force = true; - because(); + _because(); } } - public class when_noop_is_called : ChocolateyPushCommandSpecsBase + public class When_noop_is_called : ChocolateyPushCommandSpecsBase { public override void Because() { - command.noop(configuration); + Command.DryRun(Configuration); } [Fact] - public void should_call_service_push_noop() + public void Should_call_service_push_noop() { - packageService.Verify(c => c.push_noop(configuration), Times.Once); + PackageService.Verify(c => c.PushDryRun(Configuration), Times.Once); } } - public class when_run_is_called : ChocolateyPushCommandSpecsBase + public class When_run_is_called : ChocolateyPushCommandSpecsBase { public override void Because() { - command.run(configuration); + Command.Run(Configuration); } [Fact] - public void should_call_service_push_run() + public void Should_call_service_push_run() { - packageService.Verify(c => c.push_run(configuration), Times.Once); + PackageService.Verify(c => c.Push(Configuration), Times.Once); } } } diff --git a/src/chocolatey.tests/infrastructure.app/commands/ChocolateySearchCommandSpecs.cs b/src/chocolatey.tests/infrastructure.app/commands/ChocolateySearchCommandSpecs.cs index 5c0f1226a5..a9d3c460cc 100644 --- a/src/chocolatey.tests/infrastructure.app/commands/ChocolateySearchCommandSpecs.cs +++ b/src/chocolatey.tests/infrastructure.app/commands/ChocolateySearchCommandSpecs.cs @@ -43,7 +43,7 @@ public override void Context() } } - public class when_implementing_command_for : ChocolateySearchCommandSpecsBase + public class When_implementing_command_for : ChocolateySearchCommandSpecsBase { private List results; @@ -53,25 +53,25 @@ public override void Because() } [Fact] - public void should_not_implement_list() + public void Should_not_implement_list() { results.ShouldNotContain("list"); } [Fact] - public void should_implement_search() + public void Should_implement_search() { results.ShouldContain("search"); } [Fact] - public void should_implement_find() + public void Should_implement_find() { results.ShouldContain("find"); } } - public class when_configurating_the_argument_parser_for_search_command : ChocolateySearchCommandSpecsBase + public class When_configurating_the_argument_parser_for_search_command : ChocolateySearchCommandSpecsBase { private OptionSet optionSet; @@ -84,77 +84,77 @@ public override void Context() public override void Because() { - command.configure_argument_parser(optionSet, configuration); + command.ConfigureArgumentParser(optionSet, configuration); } [Fact] - public void should_add_source_to_the_option_set() + public void Should_add_source_to_the_option_set() { optionSet.Contains("source").ShouldBeTrue(); } [Fact] - public void should_add_short_version_of_source_to_the_option_set() + public void Should_add_short_version_of_source_to_the_option_set() { optionSet.Contains("s").ShouldBeTrue(); } [Fact] - public void should_add_prerelease_to_the_option_set() + public void Should_add_prerelease_to_the_option_set() { optionSet.Contains("prerelease").ShouldBeTrue(); } [Fact] - public void should_add_short_version_of_prerelease_to_the_option_set() + public void Should_add_short_version_of_prerelease_to_the_option_set() { optionSet.Contains("pre").ShouldBeTrue(); } [Fact] - public void should_add_includeprograms_to_the_option_set() + public void Should_add_includeprograms_to_the_option_set() { optionSet.Contains("includeprograms").ShouldBeTrue(); } [Fact] - public void should_add_short_version_of_includeprograms_to_the_option_set() + public void Should_add_short_version_of_includeprograms_to_the_option_set() { optionSet.Contains("i").ShouldBeTrue(); } [Fact] - public void should_add_allversions_to_the_option_set() + public void Should_add_allversions_to_the_option_set() { optionSet.Contains("allversions").ShouldBeTrue(); } [Fact] - public void should_add_short_version_of_allversions_to_the_option_set() + public void Should_add_short_version_of_allversions_to_the_option_set() { optionSet.Contains("a").ShouldBeTrue(); } [Fact] - public void should_add_user_to_the_option_set() + public void Should_add_user_to_the_option_set() { optionSet.Contains("user").ShouldBeTrue(); } [Fact] - public void should_add_short_version_of_user_to_the_option_set() + public void Should_add_short_version_of_user_to_the_option_set() { optionSet.Contains("u").ShouldBeTrue(); } [Fact] - public void should_add_password_to_the_option_set() + public void Should_add_password_to_the_option_set() { optionSet.Contains("password").ShouldBeTrue(); } [Fact] - public void should_add_short_version_of_password_to_the_option_set() + public void Should_add_short_version_of_password_to_the_option_set() { optionSet.Contains("p").ShouldBeTrue(); } @@ -162,11 +162,11 @@ public void should_add_short_version_of_password_to_the_option_set() [NUnit.Framework.TestFixture("search")] [NUnit.Framework.TestFixture("find")] - public class when_configurating_the_argument_parser : ChocolateySearchCommandSpecsBase + public class When_configurating_the_argument_parser : ChocolateySearchCommandSpecsBase { private OptionSet optionSet; - public when_configurating_the_argument_parser(string commandName) + public When_configurating_the_argument_parser(string commandName) { configuration.CommandName = commandName; } @@ -179,83 +179,83 @@ public override void Context() public override void Because() { - command.configure_argument_parser(optionSet, configuration); + command.ConfigureArgumentParser(optionSet, configuration); } [Fact] - public void should_add_source_to_the_option_set() + public void Should_add_source_to_the_option_set() { optionSet.Contains("source").ShouldBeTrue(); } [Fact] - public void should_add_short_version_of_source_to_the_option_set() + public void Should_add_short_version_of_source_to_the_option_set() { optionSet.Contains("s").ShouldBeTrue(); } [Fact] - public void should_add_prerelease_to_the_option_set() + public void Should_add_prerelease_to_the_option_set() { optionSet.Contains("prerelease").ShouldBeTrue(); } [Fact] - public void should_add_short_version_of_prerelease_to_the_option_set() + public void Should_add_short_version_of_prerelease_to_the_option_set() { optionSet.Contains("pre").ShouldBeTrue(); } [Fact] - public void should_add_includeprograms_to_the_option_set() + public void Should_add_includeprograms_to_the_option_set() { optionSet.Contains("includeprograms").ShouldBeTrue(); } [Fact] - public void should_add_short_version_of_includeprograms_to_the_option_set() + public void Should_add_short_version_of_includeprograms_to_the_option_set() { optionSet.Contains("i").ShouldBeTrue(); } [Fact] - public void should_add_allversions_to_the_option_set() + public void Should_add_allversions_to_the_option_set() { optionSet.Contains("allversions").ShouldBeTrue(); } [Fact] - public void should_add_short_version_of_allversions_to_the_option_set() + public void Should_add_short_version_of_allversions_to_the_option_set() { optionSet.Contains("a").ShouldBeTrue(); } [Fact] - public void should_add_user_to_the_option_set() + public void Should_add_user_to_the_option_set() { optionSet.Contains("user").ShouldBeTrue(); } [Fact] - public void should_add_short_version_of_user_to_the_option_set() + public void Should_add_short_version_of_user_to_the_option_set() { optionSet.Contains("u").ShouldBeTrue(); } [Fact] - public void should_add_password_to_the_option_set() + public void Should_add_password_to_the_option_set() { optionSet.Contains("password").ShouldBeTrue(); } [Fact] - public void should_add_short_version_of_password_to_the_option_set() + public void Should_add_short_version_of_password_to_the_option_set() { optionSet.Contains("p").ShouldBeTrue(); } } - public class when_handling_additional_argument_parsing : ChocolateySearchCommandSpecsBase + public class When_handling_additional_argument_parsing : ChocolateySearchCommandSpecsBase { private readonly IList unparsedArgs = new List(); private readonly string source = "https://somewhereoutthere"; @@ -271,18 +271,18 @@ public override void Context() public override void Because() { - because = () => command.handle_additional_argument_parsing(unparsedArgs, configuration); + because = () => command.ParseAdditionalArguments(unparsedArgs, configuration); } [Fact] - public void should_set_unparsed_arguments_to_configuration_input() + public void Should_set_unparsed_arguments_to_configuration_input() { because(); configuration.Input.ShouldEqual("pkg1 pkg2"); } [Fact] - public void should_leave_source_as_set() + public void Should_leave_source_as_set() { configuration.ListCommand.LocalOnly = false; because(); @@ -290,7 +290,7 @@ public void should_leave_source_as_set() } } - public class when_noop_is_called_with_search_command : ChocolateySearchCommandSpecsBase + public class When_noop_is_called_with_search_command : ChocolateySearchCommandSpecsBase { public override void Context() { @@ -300,37 +300,37 @@ public override void Context() public override void Because() { - command.noop(configuration); + command.DryRun(configuration); } [Fact] - public void should_call_service_list_noop() + public void Should_call_service_list_noop() { - packageService.Verify(c => c.list_noop(configuration), Times.Once); + packageService.Verify(c => c.ListDryRun(configuration), Times.Once); } } - public class when_noop_is_called : ChocolateySearchCommandSpecsBase + public class When_noop_is_called : ChocolateySearchCommandSpecsBase { public override void Because() { - command.noop(configuration); + command.DryRun(configuration); } [Fact] - public void should_call_service_list_noop() + public void Should_call_service_list_noop() { - packageService.Verify(c => c.list_noop(configuration), Times.Once); + packageService.Verify(c => c.ListDryRun(configuration), Times.Once); } [Fact] - public void should_not_report_any_warning_messages() + public void Should_not_report_any_warning_messages() { MockLogger.Messages.Keys.ShouldNotContain("Warn"); } } - public class when_run_is_called_with_search_command : ChocolateySearchCommandSpecsBase + public class When_run_is_called_with_search_command : ChocolateySearchCommandSpecsBase { public override void Context() { @@ -340,31 +340,31 @@ public override void Context() public override void Because() { - command.run(configuration); + command.Run(configuration); } [Fact] - public void should_call_service_list_run() + public void Should_call_service_list_run() { - packageService.Verify(c => c.list_run(configuration), Times.Once); + packageService.Verify(c => c.List(configuration), Times.Once); } } - public class when_run_is_called : ChocolateySearchCommandSpecsBase + public class When_run_is_called : ChocolateySearchCommandSpecsBase { public override void Because() { - command.run(configuration); + command.Run(configuration); } [Fact] - public void should_call_service_list_run() + public void Should_call_service_list_run() { - packageService.Verify(c => c.list_run(configuration), Times.Once); + packageService.Verify(c => c.List(configuration), Times.Once); } [Fact] - public void should_not_report_any_warning_messages() + public void Should_not_report_any_warning_messages() { MockLogger.Messages.Keys.ShouldNotContain("Warn"); } @@ -372,16 +372,16 @@ public void should_not_report_any_warning_messages() [NUnit.Framework.TestFixture("search")] [NUnit.Framework.TestFixture("find")] - public class when_outputting_help_message : ChocolateySearchCommandSpecsBase + public class When_outputting_help_message : ChocolateySearchCommandSpecsBase { - public when_outputting_help_message(string commandName) + public When_outputting_help_message(string commandName) { configuration.CommandName = commandName; } public override void Because() { - command.help_message(configuration); + command.HelpMessage(configuration); } } } diff --git a/src/chocolatey.tests/infrastructure.app/commands/ChocolateySourceCommandSpecs.cs b/src/chocolatey.tests/infrastructure.app/commands/ChocolateySourceCommandSpecs.cs index 64f65a283e..44736474a6 100644 --- a/src/chocolatey.tests/infrastructure.app/commands/ChocolateySourceCommandSpecs.cs +++ b/src/chocolatey.tests/infrastructure.app/commands/ChocolateySourceCommandSpecs.cs @@ -44,7 +44,7 @@ public override void Context() } } - public class when_implementing_command_for : ChocolateySourceCommandSpecsBase + public class When_implementing_command_for : ChocolateySourceCommandSpecsBase { private List results; @@ -54,19 +54,19 @@ public override void Because() } [Fact] - public void should_implement_source() + public void Should_implement_source() { results.ShouldContain("source"); } [Fact] - public void should_implement_sources() + public void Should_implement_sources() { results.ShouldContain("sources"); } } - public class when_configurating_the_argument_parser : ChocolateySourceCommandSpecsBase + public class When_configurating_the_argument_parser : ChocolateySourceCommandSpecsBase { private OptionSet optionSet; @@ -79,94 +79,94 @@ public override void Context() public override void Because() { - command.configure_argument_parser(optionSet, configuration); + command.ConfigureArgumentParser(optionSet, configuration); } [Fact] - public void should_clear_previously_set_Source() + public void Should_clear_previously_set_Source() { configuration.Sources.ShouldBeEmpty(); } [Fact] - public void should_add_name_to_the_option_set() + public void Should_add_name_to_the_option_set() { optionSet.Contains("name").ShouldBeTrue(); } [Fact] - public void should_add_short_version_of_name_to_the_option_set() + public void Should_add_short_version_of_name_to_the_option_set() { optionSet.Contains("n").ShouldBeTrue(); } [Fact] - public void should_add_source_to_the_option_set() + public void Should_add_source_to_the_option_set() { optionSet.Contains("source").ShouldBeTrue(); } [Fact] - public void should_add_short_version_of_source_to_the_option_set() + public void Should_add_short_version_of_source_to_the_option_set() { optionSet.Contains("s").ShouldBeTrue(); } [Fact] - public void should_add_user_to_the_option_set() + public void Should_add_user_to_the_option_set() { optionSet.Contains("user").ShouldBeTrue(); } [Fact] - public void should_add_short_version_of_user_to_the_option_set() + public void Should_add_short_version_of_user_to_the_option_set() { optionSet.Contains("u").ShouldBeTrue(); } [Fact] - public void should_add_password_to_the_option_set() + public void Should_add_password_to_the_option_set() { optionSet.Contains("password").ShouldBeTrue(); } [Fact] - public void should_add_short_version_of_password_to_the_option_set() + public void Should_add_short_version_of_password_to_the_option_set() { optionSet.Contains("p").ShouldBeTrue(); } } - public class when_handling_additional_argument_parsing : ChocolateySourceCommandSpecsBase + public class When_handling_additional_argument_parsing : ChocolateySourceCommandSpecsBase { private readonly IList unparsedArgs = new List(); private Action because; public override void Because() { - because = () => command.handle_additional_argument_parsing(unparsedArgs, configuration); + because = () => command.ParseAdditionalArguments(unparsedArgs, configuration); } - public void reset() + public void Reset() { unparsedArgs.Clear(); configSettingsService.ResetCalls(); } [Fact] - public void should_use_the_first_unparsed_arg_as_the_subcommand() + public void Should_use_the_first_unparsed_arg_as_the_subcommand() { - reset(); + Reset(); unparsedArgs.Add("list"); because(); - configuration.SourceCommand.Command.ShouldEqual(SourceCommandType.list); + configuration.SourceCommand.Command.ShouldEqual(SourceCommandType.List); } [Fact] - public void should_throw_when_more_than_one_unparsed_arg_is_passed() + public void Should_throw_when_more_than_one_unparsed_arg_is_passed() { - reset(); + Reset(); unparsedArgs.Add("wtf"); unparsedArgs.Add("bbq"); var errored = false; @@ -189,114 +189,114 @@ public void should_throw_when_more_than_one_unparsed_arg_is_passed() } [Fact] - public void should_accept_add_as_the_subcommand() + public void Should_accept_add_as_the_subcommand() { - reset(); + Reset(); unparsedArgs.Add("add"); because(); - configuration.SourceCommand.Command.ShouldEqual(SourceCommandType.add); + configuration.SourceCommand.Command.ShouldEqual(SourceCommandType.Add); } [Fact] - public void should_accept_uppercase_add_as_the_subcommand() + public void Should_accept_uppercase_add_as_the_subcommand() { - reset(); + Reset(); unparsedArgs.Add("ADD"); because(); - configuration.SourceCommand.Command.ShouldEqual(SourceCommandType.add); + configuration.SourceCommand.Command.ShouldEqual(SourceCommandType.Add); } [Fact] - public void should_remove_add_as_the_subcommand() + public void Should_remove_add_as_the_subcommand() { - reset(); + Reset(); unparsedArgs.Add("remove"); because(); - configuration.SourceCommand.Command.ShouldEqual(SourceCommandType.remove); + configuration.SourceCommand.Command.ShouldEqual(SourceCommandType.Remove); } [Fact] - public void should_accept_enable_as_the_subcommand() + public void Should_accept_enable_as_the_subcommand() { - reset(); + Reset(); unparsedArgs.Add("enable"); because(); - configuration.SourceCommand.Command.ShouldEqual(SourceCommandType.enable); + configuration.SourceCommand.Command.ShouldEqual(SourceCommandType.Enable); } [Fact] - public void should_accept_disable_as_the_subcommand() + public void Should_accept_disable_as_the_subcommand() { - reset(); + Reset(); unparsedArgs.Add("disable"); because(); - configuration.SourceCommand.Command.ShouldEqual(SourceCommandType.disable); + configuration.SourceCommand.Command.ShouldEqual(SourceCommandType.Disable); } [Fact] - public void should_set_unrecognized_values_to_list_as_the_subcommand() + public void Should_set_unrecognized_values_to_list_as_the_subcommand() { - reset(); + Reset(); unparsedArgs.Add("wtf"); because(); - configuration.SourceCommand.Command.ShouldEqual(SourceCommandType.list); + configuration.SourceCommand.Command.ShouldEqual(SourceCommandType.List); } [Fact] - public void should_default_to_list_as_the_subcommand() + public void Should_default_to_list_as_the_subcommand() { - reset(); + Reset(); because(); - configuration.SourceCommand.Command.ShouldEqual(SourceCommandType.list); + configuration.SourceCommand.Command.ShouldEqual(SourceCommandType.List); } [Fact] - public void should_handle_passing_in_an_empty_string() + public void Should_handle_passing_in_an_empty_string() { - reset(); + Reset(); unparsedArgs.Add(" "); because(); - configuration.SourceCommand.Command.ShouldEqual(SourceCommandType.list); + configuration.SourceCommand.Command.ShouldEqual(SourceCommandType.List); } } - public class when_handling_validation : ChocolateySourceCommandSpecsBase + public class When_validating : ChocolateySourceCommandSpecsBase { private Action because; public override void Because() { - because = () => command.handle_validation(configuration); + because = () => command.Validate(configuration); } [Fact] - public void should_throw_when_command_is_not_list_and_name_is_not_set() + public void Should_throw_when_command_is_not_list_and_name_is_not_set() { configuration.SourceCommand.Name = ""; const string expectedMessage = "When specifying the subcommand '{0}', you must also specify --name."; - verify_exception_thrown_on_command(expectedMessage); + VerifyExceptionThrownOnCommand(expectedMessage); } [Fact] - public void should_throw_when_command_is_add_and_source_is_not_set() + public void Should_throw_when_command_is_add_and_source_is_not_set() { configuration.SourceCommand.Name = "irrelevant"; configuration.Sources = string.Empty; const string expectedMessage = "When specifying the subcommand '{0}', you must also specify --source."; - verify_exception_thrown_on_command(expectedMessage); + VerifyExceptionThrownOnCommand(expectedMessage); } - private void verify_exception_thrown_on_command(string expectedMessage) + private void VerifyExceptionThrownOnCommand(string expectedMessage) { - configuration.SourceCommand.Command = SourceCommandType.add; + configuration.SourceCommand.Command = SourceCommandType.Add; var errored = false; Exception error = null; @@ -314,106 +314,106 @@ private void verify_exception_thrown_on_command(string expectedMessage) errored.ShouldBeTrue(); error.ShouldNotBeNull(); error.ShouldBeType(); - var commandName = configuration.SourceCommand.Command.to_string(); - error.Message.ShouldEqual(expectedMessage.format_with(commandName)); + var commandName = configuration.SourceCommand.Command.ToStringSafe().ToLower(); + error.Message.ShouldEqual(expectedMessage.FormatWith(commandName)); } [Fact] - public void should_continue_when_command_is_list_and_name_is_not_set() + public void Should_continue_when_command_is_list_and_name_is_not_set() { - configuration.SourceCommand.Command = SourceCommandType.list; + configuration.SourceCommand.Command = SourceCommandType.List; configuration.SourceCommand.Name = ""; because(); } [Fact] - public void should_continue_when_command_is_not_list_and_name_is_set() + public void Should_continue_when_command_is_not_list_and_name_is_set() { - configuration.SourceCommand.Command = SourceCommandType.list; + configuration.SourceCommand.Command = SourceCommandType.List; configuration.SourceCommand.Name = "bob"; because(); } } - public class when_noop_is_called : ChocolateySourceCommandSpecsBase + public class When_noop_is_called : ChocolateySourceCommandSpecsBase { public override void Because() { - command.noop(configuration); + command.DryRun(configuration); } [Fact] - public void should_call_service_noop() + public void Should_call_service_noop() { - configSettingsService.Verify(c => c.noop(configuration), Times.Once); + configSettingsService.Verify(c => c.DryRun(configuration), Times.Once); } } - public class when_run_is_called : ChocolateySourceCommandSpecsBase + public class When_run_is_called : ChocolateySourceCommandSpecsBase { private Action because; public override void Because() { - because = () => command.run(configuration); + because = () => command.Run(configuration); } [Fact] - public void should_call_service_source_list_when_command_is_list() + public void Should_call_service_source_list_when_command_is_list() { - configuration.SourceCommand.Command = SourceCommandType.list; + configuration.SourceCommand.Command = SourceCommandType.List; because(); - configSettingsService.Verify(c => c.source_list(configuration), Times.Once); + configSettingsService.Verify(c => c.ListSources(configuration), Times.Once); } [Fact] - public void should_call_service_source_add_when_command_is_add() + public void Should_call_service_source_add_when_command_is_add() { - configuration.SourceCommand.Command = SourceCommandType.add; + configuration.SourceCommand.Command = SourceCommandType.Add; because(); - configSettingsService.Verify(c => c.source_add(configuration), Times.Once); + configSettingsService.Verify(c => c.AddSource(configuration), Times.Once); } [Fact] - public void should_call_service_source_remove_when_command_is_remove() + public void Should_call_service_source_remove_when_command_is_remove() { - configuration.SourceCommand.Command = SourceCommandType.remove; + configuration.SourceCommand.Command = SourceCommandType.Remove; because(); - configSettingsService.Verify(c => c.source_remove(configuration), Times.Once); + configSettingsService.Verify(c => c.RemoveSource(configuration), Times.Once); } [Fact] - public void should_call_service_source_disable_when_command_is_disable() + public void Should_call_service_source_disable_when_command_is_disable() { - configuration.SourceCommand.Command = SourceCommandType.disable; + configuration.SourceCommand.Command = SourceCommandType.Disable; because(); - configSettingsService.Verify(c => c.source_disable(configuration), Times.Once); + configSettingsService.Verify(c => c.DisableSource(configuration), Times.Once); } [Fact] - public void should_call_service_source_enable_when_command_is_enable() + public void Should_call_service_source_enable_when_command_is_enable() { - configuration.SourceCommand.Command = SourceCommandType.enable; + configuration.SourceCommand.Command = SourceCommandType.Enable; because(); - configSettingsService.Verify(c => c.source_enable(configuration), Times.Once); + configSettingsService.Verify(c => c.EnableSource(configuration), Times.Once); } } - public class when_list_is_called : ChocolateySourceCommandSpecsBase + public class When_list_is_called : ChocolateySourceCommandSpecsBase { private Action because; public override void Because() { - because = () => command.list(configuration); + because = () => command.List(configuration); } [Fact] - public void should_call_service_source_list_when_command_is_list() + public void Should_call_service_source_list_when_command_is_list() { - configuration.SourceCommand.Command = SourceCommandType.list; + configuration.SourceCommand.Command = SourceCommandType.List; because(); - configSettingsService.Verify(c => c.source_list(configuration), Times.Once); + configSettingsService.Verify(c => c.ListSources(configuration), Times.Once); } } } diff --git a/src/chocolatey.tests/infrastructure.app/commands/ChocolateyTemplateCommandSpecs.cs b/src/chocolatey.tests/infrastructure.app/commands/ChocolateyTemplateCommandSpecs.cs index 4e91d26245..73bd64e103 100644 --- a/src/chocolatey.tests/infrastructure.app/commands/ChocolateyTemplateCommandSpecs.cs +++ b/src/chocolatey.tests/infrastructure.app/commands/ChocolateyTemplateCommandSpecs.cs @@ -31,279 +31,279 @@ namespace chocolatey.tests.infrastructure.app.commands public class ChocolateyTemplateCommandSpecs { - [ConcernFor("template")] - public abstract class ChocolateyTemplateCommandSpecsBase : TinySpec - { - protected ChocolateyTemplateCommand command; - protected Mock templateService = new Mock(); - protected ChocolateyConfiguration configuration = new ChocolateyConfiguration(); - - public override void Context() - { - command = new ChocolateyTemplateCommand(templateService.Object); - } - - public void reset() - { - templateService.ResetCalls(); - } - } - - public class when_implementing_command_for : ChocolateyTemplateCommandSpecsBase - { - private List results; - - public override void Because() - { - results = command.GetType().GetCustomAttributes(typeof(CommandForAttribute), false).Cast().Select(a => a.CommandName).ToList(); - } - - [Fact] - public void should_implement_help() - { - results.ShouldContain("template"); - results.ShouldContain("templates"); - } - } - - public class when_configurating_the_argument_parser : ChocolateyTemplateCommandSpecsBase - { - private OptionSet optionSet; - - public override void Context() - { - base.Context(); - optionSet = new OptionSet(); - } - - public override void Because() - { - command.configure_argument_parser(optionSet, configuration); - } - - [Fact] - public void should_add_name_to_the_option_set() - { - optionSet.Contains("name").ShouldBeTrue(); - } - - [Fact] - public void should_add_short_version_of_name_to_the_option_set() - { - optionSet.Contains("n").ShouldBeTrue(); - } - } - - - public class when_handling_additional_argument_parsing : ChocolateyTemplateCommandSpecsBase - { - private readonly IList unparsedArgs = new List(); - private Action because; - - public override void Because() - { - because = () => command.handle_additional_argument_parsing(unparsedArgs, configuration); - } - - public new void reset() - { - configuration.TemplateCommand.Name = string.Empty; - configuration.TemplateCommand.Command = TemplateCommandType.unknown; - unparsedArgs.Clear(); - base.reset(); - } - - [Fact] - public void should_use_the_first_unparsed_arg_as_the_subcommand() - { - reset(); - unparsedArgs.Add("list"); - because(); - - configuration.TemplateCommand.Command.ShouldEqual(TemplateCommandType.list); - } - - [Fact] - public void should_throw_when_more_than_one_unparsed_arg_is_passed() - { - reset(); - unparsedArgs.Add("badcommand"); - unparsedArgs.Add("bbq"); - var errorred = false; - Exception error = null; - - try - { - because(); - } - catch (Exception ex) - { - errorred = true; - error = ex; - } - - errorred.ShouldBeTrue(); - error.ShouldNotBeNull(); - error.ShouldBeType(); - error.Message.ShouldContain("A single template command must be listed"); - } - - [Fact] - public void should_accept_list_as_the_subcommand() - { - reset(); - unparsedArgs.Add("list"); - because(); - - configuration.TemplateCommand.Command.ShouldEqual(TemplateCommandType.list); - } - - [Fact] - public void should_accept_uppercase_list_as_the_subcommand() - { - reset(); - unparsedArgs.Add("LIST"); - because(); - - configuration.TemplateCommand.Command.ShouldEqual(TemplateCommandType.list); - } - - [Fact] - public void should_accept_info_as_the_subcommand() - { - reset(); - unparsedArgs.Add("info"); - because(); - - configuration.TemplateCommand.Command.ShouldEqual(TemplateCommandType.info); - } - - [Fact] - public void should_accept_uppercase_info_as_the_subcommand() - { - reset(); - unparsedArgs.Add("INFO"); - because(); - - configuration.TemplateCommand.Command.ShouldEqual(TemplateCommandType.info); - } - - [Fact] - public void should_set_unrecognized_values_to_list_as_the_subcommand() - { - reset(); - unparsedArgs.Add("badcommand"); - because(); - - configuration.TemplateCommand.Command.ShouldEqual(TemplateCommandType.list); - } - - [Fact] - public void should_default_to_list_as_the_subcommand() - { - reset(); - because(); - - configuration.TemplateCommand.Command.ShouldEqual(TemplateCommandType.list); - } - - [Fact] - public void should_handle_passing_in_an_empty_string() - { - reset(); - unparsedArgs.Add(" "); - because(); - - configuration.TemplateCommand.Command.ShouldEqual(TemplateCommandType.list); - } - } - - public class when_handling_validation : ChocolateyTemplateCommandSpecsBase - { - private Action because; - - public override void Because() - { - because = () => command.handle_validation(configuration); - } - - [Fact] - public void should_continue_when_command_is_list_and_name_is_set() - { - configuration.TemplateCommand.Command = TemplateCommandType.list; - configuration.TemplateCommand.Name = "bob"; - because(); - } - - [Fact] - public void should_continue_when_command_is_list_and_name_is_not_set() - { - configuration.TemplateCommand.Command = TemplateCommandType.list; - configuration.TemplateCommand.Name = ""; - because(); - } - - [Fact] - public void should_throw_when_command_is_info_and_name_is_not_set() - { - configuration.TemplateCommand.Command = TemplateCommandType.info; - configuration.TemplateCommand.Name = ""; - var errorred = false; - Exception error = null; - - try - { - because(); - } - catch (Exception ex) - { - errorred = true; - error = ex; - } - - errorred.ShouldBeTrue(); - error.ShouldNotBeNull(); - error.ShouldBeType(); - error.Message.ShouldEqual("When specifying the subcommand '{0}', you must also specify --name.".format_with(configuration.TemplateCommand.Command.to_string())); - } - - [Fact] - public void should_continue_when_command_info_and_name_is_set() - { - configuration.TemplateCommand.Command = TemplateCommandType.info; - configuration.TemplateCommand.Name = "bob"; - because(); - } - } - - public class when_noop_is_called : ChocolateyTemplateCommandSpecsBase - { - public override void Because() - { - configuration.TemplateCommand.Command = TemplateCommandType.list; - command.noop(configuration); - } - - [Fact] - public void should_call_service_list_noop() - { - templateService.Verify(c => c.list_noop(configuration), Times.Once); - } - } - - public class when_run_is_called : ChocolateyTemplateCommandSpecsBase - { - public override void Because() - { - configuration.TemplateCommand.Command = TemplateCommandType.list; - command.run(configuration); - } - - [Fact] - public void should_call_service_list() - { - templateService.Verify(c => c.list(configuration), Times.Once); - } - } - } -} + [ConcernFor("template")] + public abstract class ChocolateyTemplateCommandSpecsBase : TinySpec + { + protected ChocolateyTemplateCommand command; + protected Mock templateService = new Mock(); + protected ChocolateyConfiguration configuration = new ChocolateyConfiguration(); + + public override void Context() + { + command = new ChocolateyTemplateCommand(templateService.Object); + } + + public void Reset() + { + templateService.ResetCalls(); + } + } + + public class When_implementing_command_for : ChocolateyTemplateCommandSpecsBase + { + private List results; + + public override void Because() + { + results = command.GetType().GetCustomAttributes(typeof(CommandForAttribute), false).Cast().Select(a => a.CommandName).ToList(); + } + + [Fact] + public void Should_implement_help() + { + results.ShouldContain("template"); + results.ShouldContain("templates"); + } + } + + public class When_configurating_the_argument_parser : ChocolateyTemplateCommandSpecsBase + { + private OptionSet optionSet; + + public override void Context() + { + base.Context(); + optionSet = new OptionSet(); + } + + public override void Because() + { + command.ConfigureArgumentParser(optionSet, configuration); + } + + [Fact] + public void Should_add_name_to_the_option_set() + { + optionSet.Contains("name").ShouldBeTrue(); + } + + [Fact] + public void Should_add_short_version_of_name_to_the_option_set() + { + optionSet.Contains("n").ShouldBeTrue(); + } + } + + + public class When_handling_additional_argument_parsing : ChocolateyTemplateCommandSpecsBase + { + private readonly IList unparsedArgs = new List(); + private Action because; + + public override void Because() + { + because = () => command.ParseAdditionalArguments(unparsedArgs, configuration); + } + + public new void Reset() + { + configuration.TemplateCommand.Name = string.Empty; + configuration.TemplateCommand.Command = TemplateCommandType.Unknown; + unparsedArgs.Clear(); + base.Reset(); + } + + [Fact] + public void Should_use_the_first_unparsed_arg_as_the_subcommand() + { + Reset(); + unparsedArgs.Add("list"); + because(); + + configuration.TemplateCommand.Command.ShouldEqual(TemplateCommandType.List); + } + + [Fact] + public void Should_throw_when_more_than_one_unparsed_arg_is_passed() + { + Reset(); + unparsedArgs.Add("badcommand"); + unparsedArgs.Add("bbq"); + var errorred = false; + Exception error = null; + + try + { + because(); + } + catch (Exception ex) + { + errorred = true; + error = ex; + } + + errorred.ShouldBeTrue(); + error.ShouldNotBeNull(); + error.ShouldBeType(); + error.Message.ShouldContain("A single template command must be listed"); + } + + [Fact] + public void Should_accept_list_as_the_subcommand() + { + Reset(); + unparsedArgs.Add("list"); + because(); + + configuration.TemplateCommand.Command.ShouldEqual(TemplateCommandType.List); + } + + [Fact] + public void Should_accept_uppercase_list_as_the_subcommand() + { + Reset(); + unparsedArgs.Add("LIST"); + because(); + + configuration.TemplateCommand.Command.ShouldEqual(TemplateCommandType.List); + } + + [Fact] + public void Should_accept_info_as_the_subcommand() + { + Reset(); + unparsedArgs.Add("info"); + because(); + + configuration.TemplateCommand.Command.ShouldEqual(TemplateCommandType.Info); + } + + [Fact] + public void Should_accept_uppercase_info_as_the_subcommand() + { + Reset(); + unparsedArgs.Add("INFO"); + because(); + + configuration.TemplateCommand.Command.ShouldEqual(TemplateCommandType.Info); + } + + [Fact] + public void Should_set_unrecognized_values_to_list_as_the_subcommand() + { + Reset(); + unparsedArgs.Add("badcommand"); + because(); + + configuration.TemplateCommand.Command.ShouldEqual(TemplateCommandType.List); + } + + [Fact] + public void Should_default_to_list_as_the_subcommand() + { + Reset(); + because(); + + configuration.TemplateCommand.Command.ShouldEqual(TemplateCommandType.List); + } + + [Fact] + public void Should_handle_passing_in_an_empty_string() + { + Reset(); + unparsedArgs.Add(" "); + because(); + + configuration.TemplateCommand.Command.ShouldEqual(TemplateCommandType.List); + } + } + + public class When_validating : ChocolateyTemplateCommandSpecsBase + { + private Action because; + + public override void Because() + { + because = () => command.Validate(configuration); + } + + [Fact] + public void Should_continue_when_command_is_list_and_name_is_set() + { + configuration.TemplateCommand.Command = TemplateCommandType.List; + configuration.TemplateCommand.Name = "bob"; + because(); + } + + [Fact] + public void Should_continue_when_command_is_list_and_name_is_not_set() + { + configuration.TemplateCommand.Command = TemplateCommandType.List; + configuration.TemplateCommand.Name = ""; + because(); + } + + [Fact] + public void Should_throw_when_command_is_info_and_name_is_not_set() + { + configuration.TemplateCommand.Command = TemplateCommandType.Info; + configuration.TemplateCommand.Name = ""; + var errorred = false; + Exception error = null; + + try + { + because(); + } + catch (Exception ex) + { + errorred = true; + error = ex; + } + + errorred.ShouldBeTrue(); + error.ShouldNotBeNull(); + error.ShouldBeType(); + error.Message.ShouldEqual("When specifying the subcommand '{0}', you must also specify --name.".FormatWith(configuration.TemplateCommand.Command.ToStringSafe().ToLower())); + } + + [Fact] + public void Should_continue_when_command_info_and_name_is_set() + { + configuration.TemplateCommand.Command = TemplateCommandType.Info; + configuration.TemplateCommand.Name = "bob"; + because(); + } + } + + public class When_noop_is_called : ChocolateyTemplateCommandSpecsBase + { + public override void Because() + { + configuration.TemplateCommand.Command = TemplateCommandType.List; + command.DryRun(configuration); + } + + [Fact] + public void Should_call_service_list_noop() + { + templateService.Verify(c => c.ListDryRun(configuration), Times.Once); + } + } + + public class When_run_is_called : ChocolateyTemplateCommandSpecsBase + { + public override void Because() + { + configuration.TemplateCommand.Command = TemplateCommandType.List; + command.Run(configuration); + } + + [Fact] + public void Should_call_service_list() + { + templateService.Verify(c => c.List(configuration), Times.Once); + } + } + } +} diff --git a/src/chocolatey.tests/infrastructure.app/commands/ChocolateyUninstallCommandSpecs.cs b/src/chocolatey.tests/infrastructure.app/commands/ChocolateyUninstallCommandSpecs.cs index 2df9afb25c..8a71d288a1 100644 --- a/src/chocolatey.tests/infrastructure.app/commands/ChocolateyUninstallCommandSpecs.cs +++ b/src/chocolatey.tests/infrastructure.app/commands/ChocolateyUninstallCommandSpecs.cs @@ -44,7 +44,7 @@ public override void Context() } } - public class when_implementing_command_for : ChocolateyUninstallCommandSpecsBase + public class When_implementing_command_for : ChocolateyUninstallCommandSpecsBase { private List results; @@ -54,13 +54,13 @@ public override void Because() } [Fact] - public void should_implement_uninstall() + public void Should_implement_uninstall() { - results.ShouldContain(CommandNameType.uninstall.to_string()); + results.ShouldContain("uninstall"); } } - public class when_configurating_the_argument_parser : ChocolateyUninstallCommandSpecsBase + public class When_configurating_the_argument_parser : ChocolateyUninstallCommandSpecsBase { private OptionSet optionSet; @@ -72,119 +72,119 @@ public override void Context() public override void Because() { - command.configure_argument_parser(optionSet, configuration); + command.ConfigureArgumentParser(optionSet, configuration); } [Fact] - public void should_add_version_to_the_option_set() + public void Should_add_version_to_the_option_set() { optionSet.Contains("version").ShouldBeTrue(); } [Fact] - public void should_add_allversions_to_the_option_set() + public void Should_add_allversions_to_the_option_set() { optionSet.Contains("allversions").ShouldBeTrue(); } [Fact] - public void should_add_short_version_of_allversions_to_the_option_set() + public void Should_add_short_version_of_allversions_to_the_option_set() { optionSet.Contains("a").ShouldBeTrue(); } [Fact] - public void should_add_uninstallargs_to_the_option_set() + public void Should_add_uninstallargs_to_the_option_set() { optionSet.Contains("uninstallarguments").ShouldBeTrue(); } [Fact] - public void should_add_short_version_of_uninstallargs_to_the_option_set() + public void Should_add_short_version_of_uninstallargs_to_the_option_set() { optionSet.Contains("ua").ShouldBeTrue(); } [Fact] - public void should_add_overrideargs_to_the_option_set() + public void Should_add_overrideargs_to_the_option_set() { optionSet.Contains("overridearguments").ShouldBeTrue(); } [Fact] - public void should_add_short_version_of_overrideargs_to_the_option_set() + public void Should_add_short_version_of_overrideargs_to_the_option_set() { optionSet.Contains("o").ShouldBeTrue(); } [Fact] - public void should_add_notsilent_to_the_option_set() + public void Should_add_notsilent_to_the_option_set() { optionSet.Contains("notsilent").ShouldBeTrue(); } [Fact] - public void should_add_packageparameters_to_the_option_set() + public void Should_add_packageparameters_to_the_option_set() { optionSet.Contains("packageparameters").ShouldBeTrue(); } [Fact] - public void should_add_short_version_of_packageparameters_to_the_option_set() + public void Should_add_short_version_of_packageparameters_to_the_option_set() { optionSet.Contains("params").ShouldBeTrue(); } [Fact] - public void should_add_applyPackageParametersToDependencies_to_the_option_set() + public void Should_add_applyPackageParametersToDependencies_to_the_option_set() { optionSet.Contains("apply-package-parameters-to-dependencies").ShouldBeTrue(); } [Fact] - public void should_add_applyInstallArgumentsToDependencies_to_the_option_set() + public void Should_add_applyInstallArgumentsToDependencies_to_the_option_set() { optionSet.Contains("apply-install-arguments-to-dependencies").ShouldBeTrue(); } [Fact] - public void should_add_forcedependencies_to_the_option_set() + public void Should_add_forcedependencies_to_the_option_set() { optionSet.Contains("forcedependencies").ShouldBeTrue(); } [Fact] - public void should_add_short_version_of_forcedependencies_to_the_option_set() + public void Should_add_short_version_of_forcedependencies_to_the_option_set() { optionSet.Contains("x").ShouldBeTrue(); } [Fact] - public void should_add_skippowershell_to_the_option_set() + public void Should_add_skippowershell_to_the_option_set() { optionSet.Contains("skippowershell").ShouldBeTrue(); } [Fact] - public void should_add_short_version_of_skippowershell_to_the_option_set() + public void Should_add_short_version_of_skippowershell_to_the_option_set() { optionSet.Contains("n").ShouldBeTrue(); } [Fact] - public void should_add_skip_hooks_to_the_option_set() + public void Should_add_skip_hooks_to_the_option_set() { optionSet.Contains("skip-hooks").ShouldBeTrue(); } [Fact] - public void should_add_short_version_of_skip_hooks_to_the_option_set() + public void Should_add_short_version_of_skip_hooks_to_the_option_set() { optionSet.Contains("skiphooks").ShouldBeTrue(); } } - public class when_handling_additional_argument_parsing : ChocolateyUninstallCommandSpecsBase + public class When_handling_additional_argument_parsing : ChocolateyUninstallCommandSpecsBase { private readonly IList unparsedArgs = new List(); @@ -197,24 +197,24 @@ public override void Context() public override void Because() { - command.handle_additional_argument_parsing(unparsedArgs, configuration); + command.ParseAdditionalArguments(unparsedArgs, configuration); } [Fact] - public void should_set_unparsed_arguments_to_the_package_names() + public void Should_set_unparsed_arguments_to_the_package_names() { configuration.PackageNames.ShouldEqual("pkg1;pkg2"); } } - public class when_handling_validation : ChocolateyUninstallCommandSpecsBase + public class When_validating : ChocolateyUninstallCommandSpecsBase { public override void Because() { } [Fact] - public void should_throw_when_packagenames_is_not_set() + public void Should_throw_when_packagenames_is_not_set() { configuration.PackageNames = ""; var errored = false; @@ -222,7 +222,7 @@ public void should_throw_when_packagenames_is_not_set() try { - command.handle_validation(configuration); + command.Validate(configuration); } catch (Exception ex) { @@ -236,38 +236,38 @@ public void should_throw_when_packagenames_is_not_set() } [Fact] - public void should_continue_when_packagenames_is_set() + public void Should_continue_when_packagenames_is_set() { configuration.PackageNames = "bob"; - command.handle_validation(configuration); + command.Validate(configuration); } } - public class when_noop_is_called : ChocolateyUninstallCommandSpecsBase + public class When_noop_is_called : ChocolateyUninstallCommandSpecsBase { public override void Because() { - command.noop(configuration); + command.DryRun(configuration); } [Fact] - public void should_call_service_uninstall_noop() + public void Should_call_service_uninstall_noop() { - packageService.Verify(c => c.uninstall_noop(configuration), Times.Once); + packageService.Verify(c => c.UninstallDryRun(configuration), Times.Once); } } - public class when_run_is_called : ChocolateyUninstallCommandSpecsBase + public class When_run_is_called : ChocolateyUninstallCommandSpecsBase { public override void Because() { - command.run(configuration); + command.Run(configuration); } [Fact] - public void should_call_service_uninstall_run() + public void Should_call_service_uninstall_run() { - packageService.Verify(c => c.uninstall_run(configuration), Times.Once); + packageService.Verify(c => c.Uninstall(configuration), Times.Once); } } } diff --git a/src/chocolatey.tests/infrastructure.app/commands/ChocolateyUnpackSelfCommandSpecs.cs b/src/chocolatey.tests/infrastructure.app/commands/ChocolateyUnpackSelfCommandSpecs.cs index eb22a5d429..e23c336897 100644 --- a/src/chocolatey.tests/infrastructure.app/commands/ChocolateyUnpackSelfCommandSpecs.cs +++ b/src/chocolatey.tests/infrastructure.app/commands/ChocolateyUnpackSelfCommandSpecs.cs @@ -40,11 +40,11 @@ public abstract class ChocolateyUnpackSelfCommandSpecsBase : TinySpec public override void Context() { command = new ChocolateyUnpackSelfCommand(fileSystem.Object); - command.initialize_with(new Lazy(() => assembly.Object)); + command.InitializeWith(new Lazy(() => assembly.Object)); } } - public class when_implementing_command_for : ChocolateyUnpackSelfCommandSpecsBase + public class When_implementing_command_for : ChocolateyUnpackSelfCommandSpecsBase { private List results; @@ -54,47 +54,47 @@ public override void Because() } [Fact] - public void should_implement_unpackself() + public void Should_implement_unpackself() { results.ShouldContain("unpackself"); } } - public class when_noop_is_called : ChocolateyUnpackSelfCommandSpecsBase + public class When_noop_is_called : ChocolateyUnpackSelfCommandSpecsBase { public override void Because() { - command.noop(configuration); + command.DryRun(configuration); } [Fact] - public void should_log_a_message() + public void Should_log_a_message() { MockLogger.Verify(l => l.Info(It.IsAny()), Times.Once); } [Fact] - public void should_log_one_message() + public void Should_log_one_message() { MockLogger.Messages.Count.ShouldEqual(1); } [Fact] - public void should_log_a_message_about_what_it_would_have_done() + public void Should_log_a_message_about_what_it_would_have_done() { MockLogger.MessagesFor(LogLevel.Info).FirstOrDefault().ShouldContain("This would have unpacked"); } } - public class when_run_is_called : ChocolateyUnpackSelfCommandSpecsBase + public class When_run_is_called : ChocolateyUnpackSelfCommandSpecsBase { public override void Because() { - command.run(configuration); + command.Run(configuration); } [Fact] - public void should_call_assembly_file_extractor() + public void Should_call_assembly_file_extractor() { assembly.Verify(a => a.GetManifestResourceNames(), Times.Once); } diff --git a/src/chocolatey.tests/infrastructure.app/commands/ChocolateyUpgradeCommandSpecs.cs b/src/chocolatey.tests/infrastructure.app/commands/ChocolateyUpgradeCommandSpecs.cs index c95a9328dd..4651d7d354 100644 --- a/src/chocolatey.tests/infrastructure.app/commands/ChocolateyUpgradeCommandSpecs.cs +++ b/src/chocolatey.tests/infrastructure.app/commands/ChocolateyUpgradeCommandSpecs.cs @@ -44,7 +44,7 @@ public override void Context() } } - public class when_implementing_command_for : ChocolateyUpgradeCommandSpecsBase + public class When_implementing_command_for : ChocolateyUpgradeCommandSpecsBase { private List results; @@ -54,13 +54,13 @@ public override void Because() } [Fact] - public void should_implement_upgrade() + public void Should_implement_upgrade() { - results.ShouldContain(CommandNameType.upgrade.to_string()); + results.ShouldContain("upgrade"); } } - public class when_configurating_the_argument_parser : ChocolateyUpgradeCommandSpecsBase + public class When_configurating_the_argument_parser : ChocolateyUpgradeCommandSpecsBase { private OptionSet optionSet; @@ -72,173 +72,173 @@ public override void Context() public override void Because() { - command.configure_argument_parser(optionSet, configuration); + command.ConfigureArgumentParser(optionSet, configuration); } [Fact] - public void should_add_source_to_the_option_set() + public void Should_add_source_to_the_option_set() { optionSet.Contains("source").ShouldBeTrue(); } [Fact] - public void should_add_short_version_of_source_to_the_option_set() + public void Should_add_short_version_of_source_to_the_option_set() { optionSet.Contains("s").ShouldBeTrue(); } [Fact] - public void should_add_version_to_the_option_set() + public void Should_add_version_to_the_option_set() { optionSet.Contains("version").ShouldBeTrue(); } [Fact] - public void should_add_prerelease_to_the_option_set() + public void Should_add_prerelease_to_the_option_set() { optionSet.Contains("prerelease").ShouldBeTrue(); } [Fact] - public void should_add_short_version_of_prerelease_to_the_option_set() + public void Should_add_short_version_of_prerelease_to_the_option_set() { optionSet.Contains("pre").ShouldBeTrue(); } [Fact] - public void should_add_installargs_to_the_option_set() + public void Should_add_installargs_to_the_option_set() { optionSet.Contains("installarguments").ShouldBeTrue(); } [Fact] - public void should_add_short_version_of_installargs_to_the_option_set() + public void Should_add_short_version_of_installargs_to_the_option_set() { optionSet.Contains("ia").ShouldBeTrue(); } [Fact] - public void should_add_overrideargs_to_the_option_set() + public void Should_add_overrideargs_to_the_option_set() { optionSet.Contains("overridearguments").ShouldBeTrue(); } [Fact] - public void should_add_short_version_of_overrideargs_to_the_option_set() + public void Should_add_short_version_of_overrideargs_to_the_option_set() { optionSet.Contains("o").ShouldBeTrue(); } [Fact] - public void should_add_notsilent_to_the_option_set() + public void Should_add_notsilent_to_the_option_set() { optionSet.Contains("notsilent").ShouldBeTrue(); } [Fact] - public void should_add_packageparameters_to_the_option_set() + public void Should_add_packageparameters_to_the_option_set() { optionSet.Contains("packageparameters").ShouldBeTrue(); } [Fact] - public void should_add_short_version_of_packageparameters_to_the_option_set() + public void Should_add_short_version_of_packageparameters_to_the_option_set() { optionSet.Contains("params").ShouldBeTrue(); } [Fact] - public void should_add_applyPackageParametersToDependencies_to_the_option_set() + public void Should_add_applyPackageParametersToDependencies_to_the_option_set() { optionSet.Contains("apply-package-parameters-to-dependencies").ShouldBeTrue(); } [Fact] - public void should_add_applyInstallArgumentsToDependencies_to_the_option_set() + public void Should_add_applyInstallArgumentsToDependencies_to_the_option_set() { optionSet.Contains("apply-install-arguments-to-dependencies").ShouldBeTrue(); } [Fact] - public void should_add_ignoredependencies_to_the_option_set() + public void Should_add_ignoredependencies_to_the_option_set() { optionSet.Contains("ignoredependencies").ShouldBeTrue(); } [Fact] - public void should_add_short_version_of_ignoredependencies_to_the_option_set() + public void Should_add_short_version_of_ignoredependencies_to_the_option_set() { optionSet.Contains("i").ShouldBeTrue(); } [Fact] - public void should_add_skippowershell_to_the_option_set() + public void Should_add_skippowershell_to_the_option_set() { optionSet.Contains("skippowershell").ShouldBeTrue(); } [Fact] - public void should_add_short_version_of_skippowershell_to_the_option_set() + public void Should_add_short_version_of_skippowershell_to_the_option_set() { optionSet.Contains("n").ShouldBeTrue(); } [Fact] - public void should_add_user_to_the_option_set() + public void Should_add_user_to_the_option_set() { optionSet.Contains("user").ShouldBeTrue(); } [Fact] - public void should_add_short_version_of_user_to_the_option_set() + public void Should_add_short_version_of_user_to_the_option_set() { optionSet.Contains("u").ShouldBeTrue(); } [Fact] - public void should_add_password_to_the_option_set() + public void Should_add_password_to_the_option_set() { optionSet.Contains("password").ShouldBeTrue(); } [Fact] - public void should_add_short_version_of_password_to_the_option_set() + public void Should_add_short_version_of_password_to_the_option_set() { optionSet.Contains("p").ShouldBeTrue(); } [Fact] - public void should_add_pin_to_the_option_set() + public void Should_add_pin_to_the_option_set() { optionSet.Contains("pinpackage").ShouldBeTrue(); } [Fact] - public void should_add_long_version_of_pin_to_the_option_set() + public void Should_add_long_version_of_pin_to_the_option_set() { optionSet.Contains("pin-package").ShouldBeTrue(); } [Fact] - public void should_add_short_version_of_pin_to_the_option_set() + public void Should_add_short_version_of_pin_to_the_option_set() { optionSet.Contains("pin").ShouldBeTrue(); } - + [Fact] - public void should_add_skip_hooks_to_the_option_set() + public void Should_add_skip_hooks_to_the_option_set() { optionSet.Contains("skip-hooks").ShouldBeTrue(); } [Fact] - public void should_add_short_version_of_skip_hooks_to_the_option_set() + public void Should_add_short_version_of_skip_hooks_to_the_option_set() { optionSet.Contains("skiphooks").ShouldBeTrue(); } } - public class when_handling_additional_argument_parsing : ChocolateyUpgradeCommandSpecsBase + public class When_handling_additional_argument_parsing : ChocolateyUpgradeCommandSpecsBase { private readonly IList unparsedArgs = new List(); @@ -251,24 +251,24 @@ public override void Context() public override void Because() { - command.handle_additional_argument_parsing(unparsedArgs, configuration); + command.ParseAdditionalArguments(unparsedArgs, configuration); } [Fact] - public void should_set_unparsed_arguments_to_the_package_names() + public void Should_set_unparsed_arguments_to_the_package_names() { configuration.PackageNames.ShouldEqual("pkg1;pkg2"); } } - public class when_handling_validation : ChocolateyUpgradeCommandSpecsBase + public class When_validating : ChocolateyUpgradeCommandSpecsBase { public override void Because() { } [Fact] - public void should_throw_when_packagenames_is_not_set() + public void Should_throw_when_packagenames_is_not_set() { configuration.PackageNames = ""; var errored = false; @@ -276,7 +276,7 @@ public void should_throw_when_packagenames_is_not_set() try { - command.handle_validation(configuration); + command.Validate(configuration); } catch (Exception ex) { @@ -290,38 +290,38 @@ public void should_throw_when_packagenames_is_not_set() } [Fact] - public void should_continue_when_packagenames_is_set() + public void Should_continue_when_packagenames_is_set() { configuration.PackageNames = "bob"; - command.handle_validation(configuration); + command.Validate(configuration); } } - public class when_noop_is_called : ChocolateyUpgradeCommandSpecsBase + public class When_noop_is_called : ChocolateyUpgradeCommandSpecsBase { public override void Because() { - command.noop(configuration); + command.DryRun(configuration); } [Fact] - public void should_call_service_upgrade_noop() + public void Should_call_service_upgrade_noop() { - packageService.Verify(c => c.upgrade_noop(configuration), Times.Once); + packageService.Verify(c => c.UpgradeDryRun(configuration), Times.Once); } } - public class when_run_is_called : ChocolateyUpgradeCommandSpecsBase + public class When_run_is_called : ChocolateyUpgradeCommandSpecsBase { public override void Because() { - command.run(configuration); + command.Run(configuration); } [Fact] - public void should_call_service_upgrade_run() + public void Should_call_service_upgrade_run() { - packageService.Verify(c => c.upgrade_run(configuration), Times.Once); + packageService.Verify(c => c.Upgrade(configuration), Times.Once); } } } diff --git a/src/chocolatey.tests/infrastructure.app/configuration/ConfigurationOptionsSpec.cs b/src/chocolatey.tests/infrastructure.app/configuration/ConfigurationOptionsSpec.cs index 240bb438e3..f076c05c5a 100644 --- a/src/chocolatey.tests/infrastructure.app/configuration/ConfigurationOptionsSpec.cs +++ b/src/chocolatey.tests/infrastructure.app/configuration/ConfigurationOptionsSpec.cs @@ -45,8 +45,8 @@ public abstract class ConfigurationOptionsSpecBase : TinySpec public override void Context() { - ConfigurationOptions.initialize_with(new Lazy(() => console.Object)); - ConfigurationOptions.reset_options(); + ConfigurationOptions.InitializeWith(new Lazy(() => console.Object)); + ConfigurationOptions.ClearOptions(); console.Setup((c) => c.Error).Returns(errorWriter); console.Setup((c) => c.Out).Returns(outputWriter); } @@ -55,7 +55,7 @@ public override void Context() public override void Because() { - because = () => ConfigurationOptions.parse_arguments_and_update_configuration(args, config, setOptions, afterParse, validateConfiguration, helpMessage); + because = () => ConfigurationOptions.ParseArgumentsAndUpdateConfiguration(args, config, setOptions, afterParse, validateConfiguration, helpMessage); } public override void BeforeEachSpec() @@ -67,14 +67,14 @@ public override void BeforeEachSpec() validateConfiguration = () => { }; helpMessage = () => { }; helpMessageContents.Clear(); - ConfigurationOptions.reset_options(); + ConfigurationOptions.ClearOptions(); } } - public class when_ConfigurationOptions_parses_arguments_and_updates_configuration_method : ConfigurationOptionsSpecBase + public class When_ConfigurationOptions_parses_arguments_and_updates_configuration_method : ConfigurationOptionsSpecBase { [Fact] - public void should_set_help_options_by_default() + public void Should_set_help_options_by_default() { setOptions = set => { @@ -86,24 +86,37 @@ public void should_set_help_options_by_default() } [Fact] - public void should_not_have_set_other_options_by_default() + public void Should_not_have_set_other_options_by_default() { setOptions = set => { set.Contains("dude").ShouldBeFalse(); }; because(); } [Fact] - public void should_show_help_menu_when_help_is_requested() + public void Should_show_help_menu_when_help_is_requested() { args.Add("-h"); because(); config.HelpRequested.ShouldBeTrue(); + config.ShowOnlineHelp.ShouldBeFalse(); } [Fact] - public void should_have_a_helpMessage_with_contents_when_help_is_requested() + public void Should_show_online_help_menu_when_help_is_requested() + { + args.Add("-h"); + args.Add("--online"); + + because(); + + config.HelpRequested.ShouldBeTrue(); + config.ShowOnlineHelp.ShouldBeTrue(); + } + + [Fact] + public void Should_have_a_helpMessage_with_contents_when_help_is_requested() { args.Add("-h"); @@ -113,7 +126,7 @@ public void should_have_a_helpMessage_with_contents_when_help_is_requested() } [Fact] - public void should_not_run_validate_configuration_when_help_is_requested() + public void Should_not_run_validate_configuration_when_help_is_requested() { args.Add("-h"); validateConfiguration = () => { "should".ShouldEqual("not be reached"); }; @@ -122,7 +135,7 @@ public void should_not_run_validate_configuration_when_help_is_requested() } [Fact] - public void should_run_validate_configuration_unless_help_is_requested() + public void Should_run_validate_configuration_unless_help_is_requested() { var wasCalled = false; validateConfiguration = () => { wasCalled = true; }; @@ -133,7 +146,7 @@ public void should_run_validate_configuration_unless_help_is_requested() } [Fact] - public void should_give_an_empty_unparsed_args_to_after_parse() + public void Should_give_an_empty_unparsed_args_to_after_parse() { var wasCalled = false; afterParse = list => @@ -148,7 +161,7 @@ public void should_give_an_empty_unparsed_args_to_after_parse() } [Fact] - public void should_give_an_empty_unparsed_args_to_after_parse_when_all_specified_args_are_parsed() + public void Should_give_an_empty_unparsed_args_to_after_parse_when_all_specified_args_are_parsed() { args.Add("-h"); var wasCalled = false; @@ -164,7 +177,7 @@ public void should_give_an_empty_unparsed_args_to_after_parse_when_all_specified } [Fact] - public void should_give_unparsed_args_to_after_parse_when_not_picked_up_by_an_option() + public void Should_give_unparsed_args_to_after_parse_when_not_picked_up_by_an_option() { args.Add("--what-is=this"); var wasCalled = false; @@ -180,7 +193,7 @@ public void should_give_unparsed_args_to_after_parse_when_not_picked_up_by_an_op } [Fact] - public void should_find_command_name_in_unparsed_args_if_not_set_otherwise() + public void Should_find_command_name_in_unparsed_args_if_not_set_otherwise() { args.Add("dude"); var wasCalled = false; @@ -197,7 +210,7 @@ public void should_find_command_name_in_unparsed_args_if_not_set_otherwise() } [Fact] - public void should_set_help_requested_if_command_name_is_starts_with_a_prefix() + public void Should_set_help_requested_if_command_name_is_starts_with_a_prefix() { args.Add("/dude"); var wasCalled = false; @@ -215,7 +228,7 @@ public void should_set_help_requested_if_command_name_is_starts_with_a_prefix() } [Fact] - public void should_add_an_option_for_bob_when_specified() + public void Should_add_an_option_for_bob_when_specified() { setOptions = set => { set.Add("bob", "sets the bob switch", option => config.Verbose = option != null); }; because(); @@ -224,7 +237,7 @@ public void should_add_an_option_for_bob_when_specified() } [Fact] - public void should_set_option_for_tim_to_true_when_specified_with_dash() + public void Should_set_option_for_tim_to_true_when_specified_with_dash() { setOptions = set => { set.Add("tim", "sets the tim switch", option => config.Verbose = option != null); }; args.Add("-tim"); @@ -235,7 +248,7 @@ public void should_set_option_for_tim_to_true_when_specified_with_dash() } [Fact] - public void should_set_option_for_tina_to_true_when_specified_with_two_dashes() + public void Should_set_option_for_tina_to_true_when_specified_with_two_dashes() { setOptions = set => { set.Add("tina", "sets the tina switch", option => config.Verbose = option != null); }; args.Add("--tina"); @@ -245,7 +258,7 @@ public void should_set_option_for_tina_to_true_when_specified_with_two_dashes() } [Fact] - public void should_set_option_for_gena_to_true_when_specified_with_forward_slash() + public void Should_set_option_for_gena_to_true_when_specified_with_forward_slash() { setOptions = set => { set.Add("gena", "sets the gena switch", option => config.Verbose = option != null); }; args.Add("/gena"); @@ -256,7 +269,7 @@ public void should_set_option_for_gena_to_true_when_specified_with_forward_slash } [Fact] - public void should_set_option_when_specified_as_single_dash_for_timmy_and_other_option_short_values_are_passed_the_same_way() + public void Should_set_option_when_specified_as_single_dash_for_timmy_and_other_option_short_values_are_passed_the_same_way() { setOptions = set => { @@ -275,7 +288,7 @@ public void should_set_option_when_specified_as_single_dash_for_timmy_and_other_ } [Fact] - public void should_set_option_when_specified_as_single_dash_for_lo_and_other_option_short_values_are_passed_the_same_way() + public void Should_set_option_when_specified_as_single_dash_for_lo_and_other_option_short_values_are_passed_the_same_way() { setOptions = set => { @@ -295,7 +308,7 @@ public void should_set_option_when_specified_as_single_dash_for_lo_and_other_opt } [Fact] - public void should_show_help_menu_when_passing_bundled_options_that_do_not_exist() + public void Should_show_help_menu_when_passing_bundled_options_that_do_not_exist() { setOptions = set => { set.Add("w|wdebug", "sets the debug switch", option => config.Debug = option != null); }; args.Add("-wz"); @@ -307,7 +320,7 @@ public void should_show_help_menu_when_passing_bundled_options_that_do_not_exist } [Fact] - public void should_successfully_parse_help_option() + public void Should_successfully_parse_help_option() { args.Add("-h"); @@ -317,7 +330,7 @@ public void should_successfully_parse_help_option() } [Fact] - public void should_not_parse_unknown_option() + public void Should_not_parse_unknown_option() { args.Add("-unknown"); diff --git a/src/chocolatey.tests/infrastructure.app/nuget/ChocolateyNuGetProjectContextSpecs.cs b/src/chocolatey.tests/infrastructure.app/nuget/ChocolateyNuGetProjectContextSpecs.cs index 4b6b8d8432..053119336d 100644 --- a/src/chocolatey.tests/infrastructure.app/nuget/ChocolateyNuGetProjectContextSpecs.cs +++ b/src/chocolatey.tests/infrastructure.app/nuget/ChocolateyNuGetProjectContextSpecs.cs @@ -39,7 +39,7 @@ public override void Context() } [Categories.Logging, Parallelizable(ParallelScope.Self)] - public class when_calling_logging_methods_the_passed_in_logger_is_used : ChocolateyNuGetProjectContextSpecsBase + public class When_calling_logging_methods_the_passed_in_logger_is_used : ChocolateyNuGetProjectContextSpecsBase { public override void Because() { } @@ -52,7 +52,7 @@ public override void BeforeEachSpec() } [Fact] - public void should_log_debug_information_in_child_logger() + public void Should_log_debug_information_in_child_logger() { Service.Log(MessageLevel.Debug, "Some {0} message", "DEBUG"); @@ -63,7 +63,7 @@ public void should_log_debug_information_in_child_logger() } [Fact] - public void should_log_error_information_in_child_logger() + public void Should_log_error_information_in_child_logger() { Service.Log(MessageLevel.Error, "Some {0} message", "ERROR"); @@ -74,7 +74,7 @@ public void should_log_error_information_in_child_logger() } [Fact] - public void should_log_info_information_in_child_logger() + public void Should_log_info_information_in_child_logger() { Service.Log(MessageLevel.Info, "Some {0} message", "INFO"); @@ -85,7 +85,7 @@ public void should_log_info_information_in_child_logger() } [TestCase(LogLevel.Debug)] - public void should_log_to_child_logger_and_pass_along_original_message(LogLevel logLevel) + public void Should_log_to_child_logger_and_pass_along_original_message(LogLevel logLevel) { var logMessage = new LogMessage(logLevel, "My awesome message"); @@ -98,7 +98,7 @@ public void should_log_to_child_logger_and_pass_along_original_message(LogLevel } [Fact] - public void should_log_warning_information_in_child_logger() + public void Should_log_warning_information_in_child_logger() { Service.Log(MessageLevel.Warning, "Some {0} message", "WARNING"); @@ -109,7 +109,7 @@ public void should_log_warning_information_in_child_logger() } [Fact] - public void should_report_errors_to_child_logger() + public void Should_report_errors_to_child_logger() { Service.ReportError("Some kind of error!"); @@ -120,7 +120,7 @@ public void should_report_errors_to_child_logger() } [Fact] - public void should_report_errors_with_message_to_child_logger() + public void Should_report_errors_with_message_to_child_logger() { var logMessage = new LogMessage(LogLevel.Debug, "Some message"); @@ -133,7 +133,7 @@ public void should_report_errors_with_message_to_child_logger() } [Fact] - public void should_report_warning_when_resolving_file_conflicts() + public void Should_report_warning_when_resolving_file_conflicts() { var message = "Some kind of message"; diff --git a/src/chocolatey.tests/infrastructure.app/nuget/ChocolateyNugetLoggerSpecs.cs b/src/chocolatey.tests/infrastructure.app/nuget/ChocolateyNugetLoggerSpecs.cs index a4832e804c..1c704d843e 100644 --- a/src/chocolatey.tests/infrastructure.app/nuget/ChocolateyNugetLoggerSpecs.cs +++ b/src/chocolatey.tests/infrastructure.app/nuget/ChocolateyNugetLoggerSpecs.cs @@ -28,7 +28,7 @@ namespace chocolatey.tests.infrastructure.app.nuget public class ChocolateyNugetLoggerSpecs { [Categories.Logging] - public class when_calling_log_level_methods_should_log_with_appropriate_log_type : TinySpec + public class When_calling_log_level_methods_should_log_with_appropriate_log_type : TinySpec { private ILogger _logger; @@ -39,7 +39,7 @@ public override void Because() public override void BeforeEachSpec() { base.BeforeEachSpec(); - MockLogger.reset(); + MockLogger.Reset(); } public override void Context() @@ -48,14 +48,14 @@ public override void Context() } [Fact] - public void should_log_debug_level_with_nuget_prefix_on_all_lines_when_calling_LogDebug() + public void Should_log_debug_level_with_nuget_prefix_on_all_lines_when_calling_LogDebug() { const string testMessage = "This should be a debug message.\r\nThis is the second line after CRLF line ending.\nThis is the third line after LF line ending."; - var expectedMessage = "[NuGet] This should be a debug message.{0}[NuGet] This is the second line after CRLF line ending.{0}[NuGet] This is the third line after LF line ending.".format_with(Environment.NewLine); + var expectedMessage = "[NuGet] This should be a debug message.{0}[NuGet] This is the second line after CRLF line ending.{0}[NuGet] This is the third line after LF line ending.".FormatWith(Environment.NewLine); _logger.LogDebug(testMessage); - var loggerName = LogLevel.Debug.to_string(); + var loggerName = LogLevel.Debug.ToStringSafe(); MockLogger.LoggerNames.Count.ShouldEqual(1); MockLogger.LoggerNames.ShouldContain(typeof(ChocolateyNugetLogger).FullName); MockLogger.Messages.Keys.ShouldContain(loggerName); @@ -63,14 +63,14 @@ public void should_log_debug_level_with_nuget_prefix_on_all_lines_when_calling_L } [Fact] - public void should_log_debug_level_with_nuget_prefix_when_calling_LogDebug() + public void Should_log_debug_level_with_nuget_prefix_when_calling_LogDebug() { const string testMessage = "This should be a debug message"; const string expectedMessage = "[NuGet] " + testMessage; _logger.LogDebug(testMessage); - var loggerName = LogLevel.Debug.to_string(); + var loggerName = LogLevel.Debug.ToStringSafe(); MockLogger.LoggerNames.Count.ShouldEqual(1); MockLogger.LoggerNames.ShouldContain(typeof(ChocolateyNugetLogger).FullName); MockLogger.Messages.Keys.ShouldContain(loggerName); @@ -78,14 +78,14 @@ public void should_log_debug_level_with_nuget_prefix_when_calling_LogDebug() } [Fact] - public void should_log_error_level_with_nuget_prefix_on_all_lines_when_calling_LogError() + public void Should_log_error_level_with_nuget_prefix_on_all_lines_when_calling_LogError() { const string testMessage = "This should be a error message.\r\nThis is the second line after CRLF line ending.\nThis is the third line after LF line ending."; - var expectedMessage = "[NuGet] This should be a error message.{0}[NuGet] This is the second line after CRLF line ending.{0}[NuGet] This is the third line after LF line ending.".format_with(Environment.NewLine); + var expectedMessage = "[NuGet] This should be a error message.{0}[NuGet] This is the second line after CRLF line ending.{0}[NuGet] This is the third line after LF line ending.".FormatWith(Environment.NewLine); _logger.LogError(testMessage); - var loggerName = LogLevel.Error.to_string(); + var loggerName = LogLevel.Error.ToStringSafe(); MockLogger.LoggerNames.Count.ShouldEqual(1); MockLogger.LoggerNames.ShouldContain(typeof(ChocolateyNugetLogger).FullName); MockLogger.Messages.Keys.ShouldContain(loggerName); @@ -93,14 +93,14 @@ public void should_log_error_level_with_nuget_prefix_on_all_lines_when_calling_L } [Fact] - public void should_log_error_level_with_nuget_prefix_when_calling_LogError() + public void Should_log_error_level_with_nuget_prefix_when_calling_LogError() { const string testMessage = "This should be a error message"; const string expectedMessage = "[NuGet] " + testMessage; _logger.LogError(testMessage); - var loggerName = LogLevel.Error.to_string(); + var loggerName = LogLevel.Error.ToStringSafe(); MockLogger.LoggerNames.Count.ShouldEqual(1); MockLogger.LoggerNames.ShouldContain(typeof(ChocolateyNugetLogger).FullName); MockLogger.Messages.Keys.ShouldContain(loggerName); @@ -111,63 +111,63 @@ public void should_log_error_level_with_nuget_prefix_when_calling_LogError() [TestCase(NuGetLogLevel.Error, LogLevel.Error, "Test error message", "[NuGet] Test error message")] [TestCase(NuGetLogLevel.Minimal, LogLevel.Info, "Test informational message", "[NuGet] Test informational message")] [TestCase(NuGetLogLevel.Warning, LogLevel.Warn, "Test warning message", "[NuGet] Test warning message")] - public void should_log_expected_log_level_when_calling_Log_with_log_message(NuGetLogLevel nugetLogLevel, LogLevel logLevel, string testMessage, string expectedMessage) + public void Should_log_expected_log_level_when_calling_Log_with_log_message(NuGetLogLevel nugetLogLevel, LogLevel logLevel, string testMessage, string expectedMessage) { _logger.Log(new LogMessage(nugetLogLevel, testMessage)); MockLogger.LoggerNames.Count.ShouldEqual(1); MockLogger.LoggerNames.ShouldContain(typeof(ChocolateyNugetLogger).FullName); - MockLogger.Messages.Keys.ShouldContain(logLevel.to_string()); - MockLogger.Messages[logLevel.to_string()].ShouldContain(expectedMessage); + MockLogger.Messages.Keys.ShouldContain(logLevel.ToStringSafe()); + MockLogger.Messages[logLevel.ToStringSafe()].ShouldContain(expectedMessage); } [TestCase(NuGetLogLevel.Debug, LogLevel.Debug, "Test debug message", "[NuGet] Test debug message")] [TestCase(NuGetLogLevel.Error, LogLevel.Error, "Test error message", "[NuGet] Test error message")] [TestCase(NuGetLogLevel.Minimal, LogLevel.Info, "Test informational message", "[NuGet] Test informational message")] [TestCase(NuGetLogLevel.Warning, LogLevel.Warn, "Test warning message", "[NuGet] Test warning message")] - public void should_log_expected_log_level_when_calling_Log_with_nuget_log_level(NuGetLogLevel nugetLogLevel, LogLevel logLevel, string testMessage, string expectedMessage) + public void Should_log_expected_log_level_when_calling_Log_with_nuget_log_level(NuGetLogLevel nugetLogLevel, LogLevel logLevel, string testMessage, string expectedMessage) { _logger.Log(nugetLogLevel, testMessage); MockLogger.LoggerNames.Count.ShouldEqual(1); MockLogger.LoggerNames.ShouldContain(typeof(ChocolateyNugetLogger).FullName); - MockLogger.Messages.Keys.ShouldContain(logLevel.to_string()); - MockLogger.Messages[logLevel.to_string()].ShouldContain(expectedMessage); + MockLogger.Messages.Keys.ShouldContain(logLevel.ToStringSafe()); + MockLogger.Messages[logLevel.ToStringSafe()].ShouldContain(expectedMessage); } [TestCase(NuGetLogLevel.Debug, LogLevel.Debug, "Test debug message", "[NuGet] Test debug message")] [TestCase(NuGetLogLevel.Error, LogLevel.Error, "Test error message", "[NuGet] Test error message")] [TestCase(NuGetLogLevel.Minimal, LogLevel.Info, "Test informational message", "[NuGet] Test informational message")] [TestCase(NuGetLogLevel.Warning, LogLevel.Warn, "Test warning message", "[NuGet] Test warning message")] - public async Task should_log_expected_log_level_when_calling_LogAsync_with_nuget_log_level(NuGetLogLevel nugetLogLevel, LogLevel logLevel, string testMessage, string expectedMessage) + public async Task Should_log_expected_log_level_when_calling_LogAsync_with_nuget_log_level(NuGetLogLevel nugetLogLevel, LogLevel logLevel, string testMessage, string expectedMessage) { await _logger.LogAsync(nugetLogLevel, testMessage); MockLogger.LoggerNames.Count.ShouldEqual(1); MockLogger.LoggerNames.ShouldContain(typeof(ChocolateyNugetLogger).FullName); - MockLogger.Messages.Keys.ShouldContain(logLevel.to_string()); - MockLogger.Messages[logLevel.to_string()].ShouldContain(expectedMessage); + MockLogger.Messages.Keys.ShouldContain(logLevel.ToStringSafe()); + MockLogger.Messages[logLevel.ToStringSafe()].ShouldContain(expectedMessage); } [TestCase(NuGetLogLevel.Debug, LogLevel.Debug, "Test debug message", "[NuGet] Test debug message")] [TestCase(NuGetLogLevel.Error, LogLevel.Error, "Test error message", "[NuGet] Test error message")] [TestCase(NuGetLogLevel.Minimal, LogLevel.Info, "Test informational message", "[NuGet] Test informational message")] [TestCase(NuGetLogLevel.Warning, LogLevel.Warn, "Test warning message", "[NuGet] Test warning message")] - public async Task should_log_expected_log_level_when_calling_LogAsync_with_nuget_log_message(NuGetLogLevel nugetLogLevel, LogLevel logLevel, string testMessage, string expectedMessage) + public async Task Should_log_expected_log_level_when_calling_LogAsync_with_nuget_log_message(NuGetLogLevel nugetLogLevel, LogLevel logLevel, string testMessage, string expectedMessage) { await _logger.LogAsync(new LogMessage(nugetLogLevel, testMessage)); MockLogger.LoggerNames.Count.ShouldEqual(1); MockLogger.LoggerNames.ShouldContain(typeof(ChocolateyNugetLogger).FullName); - MockLogger.Messages.Keys.ShouldContain(logLevel.to_string()); - MockLogger.Messages[logLevel.to_string()].ShouldContain(expectedMessage); + MockLogger.Messages.Keys.ShouldContain(logLevel.ToStringSafe()); + MockLogger.Messages[logLevel.ToStringSafe()].ShouldContain(expectedMessage); } [Fact] - public void should_log_info_level_with_nuget_prefix_on_all_lines_when_calling_LogInformationSummary() + public void Should_log_info_level_with_nuget_prefix_on_all_lines_when_calling_LogInformationSummary() { const string testMessage = "This should be a error message.\r\nThis is the second line after CRLF line ending.\nThis is the third line after LF line ending."; - var expectedMessage = "[NuGet] This should be a error message.{0}[NuGet] This is the second line after CRLF line ending.{0}[NuGet] This is the third line after LF line ending.".format_with(Environment.NewLine); + var expectedMessage = "[NuGet] This should be a error message.{0}[NuGet] This is the second line after CRLF line ending.{0}[NuGet] This is the third line after LF line ending.".FormatWith(Environment.NewLine); _logger.LogInformationSummary(testMessage); - var loggerName = LogLevel.Info.to_string(); + var loggerName = LogLevel.Info.ToStringSafe(); MockLogger.LoggerNames.Count.ShouldEqual(1); MockLogger.LoggerNames.ShouldContain(typeof(ChocolateyNugetLogger).FullName); MockLogger.Messages.Keys.ShouldContain(loggerName); @@ -175,14 +175,14 @@ public void should_log_info_level_with_nuget_prefix_on_all_lines_when_calling_Lo } [Fact] - public void should_log_info_level_with_nuget_prefix_when_calling_LogInformationSummary() + public void Should_log_info_level_with_nuget_prefix_when_calling_LogInformationSummary() { const string testMessage = "This should be a informational message"; const string expectedMessage = "[NuGet] " + testMessage; _logger.LogInformationSummary(testMessage); - var loggerName = LogLevel.Info.to_string(); + var loggerName = LogLevel.Info.ToStringSafe(); MockLogger.LoggerNames.Count.ShouldEqual(1); MockLogger.LoggerNames.ShouldContain(typeof(ChocolateyNugetLogger).FullName); MockLogger.Messages.Keys.ShouldContain(loggerName); @@ -191,7 +191,7 @@ public void should_log_info_level_with_nuget_prefix_when_calling_LogInformationS [TestCase(NuGetLogLevel.Verbose, "Test verbose message", "[NuGet] Test verbose message")] [TestCase(NuGetLogLevel.Information, "Test informational verbose message", "[NuGet] Test informational verbose message")] - public void should_log_verbose_level_when_calling_Log_with_nuget_log_level(NuGetLogLevel nuGetLogLevel, string testMessage, string expectedMessage) + public void Should_log_verbose_level_when_calling_Log_with_nuget_log_level(NuGetLogLevel nuGetLogLevel, string testMessage, string expectedMessage) { _logger.Log(nuGetLogLevel, testMessage); MockLogger.LoggerNames.Count.ShouldEqual(2); @@ -202,7 +202,7 @@ public void should_log_verbose_level_when_calling_Log_with_nuget_log_level(NuGet [TestCase(NuGetLogLevel.Verbose, "Test verbose message", "[NuGet] Test verbose message")] [TestCase(NuGetLogLevel.Information, "Test informational verbose message", "[NuGet] Test informational verbose message")] - public void should_log_verbose_level_when_calling_Log_with_nuget_log_message(NuGetLogLevel nuGetLogLevel, string testMessage, string expectedMessage) + public void Should_log_verbose_level_when_calling_Log_with_nuget_log_message(NuGetLogLevel nuGetLogLevel, string testMessage, string expectedMessage) { _logger.Log(new LogMessage(nuGetLogLevel, testMessage)); MockLogger.LoggerNames.Count.ShouldEqual(2); @@ -213,7 +213,7 @@ public void should_log_verbose_level_when_calling_Log_with_nuget_log_message(NuG [TestCase(NuGetLogLevel.Verbose, "Test verbose message", "[NuGet] Test verbose message")] [TestCase(NuGetLogLevel.Information, "Test informational verbose message", "[NuGet] Test informational verbose message")] - public async Task should_log_verbose_level_when_calling_LogAsync_with_nuget_log_level(NuGetLogLevel nuGetLogLevel, string testMessage, string expectedMessage) + public async Task Should_log_verbose_level_when_calling_LogAsync_with_nuget_log_level(NuGetLogLevel nuGetLogLevel, string testMessage, string expectedMessage) { await _logger.LogAsync(nuGetLogLevel, testMessage); MockLogger.LoggerNames.Count.ShouldEqual(2); @@ -224,7 +224,7 @@ public async Task should_log_verbose_level_when_calling_LogAsync_with_nuget_log_ [TestCase(NuGetLogLevel.Verbose, "Test verbose message", "[NuGet] Test verbose message")] [TestCase(NuGetLogLevel.Information, "Test informational verbose message", "[NuGet] Test informational verbose message")] - public async Task should_log_verbose_level_when_calling_LogAsync_with_nuget_log_message(NuGetLogLevel nuGetLogLevel, string testMessage, string expectedMessage) + public async Task Should_log_verbose_level_when_calling_LogAsync_with_nuget_log_message(NuGetLogLevel nuGetLogLevel, string testMessage, string expectedMessage) { await _logger.LogAsync(new LogMessage(nuGetLogLevel, testMessage)); MockLogger.LoggerNames.Count.ShouldEqual(2); @@ -234,14 +234,14 @@ public async Task should_log_verbose_level_when_calling_LogAsync_with_nuget_log_ } [Fact] - public void should_log_verbose_level_with_nuget_prefix_on_all_lines_when_calling_LogInformation() + public void Should_log_verbose_level_with_nuget_prefix_on_all_lines_when_calling_LogInformation() { const string testMessage = "This should be a informational verbose message.\r\nThis is the second line after CRLF line ending.\nThis is the third line after LF line ending."; - var expectedMessage = "[NuGet] This should be a informational verbose message.{0}[NuGet] This is the second line after CRLF line ending.{0}[NuGet] This is the third line after LF line ending.".format_with(Environment.NewLine); + var expectedMessage = "[NuGet] This should be a informational verbose message.{0}[NuGet] This is the second line after CRLF line ending.{0}[NuGet] This is the third line after LF line ending.".FormatWith(Environment.NewLine); _logger.LogInformation(testMessage); - var loggerName = LogLevel.Info.to_string(); + var loggerName = LogLevel.Info.ToStringSafe(); MockLogger.LoggerNames.Count.ShouldEqual(2); MockLogger.LoggerNames.ShouldContain("Verbose"); MockLogger.Messages.Keys.ShouldContain(loggerName); @@ -249,14 +249,14 @@ public void should_log_verbose_level_with_nuget_prefix_on_all_lines_when_calling } [Fact] - public void should_log_verbose_level_with_nuget_prefix_on_all_lines_when_calling_LogMinimal() + public void Should_log_verbose_level_with_nuget_prefix_on_all_lines_when_calling_LogMinimal() { const string testMessage = "This should be a error message.\r\nThis is the second line after CRLF line ending.\nThis is the third line after LF line ending."; - var expectedMessage = "[NuGet] This should be a error message.{0}[NuGet] This is the second line after CRLF line ending.{0}[NuGet] This is the third line after LF line ending.".format_with(Environment.NewLine); + var expectedMessage = "[NuGet] This should be a error message.{0}[NuGet] This is the second line after CRLF line ending.{0}[NuGet] This is the third line after LF line ending.".FormatWith(Environment.NewLine); _logger.LogMinimal(testMessage); - var loggerName = LogLevel.Info.to_string(); + var loggerName = LogLevel.Info.ToStringSafe(); MockLogger.LoggerNames.Count.ShouldEqual(2); MockLogger.LoggerNames.ShouldContain("Verbose"); MockLogger.Messages.Keys.ShouldContain(loggerName); @@ -264,14 +264,14 @@ public void should_log_verbose_level_with_nuget_prefix_on_all_lines_when_calling } [Fact] - public void should_log_verbose_level_with_nuget_prefix_on_all_lines_when_calling_LogVerbose() + public void Should_log_verbose_level_with_nuget_prefix_on_all_lines_when_calling_LogVerbose() { const string testMessage = "This should be a verbose message.\r\nThis is the second line after CRLF line ending.\nThis is the third line after LF line ending."; - var expectedMessage = "[NuGet] This should be a verbose message.{0}[NuGet] This is the second line after CRLF line ending.{0}[NuGet] This is the third line after LF line ending.".format_with(Environment.NewLine); + var expectedMessage = "[NuGet] This should be a verbose message.{0}[NuGet] This is the second line after CRLF line ending.{0}[NuGet] This is the third line after LF line ending.".FormatWith(Environment.NewLine); _logger.LogVerbose(testMessage); - var loggerName = LogLevel.Info.to_string(); + var loggerName = LogLevel.Info.ToStringSafe(); MockLogger.LoggerNames.Count.ShouldEqual(2); MockLogger.LoggerNames.ShouldContain("Verbose"); MockLogger.Messages.Keys.ShouldContain(loggerName); @@ -279,14 +279,14 @@ public void should_log_verbose_level_with_nuget_prefix_on_all_lines_when_calling } [Fact] - public void should_log_verbose_level_with_nuget_prefix_when_calling_LogInformation() + public void Should_log_verbose_level_with_nuget_prefix_when_calling_LogInformation() { const string testMessage = "This should be a informational verbose message"; const string expectedMessage = "[NuGet] " + testMessage; _logger.LogInformation(testMessage); - var loggerName = LogLevel.Info.to_string(); + var loggerName = LogLevel.Info.ToStringSafe(); MockLogger.LoggerNames.Count.ShouldEqual(2); MockLogger.LoggerNames.ShouldContain("Verbose"); MockLogger.Messages.Keys.ShouldContain(loggerName); @@ -294,14 +294,14 @@ public void should_log_verbose_level_with_nuget_prefix_when_calling_LogInformati } [Fact] - public void should_log_verbose_level_with_nuget_prefix_when_calling_LogMinimal() + public void Should_log_verbose_level_with_nuget_prefix_when_calling_LogMinimal() { const string testMessage = "This should be a informational message"; const string expectedMessage = "[NuGet] " + testMessage; _logger.LogMinimal(testMessage); - var loggerName = LogLevel.Info.to_string(); + var loggerName = LogLevel.Info.ToStringSafe(); MockLogger.LoggerNames.Count.ShouldEqual(2); MockLogger.LoggerNames.ShouldContain("Verbose"); MockLogger.Messages.Keys.ShouldContain(loggerName); @@ -309,14 +309,14 @@ public void should_log_verbose_level_with_nuget_prefix_when_calling_LogMinimal() } [Fact] - public void should_log_verbose_level_with_nuget_prefix_when_calling_LogVerbose() + public void Should_log_verbose_level_with_nuget_prefix_when_calling_LogVerbose() { const string testMessage = "This should be a verbose message"; const string expectedMessage = "[NuGet] " + testMessage; _logger.LogVerbose(testMessage); - var loggerName = LogLevel.Info.to_string(); + var loggerName = LogLevel.Info.ToStringSafe(); MockLogger.LoggerNames.Count.ShouldEqual(2); MockLogger.LoggerNames.ShouldContain("Verbose"); MockLogger.Messages.Keys.ShouldContain(loggerName); @@ -324,14 +324,14 @@ public void should_log_verbose_level_with_nuget_prefix_when_calling_LogVerbose() } [Fact] - public void should_log_warn_level_with_nuget_prefix_on_all_lines_when_calling_LogWarning() + public void Should_log_warn_level_with_nuget_prefix_on_all_lines_when_calling_LogWarning() { const string testMessage = "This should be a warning message.\r\nThis is the second line after CRLF line ending.\nThis is the third line after LF line ending."; - var expectedMessage = "[NuGet] This should be a warning message.{0}[NuGet] This is the second line after CRLF line ending.{0}[NuGet] This is the third line after LF line ending.".format_with(Environment.NewLine); + var expectedMessage = "[NuGet] This should be a warning message.{0}[NuGet] This is the second line after CRLF line ending.{0}[NuGet] This is the third line after LF line ending.".FormatWith(Environment.NewLine); _logger.LogWarning(testMessage); - var loggerName = LogLevel.Warn.to_string(); + var loggerName = LogLevel.Warn.ToStringSafe(); MockLogger.LoggerNames.Count.ShouldEqual(1); MockLogger.LoggerNames.ShouldContain(typeof(ChocolateyNugetLogger).FullName); MockLogger.Messages.Keys.ShouldContain(loggerName); @@ -339,14 +339,14 @@ public void should_log_warn_level_with_nuget_prefix_on_all_lines_when_calling_Lo } [Fact] - public void should_log_warn_level_with_nuget_prefix_when_calling_LogWarning() + public void Should_log_warn_level_with_nuget_prefix_when_calling_LogWarning() { const string testMessage = "This should be a warning message"; const string expectedMessage = "[NuGet] " + testMessage; _logger.LogWarning(testMessage); - var loggerName = LogLevel.Warn.to_string(); + var loggerName = LogLevel.Warn.ToStringSafe(); MockLogger.LoggerNames.Count.ShouldEqual(1); MockLogger.LoggerNames.ShouldContain(typeof(ChocolateyNugetLogger).FullName); MockLogger.Messages.Keys.ShouldContain(loggerName); @@ -355,10 +355,10 @@ public void should_log_warn_level_with_nuget_prefix_when_calling_LogWarning() [TestCase("")] [TestCase(" ")] - public void should_not_output_whitespace_only_line_in_multiline_logging(string testType) + public void Should_not_output_whitespace_only_line_in_multiline_logging(string testType) { - var testValue = "I will be containing\n{0}\nsome whitespace".format_with(testType); - var expectedValue = "[NuGet] I will be containing{0}[NuGet]{0}[NuGet] some whitespace".format_with(Environment.NewLine); + var testValue = "I will be containing\n{0}\nsome whitespace".FormatWith(testType); + var expectedValue = "[NuGet] I will be containing{0}[NuGet]{0}[NuGet] some whitespace".FormatWith(Environment.NewLine); _logger.Log(NuGetLogLevel.Minimal, testValue); MockLogger.Messages.Keys.ShouldContain("Info"); @@ -368,7 +368,7 @@ public void should_not_output_whitespace_only_line_in_multiline_logging(string t [TestCase(null)] [TestCase("")] [TestCase(" ")] - public void should_only_output_prefix_for_null_or_empty_values(string testValue) + public void Should_only_output_prefix_for_null_or_empty_values(string testValue) { _logger.Log(NuGetLogLevel.Minimal, testValue); @@ -378,9 +378,9 @@ public void should_only_output_prefix_for_null_or_empty_values(string testValue) [TestCase("\n\n\n\n\n")] [TestCase("\r\n\r\n\r\n\r\n\r\n")] - public void should_only_output_prefixes_on_every_line(string testValue) + public void Should_only_output_prefixes_on_every_line(string testValue) { - var expectedValue = "[NuGet]{0}[NuGet]{0}[NuGet]{0}[NuGet]{0}[NuGet]".format_with(Environment.NewLine); + var expectedValue = "[NuGet]{0}[NuGet]{0}[NuGet]{0}[NuGet]{0}[NuGet]".FormatWith(Environment.NewLine); _logger.Log(NuGetLogLevel.Information, testValue); MockLogger.Messages.Keys.ShouldContain("Info"); diff --git a/src/chocolatey.tests/infrastructure.app/nuget/NugetCommonSpecs.cs b/src/chocolatey.tests/infrastructure.app/nuget/NugetCommonSpecs.cs index a2e8143ccd..e1cc4baa8c 100644 --- a/src/chocolatey.tests/infrastructure.app/nuget/NugetCommonSpecs.cs +++ b/src/chocolatey.tests/infrastructure.app/nuget/NugetCommonSpecs.cs @@ -19,6 +19,7 @@ namespace chocolatey.tests.infrastructure.app.nuget using System; using System.Collections.Generic; using System.Linq; + using chocolatey.infrastructure.app; using chocolatey.infrastructure.app.configuration; using chocolatey.infrastructure.app.nuget; using chocolatey.infrastructure.filesystem; @@ -47,7 +48,7 @@ public override void Context() packageDownloader.ResetCalls(); filesystem.ResetCalls(); - filesystem.Setup(f => f.get_full_path(It.IsAny())).Returns((string a) => + filesystem.Setup(f => f.GetFullPath(It.IsAny())).Returns((string a) => { return "C:\\packages\\" + a; }); @@ -59,7 +60,7 @@ public override void Because() } [Fact] - public void should_create_repository_when_source_is_null() + public void Should_create_repository_when_source_is_null() { Context(); configuration.Sources = null; @@ -70,7 +71,7 @@ public void should_create_repository_when_source_is_null() } [Fact] - public void should_parse_http_source() + public void Should_parse_http_source() { Context(); var source = "http://nexus.example.com:8081/repository/choco"; @@ -80,12 +81,12 @@ public void should_parse_http_source() because(); packageRepositories.First().PackageSource.TrySourceAsUri.ShouldNotBeNull(); - packageRepositories.First().PackageSource.SourceUri.to_string().ShouldEqual(source); + packageRepositories.First().PackageSource.SourceUri.ToStringSafe().ShouldEqual(source); packageRepositories.First().PackageSource.IsHttp.ShouldBeTrue(); } [Fact] - public void should_parse_https_source() + public void Should_parse_https_source() { Context(); var source = "https://nexus.example.com/repository/choco"; @@ -95,12 +96,12 @@ public void should_parse_https_source() because(); packageRepositories.First().PackageSource.TrySourceAsUri.ShouldNotBeNull(); - packageRepositories.First().PackageSource.SourceUri.to_string().ShouldEqual(source); + packageRepositories.First().PackageSource.SourceUri.ToStringSafe().ShouldEqual(source); packageRepositories.First().PackageSource.IsHttps.ShouldBeTrue(); } [Fact] - public void should_parse_absolute_path_source() + public void Should_parse_absolute_path_source() { Context(); var source = "C:\\packages"; @@ -109,13 +110,13 @@ public void should_parse_absolute_path_source() because(); packageRepositories.First().PackageSource.TrySourceAsUri.ShouldNotBeNull(); - packageRepositories.First().PackageSource.SourceUri.to_string() + packageRepositories.First().PackageSource.SourceUri.ToStringSafe() .ShouldEqual(("file:///" + source).Replace("\\","/")); packageRepositories.First().PackageSource.IsLocal.ShouldBeTrue(); } [Fact] - public void should_parse_relative_path_source() + public void Should_parse_relative_path_source() { Context(); var source = "choco"; @@ -125,13 +126,13 @@ public void should_parse_relative_path_source() because(); packageRepositories.First().PackageSource.TrySourceAsUri.ShouldNotBeNull(); - packageRepositories.First().PackageSource.SourceUri.to_string() + packageRepositories.First().PackageSource.SourceUri.ToStringSafe() .ShouldEqual(("file:///" + fullsource).Replace("\\", "/")); packageRepositories.First().PackageSource.IsLocal.ShouldBeTrue(); } [Fact] - public void should_parse_dot_relative_path_source() + public void Should_parse_dot_relative_path_source() { Context(); var source = "."; @@ -141,13 +142,13 @@ public void should_parse_dot_relative_path_source() because(); packageRepositories.First().PackageSource.TrySourceAsUri.ShouldNotBeNull(); - packageRepositories.First().PackageSource.SourceUri.to_string() + packageRepositories.First().PackageSource.SourceUri.ToStringSafe() .ShouldEqual(("file:///" + fullsource + "/").Replace("\\", "/")); packageRepositories.First().PackageSource.IsLocal.ShouldBeTrue(); } [Fact] - public void should_parse_unc_source() + public void Should_parse_unc_source() { Context(); var source = "\\\\samba-server\\choco-share"; @@ -156,11 +157,27 @@ public void should_parse_unc_source() because(); packageRepositories.First().PackageSource.TrySourceAsUri.ShouldNotBeNull(); - packageRepositories.First().PackageSource.SourceUri.to_string() + packageRepositories.First().PackageSource.SourceUri.ToStringSafe() .ShouldEqual(("file:" + source).Replace("\\", "/")); packageRepositories.First().PackageSource.IsLocal.ShouldBeTrue(); packageRepositories.First().PackageSource.SourceUri.IsUnc.ShouldBeTrue(); } + + [Fact] + public void Should_set_user_agent_string() + { + Context(); + var source = "https://community.chocolatey.org/api/v2/"; + configuration.Sources = source; + configuration.Information.ChocolateyProductVersion = "vNext"; + + because(); + + // Change this when the NuGet version is updated. + string nugetClientVersion = "6.4.1"; + string expectedUserAgentString = "{0}/{1} via NuGet Client/{2}".FormatWith(ApplicationParameters.UserAgent, configuration.Information.ChocolateyProductVersion, nugetClientVersion); + UserAgent.UserAgentString.ShouldStartWith(expectedUserAgentString); + } } } } diff --git a/src/chocolatey.tests/infrastructure.app/services/AutomaticUninstallerServiceSpecs.cs b/src/chocolatey.tests/infrastructure.app/services/AutomaticUninstallerServiceSpecs.cs index 5df8ad9ef3..382910d97d 100644 --- a/src/chocolatey.tests/infrastructure.app/services/AutomaticUninstallerServiceSpecs.cs +++ b/src/chocolatey.tests/infrastructure.app/services/AutomaticUninstallerServiceSpecs.cs @@ -59,7 +59,7 @@ public abstract class AutomaticUninstallerServiceSpecsBase : TinySpec public override void Context() { - CommandExecutor.initialize_with(new Lazy(() => fileSystem.Object), () => process.Object); + CommandExecutor.InitializeWith(new Lazy(() => fileSystem.Object), () => process.Object); service = new AutomaticUninstallerService(packageInfoService.Object, fileSystem.Object, registryService.Object, commandExecutor.Object); service.WaitForCleanup = false; @@ -81,20 +81,20 @@ public override void Context() InstallerType = installerType.InstallerType, }); packageInformation.RegistrySnapshot = new Registry("123", registryKeys); - packageInfoService.Setup(s => s.get_package_information(package.Object)).Returns(packageInformation); + packageInfoService.Setup(s => s.Get(package.Object)).Returns(packageInformation); packageResults.GetOrAdd("regular", packageResult); - fileSystem.Setup(f => f.directory_exists(registryKeys.FirstOrDefault().InstallLocation)).Returns(true); - registryService.Setup(r => r.installer_value_exists(registryKeys.FirstOrDefault().KeyPath, ApplicationParameters.RegistryValueInstallLocation)).Returns(true); - fileSystem.Setup(f => f.get_full_path(expectedUninstallString)).Returns(expectedUninstallString); - fileSystem.Setup(x => x.file_exists(expectedUninstallString)).Returns(true); + fileSystem.Setup(f => f.DirectoryExists(registryKeys.FirstOrDefault().InstallLocation)).Returns(true); + registryService.Setup(r => r.InstallerKeyExists(registryKeys.FirstOrDefault().KeyPath)).Returns(true); + fileSystem.Setup(f => f.GetFullPath(expectedUninstallString)).Returns(expectedUninstallString); + fileSystem.Setup(x => x.FileExists(expectedUninstallString)).Returns(true); var field = typeof(ApplicationParameters).GetField("AllowPrompts"); field.SetValue(null, false); } } - public class when_autouninstall_feature_is_off : AutomaticUninstallerServiceSpecsBase + public class When_autouninstall_feature_is_off : AutomaticUninstallerServiceSpecsBase { public override void Context() { @@ -104,61 +104,61 @@ public override void Context() public override void Because() { - service.run(packageResult, config); + service.Run(packageResult, config); } [Fact] - public void should_log_why_it_skips_auto_uninstaller() + public void Should_log_why_it_skips_auto_uninstaller() { MockLogger.Verify(l => l.Info(" Skipping auto uninstaller - AutoUninstaller feature is not enabled."), Times.Once); } [Fact] - public void should_not_get_package_information() + public void Should_not_get_package_information() { - packageInfoService.Verify(s => s.get_package_information(It.IsAny()), Times.Never); + packageInfoService.Verify(s => s.Get(It.IsAny()), Times.Never); } [Fact] - public void should_not_call_command_executor() + public void Should_not_call_command_executor() { commandExecutor.Verify( - c => c.execute(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny>(), It.IsAny>(), It.IsAny()), + c => c.Execute(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny>(), It.IsAny>(), It.IsAny()), Times.Never); } } - public class when_an_autoUninstaller_skip_file_exists : AutomaticUninstallerServiceSpecsBase + public class When_an_autoUninstaller_skip_file_exists : AutomaticUninstallerServiceSpecsBase { private string skipFileName = ".skipAutoUninstall"; IEnumerable fileList = new List() {"c:\\.skipAutoUninstall"}; public override void Context() { base.Context(); - fileSystem.Setup(f => f.get_files(It.IsAny(), ".skipAutoUninstall*", SearchOption.AllDirectories)).Returns(fileList); + fileSystem.Setup(f => f.GetFiles(It.IsAny(), ".skipAutoUninstall*", SearchOption.AllDirectories)).Returns(fileList); } public override void Because() { - service.run(packageResult, config); + service.Run(packageResult, config); } [Fact] - public void should_log_why_it_skips_auto_uninstaller() + public void Should_log_why_it_skips_auto_uninstaller() { MockLogger.Verify(l => l.Info(" Skipping auto uninstaller - Package contains a skip file ('" + skipFileName + "')."), Times.Once); } [Fact] - public void should_not_call_command_executor() + public void Should_not_call_command_executor() { commandExecutor.Verify( - c => c.execute(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny>(), It.IsAny>(), It.IsAny()), + c => c.Execute(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny>(), It.IsAny>(), It.IsAny()), Times.Never); } } - public class when_registry_snapshot_is_null : AutomaticUninstallerServiceSpecsBase + public class When_registry_snapshot_is_null : AutomaticUninstallerServiceSpecsBase { public override void Context() { @@ -168,25 +168,25 @@ public override void Context() public override void Because() { - service.run(packageResult, config); + service.Run(packageResult, config); } [Fact] - public void should_log_why_it_skips_auto_uninstaller() + public void Should_log_why_it_skips_auto_uninstaller() { MockLogger.Verify(l => l.Info(" Skipping auto uninstaller - No registry snapshot."), Times.Once); } [Fact] - public void should_not_call_command_executor() + public void Should_not_call_command_executor() { commandExecutor.Verify( - c => c.execute(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny>(), It.IsAny>(), It.IsAny()), + c => c.Execute(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny>(), It.IsAny>(), It.IsAny()), Times.Never); } } - public class when_package_is_missing : AutomaticUninstallerServiceSpecsBase + public class When_package_is_missing : AutomaticUninstallerServiceSpecsBase { public override void Context() { @@ -196,25 +196,25 @@ public override void Context() public override void Because() { - service.run(packageResult, config); + service.Run(packageResult, config); } [Fact] - public void should_log_why_it_skips_auto_uninstaller() + public void Should_log_why_it_skips_auto_uninstaller() { MockLogger.Verify(l => l.Info(" Skipping auto uninstaller - No package in package information."), Times.Once); } [Fact] - public void should_not_call_command_executor() + public void Should_not_call_command_executor() { commandExecutor.Verify( - c => c.execute(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny>(), It.IsAny>(), It.IsAny()), + c => c.Execute(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny>(), It.IsAny>(), It.IsAny()), Times.Never); } } - public class when_registry_keys_are_empty : AutomaticUninstallerServiceSpecsBase + public class When_registry_keys_are_empty : AutomaticUninstallerServiceSpecsBase { public override void Context() { @@ -224,55 +224,55 @@ public override void Context() public override void Because() { - service.run(packageResult, config); + service.Run(packageResult, config); } [Fact] - public void should_log_why_it_skips_auto_uninstaller() + public void Should_log_why_it_skips_auto_uninstaller() { MockLogger.Verify(l => l.Info(" Skipping auto uninstaller - No registry keys in snapshot."), Times.Once); } [Fact] - public void should_not_call_command_executor() + public void Should_not_call_command_executor() { commandExecutor.Verify( - c => c.execute(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny>(), It.IsAny>(), It.IsAny()), + c => c.Execute(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny>(), It.IsAny>(), It.IsAny()), Times.Never); } } - public class when_install_location_does_not_exist : AutomaticUninstallerServiceSpecsBase + public class When_install_location_does_not_exist : AutomaticUninstallerServiceSpecsBase { public override void Context() { base.Context(); fileSystem.ResetCalls(); - fileSystem.Setup(f => f.directory_exists(registryKeys.FirstOrDefault().InstallLocation)).Returns(false); - fileSystem.Setup(x => x.file_exists(expectedUninstallString)).Returns(true); + fileSystem.Setup(f => f.DirectoryExists(registryKeys.FirstOrDefault().InstallLocation)).Returns(false); + fileSystem.Setup(x => x.FileExists(expectedUninstallString)).Returns(true); } public override void Because() { - service.run(packageResult, config); + service.Run(packageResult, config); } [Fact] - public void should_log_why_it_skips_auto_uninstaller() + public void Should_log_why_it_skips_auto_uninstaller() { - MockLogger.Verify(l => l.Info(" Skipping auto uninstaller - '{0}' appears to have been uninstalled already by other means.".format_with(expectedDisplayName)), Times.Once); + MockLogger.Verify(l => l.Info(" Skipping auto uninstaller - '{0}' appears to have been uninstalled already by other means.".FormatWith(expectedDisplayName)), Times.Once); } [Fact] - public void should_not_call_command_executor() + public void Should_not_call_command_executor() { commandExecutor.Verify( - c => c.execute(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny>(), It.IsAny>(), It.IsAny()), + c => c.Execute(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny>(), It.IsAny>(), It.IsAny()), Times.Never); } } - public class when_install_location_is_empty : AutomaticUninstallerServiceSpecsBase + public class When_install_location_is_empty : AutomaticUninstallerServiceSpecsBase { public override void Context() { @@ -289,31 +289,31 @@ public override void Context() KeyPath = @"HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\WinDirStat" }); packageInformation.RegistrySnapshot = new Registry("123", registryKeys); - fileSystem.Setup(x => x.file_exists(expectedUninstallString)).Returns(true); + fileSystem.Setup(x => x.FileExists(expectedUninstallString)).Returns(true); } public override void Because() { - service.run(packageResult, config); + service.Run(packageResult, config); } [Fact] - public void should_call_get_package_information() + public void Should_call_get_package_information() { - packageInfoService.Verify(s => s.get_package_information(It.IsAny()), Times.Once); + packageInfoService.Verify(s => s.Get(It.IsAny()), Times.Once); } [Fact] - public void should_call_command_executor() + public void Should_call_command_executor() { - var args = installerType.build_uninstall_command_arguments().trim_safe(); + var args = installerType.BuildUninstallCommandArguments().TrimSafe(); commandExecutor.Verify( - c => c.execute(expectedUninstallString, args, It.IsAny(), It.IsAny>(), It.IsAny>(), It.IsAny()), + c => c.Execute(expectedUninstallString, args, It.IsAny(), It.IsAny>(), It.IsAny>(), It.IsAny()), Times.Once); } } - public class when_uninstall_string_is_empty : AutomaticUninstallerServiceSpecsBase + public class When_uninstall_string_is_empty : AutomaticUninstallerServiceSpecsBase { public override void Context() { @@ -330,142 +330,142 @@ public override void Context() KeyPath = @"HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\WinDirStat" }); packageInformation.RegistrySnapshot = new Registry("123", registryKeys); - fileSystem.Setup(x => x.file_exists(expectedUninstallString)).Returns(true); + fileSystem.Setup(x => x.FileExists(expectedUninstallString)).Returns(true); } public override void Because() { - service.run(packageResult, config); + service.Run(packageResult, config); } [Fact] - public void should_log_why_it_skips_auto_uninstaller() + public void Should_log_why_it_skips_auto_uninstaller() { - MockLogger.Verify(l => l.Info(" Skipping auto uninstaller - '{0}' does not have an uninstall string.".format_with(expectedDisplayName)), Times.Once); + MockLogger.Verify(l => l.Info(" Skipping auto uninstaller - '{0}' does not have an uninstall string.".FormatWith(expectedDisplayName)), Times.Once); } [Fact] - public void should_not_call_command_executor() + public void Should_not_call_command_executor() { commandExecutor.Verify( - c => c.execute(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny>(), It.IsAny>(), It.IsAny()), + c => c.Execute(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny>(), It.IsAny>(), It.IsAny()), Times.Never); } } - public class when_registry_location_does_not_exist : AutomaticUninstallerServiceSpecsBase + public class When_registry_location_does_not_exist : AutomaticUninstallerServiceSpecsBase { public override void Context() { base.Context(); registryService.ResetCalls(); - registryService.Setup(r => r.installer_value_exists(registryKeys.FirstOrDefault().KeyPath, ApplicationParameters.RegistryValueInstallLocation)).Returns(false); + registryService.Setup(r => r.InstallerKeyExists(registryKeys.FirstOrDefault().KeyPath)).Returns(false); } public override void Because() { - service.run(packageResult, config); + service.Run(packageResult, config); } [Fact] - public void should_log_why_it_skips_auto_uninstaller() + public void Should_log_why_it_skips_auto_uninstaller() { - MockLogger.Verify(l => l.Info(" Skipping auto uninstaller - '{0}' appears to have been uninstalled already by other means.".format_with(expectedDisplayName)), Times.Once); + MockLogger.Verify(l => l.Info(" Skipping auto uninstaller - '{0}' appears to have been uninstalled already by other means.".FormatWith(expectedDisplayName)), Times.Once); } [Fact] - public void should_not_call_command_executor() + public void Should_not_call_command_executor() { commandExecutor.Verify( - c => c.execute(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny>(), It.IsAny>(), It.IsAny()), + c => c.Execute(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny>(), It.IsAny>(), It.IsAny()), Times.Never); } } - public class when_registry_location_and_install_location_both_do_not_exist : AutomaticUninstallerServiceSpecsBase + public class When_registry_location_and_install_location_both_do_not_exist : AutomaticUninstallerServiceSpecsBase { public override void Context() { base.Context(); fileSystem.ResetCalls(); - fileSystem.Setup(f => f.directory_exists(registryKeys.FirstOrDefault().InstallLocation)).Returns(false); - fileSystem.Setup(x => x.file_exists(expectedUninstallString)).Returns(true); + fileSystem.Setup(f => f.DirectoryExists(registryKeys.FirstOrDefault().InstallLocation)).Returns(false); + fileSystem.Setup(x => x.FileExists(expectedUninstallString)).Returns(true); registryService.ResetCalls(); - registryService.Setup(r => r.installer_value_exists(registryKeys.FirstOrDefault().KeyPath, ApplicationParameters.RegistryValueInstallLocation)).Returns(false); + registryService.Setup(r => r.InstallerKeyExists(registryKeys.FirstOrDefault().KeyPath)).Returns(false); } public override void Because() { - service.run(packageResult, config); + service.Run(packageResult, config); } [Fact] - public void should_log_why_it_skips_auto_uninstaller() + public void Should_log_why_it_skips_auto_uninstaller() { - MockLogger.Verify(l => l.Info(" Skipping auto uninstaller - '{0}' appears to have been uninstalled already by other means.".format_with(expectedDisplayName)), Times.Once); + MockLogger.Verify(l => l.Info(" Skipping auto uninstaller - '{0}' appears to have been uninstalled already by other means.".FormatWith(expectedDisplayName)), Times.Once); } [Fact] - public void should_not_call_command_executor() + public void Should_not_call_command_executor() { commandExecutor.Verify( - c => c.execute(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny>(), It.IsAny>(), It.IsAny()), + c => c.Execute(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny>(), It.IsAny>(), It.IsAny()), Times.Never); } } - public class when_uninstall_exe_does_not_exist : AutomaticUninstallerServiceSpecsBase + public class When_uninstall_exe_does_not_exist : AutomaticUninstallerServiceSpecsBase { public override void Context() { base.Context(); fileSystem.ResetCalls(); - fileSystem.Setup(f => f.directory_exists(registryKeys.FirstOrDefault().InstallLocation)).Returns(true); - fileSystem.Setup(f => f.get_full_path(expectedUninstallString)).Returns(expectedUninstallString); - fileSystem.Setup(x => x.file_exists(expectedUninstallString)).Returns(false); + fileSystem.Setup(f => f.DirectoryExists(registryKeys.FirstOrDefault().InstallLocation)).Returns(true); + fileSystem.Setup(f => f.GetFullPath(expectedUninstallString)).Returns(expectedUninstallString); + fileSystem.Setup(x => x.FileExists(expectedUninstallString)).Returns(false); } public override void Because() { - service.run(packageResult, config); + service.Run(packageResult, config); } [Fact] - public void should_log_why_it_skips_auto_uninstaller() + public void Should_log_why_it_skips_auto_uninstaller() { MockLogger.Verify(l => l.Info(" Skipping auto uninstaller - The uninstaller file no longer exists. \"" + expectedUninstallString + "\""), Times.Once); } [Fact] - public void should_not_call_command_executor() + public void Should_not_call_command_executor() { commandExecutor.Verify( - c => c.execute(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny>(), It.IsAny>(), It.IsAny()), + c => c.Execute(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny>(), It.IsAny>(), It.IsAny()), Times.Never); } } - public class when_AutomaticUninstallerService_is_run_normally : AutomaticUninstallerServiceSpecsBase + public class When_AutomaticUninstallerService_is_run_normally : AutomaticUninstallerServiceSpecsBase { public override void Because() { - service.run(packageResult, config); + service.Run(packageResult, config); } [Fact] - public void should_call_get_package_information() + public void Should_call_get_package_information() { - packageInfoService.Verify(s => s.get_package_information(It.IsAny()), Times.Once); + packageInfoService.Verify(s => s.Get(It.IsAny()), Times.Once); } [Fact] - public void should_call_command_executor() + public void Should_call_command_executor() { commandExecutor.Verify( c => - c.execute( + c.Execute( expectedUninstallString, - installerType.build_uninstall_command_arguments().trim_safe(), + installerType.BuildUninstallCommandArguments().TrimSafe(), It.IsAny(), It.IsAny>(), It.IsAny>(), @@ -474,7 +474,7 @@ public void should_call_command_executor() } } - public class when_uninstall_string_is_split_by_quotes : AutomaticUninstallerServiceSpecsBase + public class When_uninstall_string_is_split_by_quotes : AutomaticUninstallerServiceSpecsBase { private readonly string uninstallStringWithQuoteSeparation = @"""C:\Program Files (x86)\WinDirStat\Uninstall.exe"" ""WinDir Stat"""; @@ -497,23 +497,23 @@ public override void Context() public override void Because() { - service.run(packageResult, config); + service.Run(packageResult, config); } [Fact] - public void should_call_get_package_information() + public void Should_call_get_package_information() { - packageInfoService.Verify(s => s.get_package_information(It.IsAny()), Times.Once); + packageInfoService.Verify(s => s.Get(It.IsAny()), Times.Once); } [Fact] - public void should_call_command_executor() + public void Should_call_command_executor() { commandExecutor.Verify( c => - c.execute( + c.Execute( expectedUninstallString, - "\"WinDir Stat\"".trim_safe(), + "\"WinDir Stat\"".TrimSafe(), It.IsAny(), It.IsAny>(), It.IsAny>(), @@ -522,7 +522,7 @@ public void should_call_command_executor() } } - public class when_uninstall_string_has_ampersand_quot : AutomaticUninstallerServiceSpecsBase + public class When_uninstall_string_has_ampersand_quot : AutomaticUninstallerServiceSpecsBase { private readonly string uninstallStringWithAmpersandQuot = @""C:\Program Files (x86)\WinDirStat\Uninstall.exe" /SILENT"; @@ -546,23 +546,23 @@ public override void Context() public override void Because() { MockLogger.LogMessagesToConsole = true; - service.run(packageResult, config); + service.Run(packageResult, config); } [Fact] - public void should_call_get_package_information() + public void Should_call_get_package_information() { - packageInfoService.Verify(s => s.get_package_information(It.IsAny()), Times.Once); + packageInfoService.Verify(s => s.Get(It.IsAny()), Times.Once); } [Fact] - public void should_call_command_executor() + public void Should_call_command_executor() { commandExecutor.Verify( c => - c.execute( + c.Execute( expectedUninstallString, - "/SILENT".trim_safe(), + "/SILENT".TrimSafe(), It.IsAny(), It.IsAny>(), It.IsAny>(), @@ -571,7 +571,7 @@ public void should_call_command_executor() } } - public class when_uninstall_string_has_multiple_file_paths : AutomaticUninstallerServiceSpecsBase + public class When_uninstall_string_has_multiple_file_paths : AutomaticUninstallerServiceSpecsBase { private readonly string uninstallStringPointingToPath = @"C:\Programs\WinDirStat\Uninstall.exe D:\Programs\WinDirStat"; protected readonly string expectedUninstallStringMultiplePaths = @"C:\Programs\WinDirStat\Uninstall.exe"; @@ -591,28 +591,28 @@ public override void Context() InstallerType = installerType.InstallerType, }); packageInformation.RegistrySnapshot = new Registry("123", registryKeys); - fileSystem.Setup(x => x.file_exists(expectedUninstallStringMultiplePaths)).Returns(true); + fileSystem.Setup(x => x.FileExists(expectedUninstallStringMultiplePaths)).Returns(true); } public override void Because() { - service.run(packageResult, config); + service.Run(packageResult, config); } [Fact] - public void should_call_get_package_information() + public void Should_call_get_package_information() { - packageInfoService.Verify(s => s.get_package_information(It.IsAny()), Times.Once); + packageInfoService.Verify(s => s.Get(It.IsAny()), Times.Once); } [Fact] - public void should_call_command_executor() + public void Should_call_command_executor() { commandExecutor.Verify( c => - c.execute( + c.Execute( expectedUninstallStringMultiplePaths, - @"D:\Programs\WinDirStat".trim_safe(), + @"D:\Programs\WinDirStat".TrimSafe(), It.IsAny(), It.IsAny>(), It.IsAny>(), @@ -621,7 +621,7 @@ public void should_call_command_executor() } } - public class when_AutomaticUninstallerService_cannot_determine_silent_install_arguments : AutomaticUninstallerServiceSpecsBase + public class When_AutomaticUninstallerService_cannot_determine_silent_install_arguments : AutomaticUninstallerServiceSpecsBase { public override void Context() { @@ -632,38 +632,38 @@ public override void Context() new RegistryApplicationKey { InstallLocation = @"C:\Program Files (x86)\WinDirStat", - UninstallString = "{0} {1}".format_with(originalUninstallString, "/bob"), + UninstallString = "{0} {1}".FormatWith(originalUninstallString, "/bob"), HasQuietUninstall = false, KeyPath = @"HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\WinDirStat", InstallerType = InstallerType.Unknown, }); packageInformation.RegistrySnapshot = new Registry("123", registryKeys); - fileSystem.Setup(x => x.combine_paths(config.CacheLocation, "chocolatey", It.IsAny(), It.IsAny())).Returns(""); + fileSystem.Setup(x => x.CombinePaths(config.CacheLocation, "chocolatey", It.IsAny(), It.IsAny())).Returns(""); } // under normal circumstances, it prompts so the user can decide, but if -y is passed it will skip public override void Because() { - service.run(packageResult, config); + service.Run(packageResult, config); } [Fact] - public void should_log_why_it_skips_auto_uninstaller() + public void Should_log_why_it_skips_auto_uninstaller() { MockLogger.Verify(l => l.Info(" Skipping auto uninstaller - Installer type was not detected and no silent uninstall key exists."), Times.Once); } [Fact] - public void should_not_call_command_executor() + public void Should_not_call_command_executor() { commandExecutor.Verify( - c => c.execute(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny>(), It.IsAny>(), It.IsAny()), + c => c.Execute(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny>(), It.IsAny>(), It.IsAny()), Times.Never); } } - public class when_AutomaticUninstallerService_is_passed_uninstall_arguments_from_command_line : AutomaticUninstallerServiceSpecsBase + public class When_AutomaticUninstallerService_is_passed_uninstall_arguments_from_command_line : AutomaticUninstallerServiceSpecsBase { IInstaller _installerType = new InnoSetupInstaller(); @@ -688,25 +688,25 @@ public override void Context() public override void Because() { - service.run(packageResult, config); + service.Run(packageResult, config); } [Fact] - public void should_call_get_package_information() + public void Should_call_get_package_information() { - packageInfoService.Verify(s => s.get_package_information(It.IsAny()), Times.Once); + packageInfoService.Verify(s => s.Get(It.IsAny()), Times.Once); } [Fact] - public void should_call_command_executor_appending_passed_arguments() + public void Should_call_command_executor_appending_passed_arguments() { - var uninstallArgs = _installerType.build_uninstall_command_arguments().trim_safe(); + var uninstallArgs = _installerType.BuildUninstallCommandArguments().TrimSafe(); - uninstallArgs += " {0}".format_with(config.InstallArguments); + uninstallArgs += " {0}".FormatWith(config.InstallArguments); commandExecutor.Verify( c => - c.execute( + c.Execute( expectedUninstallString, uninstallArgs, It.IsAny(), @@ -717,7 +717,7 @@ public void should_call_command_executor_appending_passed_arguments() } } - public class when_AutomaticUninstallerService_is_passed_overriding_uninstall_arguments_from_command_line : AutomaticUninstallerServiceSpecsBase + public class When_AutomaticUninstallerService_is_passed_overriding_uninstall_arguments_from_command_line : AutomaticUninstallerServiceSpecsBase { IInstaller _installerType = new InnoSetupInstaller(); @@ -743,21 +743,21 @@ public override void Context() public override void Because() { - service.run(packageResult, config); + service.Run(packageResult, config); } [Fact] - public void should_call_get_package_information() + public void Should_call_get_package_information() { - packageInfoService.Verify(s => s.get_package_information(It.IsAny()), Times.Once); + packageInfoService.Verify(s => s.Get(It.IsAny()), Times.Once); } [Fact] - public void should_call_command_executor_with_only_passed_arguments() + public void Should_call_command_executor_with_only_passed_arguments() { commandExecutor.Verify( c => - c.execute( + c.Execute( expectedUninstallString, config.InstallArguments, It.IsAny(), @@ -768,7 +768,7 @@ public void should_call_command_executor_with_only_passed_arguments() } } - public class when_AutomaticUninstallerService_defines_uninstall_switches : AutomaticUninstallerServiceSpecsBase + public class When_AutomaticUninstallerService_defines_uninstall_switches : AutomaticUninstallerServiceSpecsBase { private Action because; private readonly string registryUninstallArgs = "/bob"; @@ -776,42 +776,42 @@ public class when_AutomaticUninstallerService_defines_uninstall_switches : Autom public override void Because() { - because = () => service.run(packageResult, config); + because = () => service.Run(packageResult, config); } - public void reset() + public void Reset() { Context(); registryKeys.Clear(); commandExecutor.ResetCalls(); } - private void test_installertype(IInstaller installer, bool hasQuietUninstallString) + private void TestInstallerType(IInstaller installer, bool hasQuietUninstallString) { - reset(); + Reset(); registryKeys.Add( new RegistryApplicationKey { InstallLocation = @"C:\Program Files (x86)\WinDirStat", - UninstallString = "{0} {1}".format_with(originalUninstallString, registryUninstallArgs), + UninstallString = "{0} {1}".FormatWith(originalUninstallString, registryUninstallArgs), HasQuietUninstall = hasQuietUninstallString, KeyPath = @"HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\WinDirStat", InstallerType = installer.InstallerType, }); packageInformation.RegistrySnapshot = new Registry("123", registryKeys); - fileSystem.Setup(x => x.combine_paths(config.CacheLocation, "chocolatey", It.IsAny(), It.IsAny())).Returns(logLocation); + fileSystem.Setup(x => x.CombinePaths(config.CacheLocation, "chocolatey", It.IsAny(), It.IsAny())).Returns(logLocation); because(); - var installerTypeArgs = installer.build_uninstall_command_arguments().trim_safe().Replace(InstallTokens.PACKAGE_LOCATION, logLocation); + var installerTypeArgs = installer.BuildUninstallCommandArguments().TrimSafe().Replace(InstallTokens.PackageLocation, logLocation); - var uninstallArgs = !hasQuietUninstallString ? registryUninstallArgs.trim_safe() + " " + installerTypeArgs : registryUninstallArgs.trim_safe(); + var uninstallArgs = !hasQuietUninstallString ? registryUninstallArgs.TrimSafe() + " " + installerTypeArgs : registryUninstallArgs.TrimSafe(); commandExecutor.Verify( c => - c.execute( + c.Execute( expectedUninstallString, - uninstallArgs.trim_safe(), + uninstallArgs.TrimSafe(), It.IsAny(), It.IsAny>(), It.IsAny>(), @@ -820,63 +820,63 @@ private void test_installertype(IInstaller installer, bool hasQuietUninstallStri } //[Fact] - //public void should_use_CustomInstaller_uninstall_args_when_installtype_is_unknown_and_has_quiet_uninstall_is_false() + //public void Should_use_CustomInstaller_uninstall_args_when_installtype_is_unknown_and_has_quiet_uninstall_is_false() //{ // test_installertype(new CustomInstaller(), hasQuietUninstallString: false); //} [Fact] - public void should_use_registry_uninstall_args_when_installtype_is_unknown_and_has_quiet_uninstall_is_true() + public void Should_use_registry_uninstall_args_when_installtype_is_unknown_and_has_quiet_uninstall_is_true() { - test_installertype(new CustomInstaller(), hasQuietUninstallString: true); + TestInstallerType(new CustomInstaller(), hasQuietUninstallString: true); } [Fact] - public void should_use_MsiInstaller_uninstall_args_when_installtype_is_msi_and_has_quiet_uninstall_is_false() + public void Should_use_MsiInstaller_uninstall_args_when_installtype_is_msi_and_has_quiet_uninstall_is_false() { - test_installertype(new MsiInstaller(), hasQuietUninstallString: false); + TestInstallerType(new MsiInstaller(), hasQuietUninstallString: false); } [Fact] - public void should_use_registry_uninstall_args_when_installtype_is_msi_and_has_quiet_uninstall_is_true() + public void Should_use_registry_uninstall_args_when_installtype_is_msi_and_has_quiet_uninstall_is_true() { - test_installertype(new MsiInstaller(), hasQuietUninstallString: true); + TestInstallerType(new MsiInstaller(), hasQuietUninstallString: true); } [Fact] - public void should_use_InnoSetupInstaller_uninstall_args_when_installtype_is_innosetup_and_has_quiet_uninstall_is_false() + public void Should_use_InnoSetupInstaller_uninstall_args_when_installtype_is_innosetup_and_has_quiet_uninstall_is_false() { - test_installertype(new InnoSetupInstaller(), hasQuietUninstallString: false); + TestInstallerType(new InnoSetupInstaller(), hasQuietUninstallString: false); } [Fact] - public void should_use_registry_uninstall_args_when_installtype_is_innosetup_and_has_quiet_uninstall_is_true() + public void Should_use_registry_uninstall_args_when_installtype_is_innosetup_and_has_quiet_uninstall_is_true() { - test_installertype(new InnoSetupInstaller(), hasQuietUninstallString: true); + TestInstallerType(new InnoSetupInstaller(), hasQuietUninstallString: true); } [Fact] - public void should_use_InstallShieldInstaller_uninstall_args_when_installtype_is_installshield_and_has_quiet_uninstall_is_false() + public void Should_use_InstallShieldInstaller_uninstall_args_when_installtype_is_installshield_and_has_quiet_uninstall_is_false() { - test_installertype(new InstallShieldInstaller(), hasQuietUninstallString: false); + TestInstallerType(new InstallShieldInstaller(), hasQuietUninstallString: false); } [Fact] - public void should_use_registry_uninstall_args_when_installtype_is_installshield_and_has_quiet_uninstall_is_true() + public void Should_use_registry_uninstall_args_when_installtype_is_installshield_and_has_quiet_uninstall_is_true() { - test_installertype(new InstallShieldInstaller(), hasQuietUninstallString: true); + TestInstallerType(new InstallShieldInstaller(), hasQuietUninstallString: true); } [Fact] - public void should_use_NsisInstaller_uninstall_args_when_installtype_is_nsis_and_has_quiet_uninstall_is_false() + public void Should_use_NsisInstaller_uninstall_args_when_installtype_is_nsis_and_has_quiet_uninstall_is_false() { - test_installertype(new NsisInstaller(), hasQuietUninstallString: false); + TestInstallerType(new NsisInstaller(), hasQuietUninstallString: false); } [Fact] - public void should_use_registry_uninstall_args_when_installtype_is_nsis_and_has_quiet_uninstall_is_true() + public void Should_use_registry_uninstall_args_when_installtype_is_nsis_and_has_quiet_uninstall_is_true() { - test_installertype(new NsisInstaller(), hasQuietUninstallString: true); + TestInstallerType(new NsisInstaller(), hasQuietUninstallString: true); } } } diff --git a/src/chocolatey.tests/infrastructure.app/services/ChocolateyConfigSettingsServiceSpecs.cs b/src/chocolatey.tests/infrastructure.app/services/ChocolateyConfigSettingsServiceSpecs.cs index ac7f21e30d..9635a373a5 100644 --- a/src/chocolatey.tests/infrastructure.app/services/ChocolateyConfigSettingsServiceSpecs.cs +++ b/src/chocolatey.tests/infrastructure.app/services/ChocolateyConfigSettingsServiceSpecs.cs @@ -24,7 +24,7 @@ public override void Context() } } - public class when_ChocolateyConfigSettingsService_disables_available_feature : ChocolateyConfigSettingsServiceSpecsBase + public class When_ChocolateyConfigSettingsService_disables_available_feature : ChocolateyConfigSettingsServiceSpecsBase { public override void Because() { @@ -36,14 +36,14 @@ public override void Because() } }; - Service.feature_disable(config); + Service.DisableFeature(config); } public override void Context() { base.Context(); - XmlService.Setup(x => x.deserialize(ApplicationParameters.GlobalConfigFileLocation)) + XmlService.Setup(x => x.Deserialize(ApplicationParameters.GlobalConfigFileLocation)) .Returns(new ConfigFileSettings { Features = new HashSet() @@ -59,28 +59,28 @@ public override void Context() } [Fact] - public void should_not_report_feature_being_unsupported() + public void Should_not_report_feature_being_unsupported() { - MockLogger.Messages["Warn"].ShouldNotContain("Feature '{0}' is not supported. Any change have no effect on running Chocolatey.".format_with(ApplicationParameters.Features.ChecksumFiles)); + MockLogger.Messages["Warn"].ShouldNotContain("Feature '{0}' is not supported. Any change have no effect on running Chocolatey.".FormatWith(ApplicationParameters.Features.ChecksumFiles)); } [Fact] - public void should_report_feature_being_disabled() + public void Should_report_feature_being_disabled() { MockLogger.Messages.Keys.ShouldContain("Warn"); - MockLogger.Messages["Warn"].ShouldContain("Disabled {0}".format_with(ApplicationParameters.Features.ChecksumFiles)); + MockLogger.Messages["Warn"].ShouldContain("Disabled {0}".FormatWith(ApplicationParameters.Features.ChecksumFiles)); } [Fact] - public void should_serialize_feature_correctly() + public void Should_serialize_feature_correctly() { - XmlService.Verify(x => x.serialize(It.Is(config => + XmlService.Verify(x => x.Serialize(It.Is(config => config.Features.Any(f => f.Name == ApplicationParameters.Features.ChecksumFiles && f.SetExplicitly && !f.Enabled)), ApplicationParameters.GlobalConfigFileLocation), Times.Once); } } - public class when_ChocolateyConfigSettingsService_disables_unknown_feature : ChocolateyConfigSettingsServiceSpecsBase + public class When_ChocolateyConfigSettingsService_disables_unknown_feature : ChocolateyConfigSettingsServiceSpecsBase { public override void Because() { @@ -90,7 +90,7 @@ public override void Context() { base.Context(); - XmlService.Setup(x => x.deserialize(ApplicationParameters.GlobalConfigFileLocation)) + XmlService.Setup(x => x.Deserialize(ApplicationParameters.GlobalConfigFileLocation)) .Returns(new ConfigFileSettings { Features = new HashSet() @@ -100,13 +100,13 @@ public override void Context() } [Fact] - public void should_not_contain_any_warnings() + public void Should_not_contain_any_warnings() { MockLogger.Messages.Keys.ShouldNotContain("Warn"); } [Fact] - public void should_throw_exception_on_unknown_feature() + public void Should_throw_exception_on_unknown_feature() { Assert.ThrowsDelegate action = () => { @@ -118,7 +118,7 @@ public void should_throw_exception_on_unknown_feature() } }; - Service.feature_disable(config); + Service.DisableFeature(config); }; Assert.Throws(action) @@ -126,9 +126,9 @@ public void should_throw_exception_on_unknown_feature() } } - public class when_ChocolateyConfigSettingsService_disables_unsupported_feature : ChocolateyConfigSettingsServiceSpecsBase + public class When_ChocolateyConfigSettingsService_disables_unsupported_feature : ChocolateyConfigSettingsServiceSpecsBase { - private const string FEATURE_NAME = "scriptsCheckLastExitCode"; + private const string FeatureName = "scriptsCheckLastExitCode"; public override void Because() { @@ -138,14 +138,14 @@ public override void Context() { base.Context(); - XmlService.Setup(x => x.deserialize(ApplicationParameters.GlobalConfigFileLocation)) + XmlService.Setup(x => x.Deserialize(ApplicationParameters.GlobalConfigFileLocation)) .Returns(new ConfigFileSettings { Features = new HashSet() { new ConfigFileFeatureSetting() { - Name = FEATURE_NAME + Name = FeatureName } } }); @@ -154,7 +154,7 @@ public override void Context() } [Fact] - public void should_throw_exception_on_unsupported_feature() + public void Should_throw_exception_on_unsupported_feature() { Assert.Throws(() => { @@ -162,16 +162,16 @@ public void should_throw_exception_on_unsupported_feature() { FeatureCommand = new FeatureCommandConfiguration() { - Name = FEATURE_NAME + Name = FeatureName } }; - Service.feature_disable(config); - }).Message.ShouldEqual("Feature '{0}' is not supported.".format_with(FEATURE_NAME)); + Service.DisableFeature(config); + }).Message.ShouldEqual("Feature '{0}' is not supported.".FormatWith(FeatureName)); } } - public class when_ChocolateyConfigSettingsService_enables_available_feature : ChocolateyConfigSettingsServiceSpecsBase + public class When_ChocolateyConfigSettingsService_enables_available_feature : ChocolateyConfigSettingsServiceSpecsBase { public override void Because() { @@ -183,14 +183,14 @@ public override void Because() } }; - Service.feature_enable(config); + Service.EnableFeature(config); } public override void Context() { base.Context(); - XmlService.Setup(x => x.deserialize(ApplicationParameters.GlobalConfigFileLocation)) + XmlService.Setup(x => x.Deserialize(ApplicationParameters.GlobalConfigFileLocation)) .Returns(new ConfigFileSettings { Features = new HashSet() @@ -206,28 +206,28 @@ public override void Context() } [Fact] - public void should_not_report_feature_being_unsupported() + public void Should_not_report_feature_being_unsupported() { - MockLogger.Messages["Warn"].ShouldNotContain("Feature '{0}' is not supported. Any change have no effect on running Chocolatey.".format_with(ApplicationParameters.Features.ChecksumFiles)); + MockLogger.Messages["Warn"].ShouldNotContain("Feature '{0}' is not supported. Any change have no effect on running Chocolatey.".FormatWith(ApplicationParameters.Features.ChecksumFiles)); } [Fact] - public void should_report_feature_being_enabled() + public void Should_report_feature_being_enabled() { MockLogger.Messages.Keys.ShouldContain("Warn"); - MockLogger.Messages["Warn"].ShouldContain("Enabled {0}".format_with(ApplicationParameters.Features.ChecksumFiles)); + MockLogger.Messages["Warn"].ShouldContain("Enabled {0}".FormatWith(ApplicationParameters.Features.ChecksumFiles)); } [Fact] - public void should_serialize_feature_correctly() + public void Should_serialize_feature_correctly() { - XmlService.Verify(x => x.serialize(It.Is(config => + XmlService.Verify(x => x.Serialize(It.Is(config => config.Features.Any(f => f.Name == ApplicationParameters.Features.ChecksumFiles && f.SetExplicitly && f.Enabled)), ApplicationParameters.GlobalConfigFileLocation), Times.Once); } } - public class when_ChocolateyConfigSettingsService_enables_unknown_feature : ChocolateyConfigSettingsServiceSpecsBase + public class When_ChocolateyConfigSettingsService_enables_unknown_feature : ChocolateyConfigSettingsServiceSpecsBase { public override void Because() { @@ -237,7 +237,7 @@ public override void Context() { base.Context(); - XmlService.Setup(x => x.deserialize(ApplicationParameters.GlobalConfigFileLocation)) + XmlService.Setup(x => x.Deserialize(ApplicationParameters.GlobalConfigFileLocation)) .Returns(new ConfigFileSettings { Features = new HashSet() @@ -247,13 +247,13 @@ public override void Context() } [Fact] - public void should_not_contain_any_warnings() + public void Should_not_contain_any_warnings() { MockLogger.Messages.Keys.ShouldNotContain("Warn"); } [Fact] - public void should_throw_exception_on_unknown_feature() + public void Should_throw_exception_on_unknown_feature() { Assert.ThrowsDelegate action = () => { @@ -265,7 +265,7 @@ public void should_throw_exception_on_unknown_feature() } }; - Service.feature_enable(config); + Service.EnableFeature(config); }; Assert.Throws(action) @@ -273,9 +273,9 @@ public void should_throw_exception_on_unknown_feature() } } - public class when_ChocolateyConfigSettingsService_enables_unsupported_feature : ChocolateyConfigSettingsServiceSpecsBase + public class When_ChocolateyConfigSettingsService_enables_unsupported_feature : ChocolateyConfigSettingsServiceSpecsBase { - private const string FEATURE_NAME = "scriptsCheckLastExitCode"; + private const string FeatureName = "scriptsCheckLastExitCode"; public override void Because() { @@ -285,14 +285,14 @@ public override void Context() { base.Context(); - XmlService.Setup(x => x.deserialize(ApplicationParameters.GlobalConfigFileLocation)) + XmlService.Setup(x => x.Deserialize(ApplicationParameters.GlobalConfigFileLocation)) .Returns(new ConfigFileSettings { Features = new HashSet() { new ConfigFileFeatureSetting() { - Name = FEATURE_NAME + Name = FeatureName } } }); @@ -301,7 +301,7 @@ public override void Context() } [Fact] - public void should_throw_exception_on_unsupported_feature() + public void Should_throw_exception_on_unsupported_feature() { Assert.Throws(() => { @@ -309,13 +309,264 @@ public void should_throw_exception_on_unsupported_feature() { FeatureCommand = new FeatureCommandConfiguration() { - Name = FEATURE_NAME + Name = FeatureName } }; - Service.feature_enable(config); - }).Message.ShouldEqual("Feature '{0}' is not supported.".format_with(FEATURE_NAME)); + Service.EnableFeature(config); + }).Message.ShouldEqual("Feature '{0}' is not supported.".FormatWith(FeatureName)); + } + } + + public class When_ChocolateyConfigSettingsService_list_feature : ChocolateyConfigSettingsServiceSpecsBase + { + public override void Because() + { + var config = new ChocolateyConfiguration() + { + RegularOutput = true + }; + + Service.ListFeatures(config); + } + + public override void Context() + { + base.Context(); + + XmlService.Setup(x => x.Deserialize(ApplicationParameters.GlobalConfigFileLocation)) + .Returns(new ConfigFileSettings + { + Features = new HashSet() + { + new ConfigFileFeatureSetting() + { + Name = ApplicationParameters.Features.VirusCheck, + }, + new ConfigFileFeatureSetting() + { + Name = ApplicationParameters.Features.AllowEmptyChecksums + } + } + }); + + Service = new ChocolateyConfigSettingsService(XmlService.Object); + } + + [Fact] + public void Should_output_features_in_alphabetical_order() + { + MockLogger.Messages.Keys.ShouldContain("Info"); + + var infoMessages = MockLogger.Messages["Info"]; + infoMessages.Count.ShouldEqual(2); + infoMessages[0].ShouldContain("allowEmptyChecksums"); + infoMessages[1].ShouldContain("virusCheck"); + } + } + + public class When_ChocolateyConfigSettingsService_list_config : ChocolateyConfigSettingsServiceSpecsBase + { + public override void Because() + { + var config = new ChocolateyConfiguration() + { + RegularOutput = true + }; + + Service.ListConfig(config); + } + + public override void Context() + { + base.Context(); + + XmlService.Setup(x => x.Deserialize(ApplicationParameters.GlobalConfigFileLocation)) + .Returns(new ConfigFileSettings + { + ConfigSettings = new HashSet() + { + new ConfigFileConfigSetting() + { + Key = ApplicationParameters.ConfigSettings.WebRequestTimeoutSeconds + }, + new ConfigFileConfigSetting() + { + Key = ApplicationParameters.ConfigSettings.CacheLocation + } + } + }); + + Service = new ChocolateyConfigSettingsService(XmlService.Object); + } + + [Fact] + public void Should_output_config_in_alphabetical_order() + { + MockLogger.Messages.Keys.ShouldContain("Info"); + + var infoMessages = MockLogger.Messages["Info"]; + infoMessages.Count.ShouldEqual(2); + infoMessages[0].ShouldContain("cacheLocation"); + infoMessages[1].ShouldContain("webRequestTimeoutSeconds"); + } + } + + public class When_ChocolateyConfigSettingsService_list_source : ChocolateyConfigSettingsServiceSpecsBase + { + public override void Because() + { + var config = new ChocolateyConfiguration() + { + RegularOutput = true + }; + + Service.ListSources(config); + } + + public override void Context() + { + base.Context(); + + XmlService.Setup(x => x.Deserialize(ApplicationParameters.GlobalConfigFileLocation)) + .Returns(new ConfigFileSettings + { + Sources = new HashSet() + { + new ConfigFileSourceSetting() + { + Id = "beta" + }, + new ConfigFileSourceSetting() + { + Id = "alpha" + } + } + }); + + Service = new ChocolateyConfigSettingsService(XmlService.Object); + } + + [Fact] + public void Should_output_sources_in_alphabetical_order() + { + MockLogger.Messages.Keys.ShouldContain("Info"); + + var infoMessages = MockLogger.Messages["Info"]; + infoMessages.Count.ShouldEqual(2); + infoMessages[0].ShouldContain("alpha"); + infoMessages[1].ShouldContain("beta"); + } + } + + public class When_ChocolateyConfigSettingsService_get_unknown_feature : ChocolateyConfigSettingsServiceSpecsBase + { + private Exception _error = null; + private Action _because; + + public override void Because() + { + var config = new ChocolateyConfiguration() + { + RegularOutput = true, + FeatureCommand = new FeatureCommandConfiguration() + { + Name = "unknown", + Command = chocolatey.infrastructure.app.domain.FeatureCommandType.Get + } + }; + + _because = () => Service.GetFeature(config); + } + + public override void Context() + { + base.Context(); + + XmlService.Setup(x => x.Deserialize(ApplicationParameters.GlobalConfigFileLocation)) + .Returns(new ConfigFileSettings + { + Features = new HashSet() + { + new ConfigFileFeatureSetting() + { + Name = ApplicationParameters.Features.VirusCheck, + Enabled = true + }, + new ConfigFileFeatureSetting() + { + Name = ApplicationParameters.Features.ChecksumFiles, + Enabled = false + } + } + }); + + Service = new ChocolateyConfigSettingsService(XmlService.Object); + } + + [Fact] + public void Should_throw_when_unknown_feature_name() + { + try + { + _because(); + } + catch (Exception ex) + { + _error = ex; + } + + _error.ShouldNotBeNull(); + _error.ShouldBeType(); + _error.Message.ShouldContain("No feature value by the name 'unknown'"); + } + } + + public class When_ChocolateyConfigSettingsService_get_existing_feature : ChocolateyConfigSettingsServiceSpecsBase + { + public override void Because() + { + var config = new ChocolateyConfiguration() + { + RegularOutput = true, + FeatureCommand = new FeatureCommandConfiguration() + { + Name = ApplicationParameters.Features.VirusCheck, + Command = chocolatey.infrastructure.app.domain.FeatureCommandType.Get + } + }; + + Service.GetFeature(config); + } + + public override void Context() + { + base.Context(); + + XmlService.Setup(x => x.Deserialize(ApplicationParameters.GlobalConfigFileLocation)) + .Returns(new ConfigFileSettings + { + Features = new HashSet() + { + new ConfigFileFeatureSetting() + { + Name = ApplicationParameters.Features.VirusCheck, + Enabled = true + } + } + }); + + Service = new ChocolateyConfigSettingsService(XmlService.Object); + } + + [Fact] + public void Should_return_feature_status() + { + MockLogger.Messages.Keys.ShouldContain("Info"); + var infoMessages = MockLogger.Messages["Info"]; + infoMessages.Count.ShouldEqual(1); + infoMessages[0].ShouldContain("Enabled"); } } } -} \ No newline at end of file +} diff --git a/src/chocolatey.tests/infrastructure.app/services/ChocolateyPackageServiceSpecs.cs b/src/chocolatey.tests/infrastructure.app/services/ChocolateyPackageServiceSpecs.cs index 09e1637315..80e7e02b79 100644 --- a/src/chocolatey.tests/infrastructure.app/services/ChocolateyPackageServiceSpecs.cs +++ b/src/chocolatey.tests/infrastructure.app/services/ChocolateyPackageServiceSpecs.cs @@ -33,6 +33,7 @@ namespace chocolatey.tests.infrastructure.app.services { using System.IO; + using chocolatey.infrastructure.app.registration; using NuGet.Packaging; public class ChocolateyPackageServiceSpecs @@ -42,7 +43,6 @@ public abstract class ChocolateyPackageServiceSpecsBase : TinySpec protected ChocolateyPackageService Service; protected Mock NugetService = new Mock(); protected Mock PowershellService = new Mock(); - protected List SourceRunners = new List(); protected Mock ShimGenerationService = new Mock(); protected Mock FileSystem = new Mock(); protected Mock RegistryService = new Mock(); @@ -51,6 +51,7 @@ public abstract class ChocolateyPackageServiceSpecsBase : TinySpec protected Mock AutomaticUninstallerService = new Mock(); protected Mock XmlService = new Mock(); protected Mock ConfigTransformService = new Mock(); + protected Mock ContainerResolver = new Mock(); protected ChocolateyConfiguration Configuration = new ChocolateyConfiguration(); @@ -66,15 +67,27 @@ public override void Context() AutomaticUninstallerService.ResetCalls(); XmlService.ResetCalls(); ConfigTransformService.ResetCalls(); - Service = new ChocolateyPackageService(NugetService.Object, PowershellService.Object, SourceRunners, ShimGenerationService.Object, FileSystem.Object, RegistryService.Object, ChocolateyPackageInformationService.Object, FilesService.Object, AutomaticUninstallerService.Object, XmlService.Object, ConfigTransformService.Object); + ContainerResolver.ResetCalls(); + Service = new ChocolateyPackageService( + NugetService.Object, + PowershellService.Object, + ShimGenerationService.Object, + FileSystem.Object, + RegistryService.Object, + ChocolateyPackageInformationService.Object, + FilesService.Object, + AutomaticUninstallerService.Object, + XmlService.Object, + ConfigTransformService.Object, + ContainerResolver.Object); } } - public class when_ChocolateyPackageService_install_from_package_config_with_custom_sources : ChocolateyPackageServiceSpecsBase + public class When_ChocolateyPackageService_install_from_package_config_with_custom_sources : ChocolateyPackageServiceSpecsBase { - protected Mock FeaturesRunner = new Mock(); - protected Mock NormalRunner = new Mock(); - private ConcurrentDictionary result; + protected Mock WindowsFeaturesRunner = new Mock(); + + private ConcurrentDictionary _result; public override void Context() { @@ -83,23 +96,23 @@ public override void Context() Configuration.PackageNames = @"C:\test\packages.config"; Configuration.Sources = @"C:\test"; - NormalRunner.Setup(r => r.SourceType).Returns(SourceTypes.NORMAL); - FeaturesRunner.Setup(r => r.SourceType).Returns(SourceTypes.WINDOWS_FEATURES); + WindowsFeaturesRunner.Setup(r => r.SourceType).Returns(SourceTypes.WindowsFeatures); var package = new Mock(); var expectedResult = new ConcurrentDictionary(); expectedResult.TryAdd("test-feature", new PackageResult(package.Object, "windowsfeatures", null)); - FeaturesRunner.Setup(r => r.install_run(It.IsAny(), It.IsAny>(), It.IsAny>())) + WindowsFeaturesRunner.Setup(r => r.Install(It.IsAny(), It.IsAny>())) + .Returns(expectedResult); + NugetService.Setup(n => n.Install(It.IsAny(), It.IsAny>(), It.IsAny>())) .Returns(expectedResult); - NormalRunner.Setup(r => r.install_run(It.IsAny(), It.IsAny>(), It.IsAny>())) - .Returns(new ConcurrentDictionary()); - SourceRunners.AddRange(new[] { NormalRunner.Object, FeaturesRunner.Object }); - FileSystem.Setup(f => f.get_full_path(Configuration.PackageNames)).Returns(Configuration.PackageNames); - FileSystem.Setup(f => f.file_exists(Configuration.PackageNames)).Returns(true); + ContainerResolver.Setup(c => c.ResolveAll()).Returns(new[] { WindowsFeaturesRunner.Object }); + + FileSystem.Setup(f => f.GetFullPath(Configuration.PackageNames)).Returns(Configuration.PackageNames); + FileSystem.Setup(f => f.FileExists(Configuration.PackageNames)).Returns(true); - XmlService.Setup(x => x.deserialize(Configuration.PackageNames)) + XmlService.Setup(x => x.Deserialize(Configuration.PackageNames)) .Returns(new PackagesConfigFileSettings { Packages = new HashSet @@ -115,43 +128,45 @@ public override void Context() public override void Because() { - result = Service.install_run(Configuration); + _result = Service.Install(Configuration); } [Test] - public void should_return_package_that_should_have_been_installed() + public void Should_return_package_that_should_have_been_installed() { - result.Keys.ShouldContain("test-feature"); + _result.Keys.ShouldContain("test-feature"); } [Test] - public void should_have_called_runner_for_windows_features_source() + public void Should_have_called_runner_for_windows_features_source() { - FeaturesRunner.Verify(r => r.install_run(It.Is(c => c.PackageNames == "test-feature"), It.IsAny>(), It.IsAny>()), Times.Once); + WindowsFeaturesRunner + .Verify(r => r.Install(It.Is(c => c.PackageNames == "test-feature"), It.IsAny>()), Times.Once); } [Test] - public void should_not_have_called_runner_for_windows_features_source_with_other_package_names() + public void Should_not_have_called_runner_for_windows_features_source_with_other_package_names() { - FeaturesRunner.Verify(r => r.install_run(It.Is(c => c.PackageNames != "test-feature"), It.IsAny>(), It.IsAny>()), Times.Never); + WindowsFeaturesRunner.Verify(r => r.Install(It.Is(c => c.PackageNames != "test-feature"), It.IsAny>()), Times.Never); + WindowsFeaturesRunner.Verify(r => r.Install(It.IsAny(), It.IsAny>(), It.IsAny>()), Times.Never); } [Test] - public void should_not_have_called_normal_source_runner_for_non_empty_packages() + public void Should_not_have_called_normal_source_runner_for_non_empty_packages() { // The normal source runners will be called with an argument - NormalRunner.Verify(r => r.install_run(It.Is(c => c.PackageNames != string.Empty), It.IsAny>(), It.IsAny>()), Times.Never); + NugetService.Verify(r => r.Install(It.Is(c => c.PackageNames != string.Empty), It.IsAny>(), It.IsAny>()), Times.Never); } } - public class when_ChocolateyPackageService_tries_to_install_nupkg_file : ChocolateyPackageServiceSpecsBase + public class When_ChocolateyPackageService_tries_to_install_nupkg_file : ChocolateyPackageServiceSpecsBase { protected Action Action; public override void Context() { base.Context(); - Action = () => Service.install_noop(Configuration); + Action = () => Service.InstallDryRun(Configuration); Configuration.CommandName = "install"; } @@ -160,138 +175,138 @@ public override void Because() } [Fact] - public void should_throw_exception_when_full_path_is_passed_to_install_run() + public void Should_throw_exception_when_full_path_is_passed_to_install_run() { var directory = Path.Combine(Path.GetPathRoot(Environment.CurrentDirectory), "testing"); Configuration.PackageNames = Path.Combine( directory, "my-package.nupkg"); - FileSystem.Setup(f => f.get_file_name_without_extension(Configuration.PackageNames)) + FileSystem.Setup(f => f.GetFilenameWithoutExtension(Configuration.PackageNames)) .Returns("my-package"); - FileSystem.Setup(f => f.get_file_name(Configuration.PackageNames)) + FileSystem.Setup(f => f.GetFileName(Configuration.PackageNames)) .Returns("my-package.nupkg"); - FileSystem.Setup(f => f.get_directory_name(Configuration.PackageNames)) + FileSystem.Setup(f => f.GetDirectoryName(Configuration.PackageNames)) .Returns(directory); - var ex = try_run(Action); - var message = get_expected_local_value(directory, "my-package"); + var ex = TryRun(Action); + var message = GetExpectedLocalValue(directory, "my-package"); ex.Message.ShouldEqual(message); } [Fact] - public void should_throw_exception_when_full_file_prefixed_path_is_passed_to_install_run() + public void Should_throw_exception_when_full_file_prefixed_path_is_passed_to_install_run() { var directory = Path.Combine(Path.GetPathRoot(Environment.CurrentDirectory), "testing"); var filePath = Path.Combine(directory, "my-package.nupkg"); Configuration.PackageNames = new Uri(filePath).AbsoluteUri; - FileSystem.Setup(f => f.get_file_name_without_extension(filePath)) + FileSystem.Setup(f => f.GetFilenameWithoutExtension(filePath)) .Returns("my-package"); - FileSystem.Setup(f => f.get_file_name(filePath)) + FileSystem.Setup(f => f.GetFileName(filePath)) .Returns("my-package.nupkg"); - FileSystem.Setup(f => f.get_directory_name(filePath)) + FileSystem.Setup(f => f.GetDirectoryName(filePath)) .Returns(directory); - var ex = try_run(Action); - var message = get_expected_local_value(directory, "my-package"); + var ex = TryRun(Action); + var message = GetExpectedLocalValue(directory, "my-package"); ex.Message.ShouldEqual(message); } [Fact, Categories.Unc] - public void should_throw_exception_when_UNC_path_is_passed_to_install_run() + public void Should_throw_exception_when_UNC_path_is_passed_to_install_run() { var directory = UNCHelper.convert_local_folder_path_to_ip_based_unc_path(Path.Combine(Path.GetPathRoot(Environment.CurrentDirectory), "testing")); var filePath = Path.Combine(directory, "my-package.nupkg"); Configuration.PackageNames = new Uri(filePath).AbsoluteUri; - FileSystem.Setup(f => f.get_file_name_without_extension(filePath)) + FileSystem.Setup(f => f.GetFilenameWithoutExtension(filePath)) .Returns("my-package"); - FileSystem.Setup(f => f.get_file_name(filePath)) + FileSystem.Setup(f => f.GetFileName(filePath)) .Returns("my-package.nupkg"); - FileSystem.Setup(f => f.get_directory_name(filePath)) + FileSystem.Setup(f => f.GetDirectoryName(filePath)) .Returns(directory); - var ex = try_run(Action); - var message = get_expected_unc_value(directory, "my-package"); + var ex = TryRun(Action); + var message = GetExpectedUncValue(directory, "my-package"); ex.Message.ShouldEqual(message); } [Fact] - public void should_throw_exception_when_remote_path_is_passed_to_install_run() + public void Should_throw_exception_when_remote_path_is_passed_to_install_run() { Configuration.PackageNames = "https://test.com/repository/awesome-package.nupkg"; - var ex = try_run(Action); + var ex = TryRun(Action); ex.Message.ShouldEqual("Package name cannot point directly to a local, or remote file. Please use the --source argument and point it to a local file directory, UNC directory path or a NuGet feed instead."); } [Fact] - public void should_throw_exception_when_passed_in_path_to_nupkg_is_relative_and_it_exists() + public void Should_throw_exception_when_passed_in_path_to_nupkg_is_relative_and_it_exists() { Configuration.PackageNames = "test.1.5.0.nupkg"; var directory = Environment.CurrentDirectory; var fullPath = Path.Combine(directory, Configuration.PackageNames); - FileSystem.Setup(f => f.file_exists(Configuration.PackageNames)).Returns(true); - FileSystem.Setup(f => f.get_full_path(Configuration.PackageNames)).Returns(fullPath); - FileSystem.Setup(f => f.get_directory_name(fullPath)).Returns(directory); - FileSystem.Setup(f => f.get_file_name(fullPath)).Returns("test.1.5.0.nupkg"); - FileSystem.Setup(f => f.get_file_name_without_extension(fullPath)).Returns("test.1.5.0"); - - var ex = try_run(Action); - var expectedMessage = get_expected_local_value(Environment.CurrentDirectory, "test", "1.5.0"); + FileSystem.Setup(f => f.FileExists(Configuration.PackageNames)).Returns(true); + FileSystem.Setup(f => f.GetFullPath(Configuration.PackageNames)).Returns(fullPath); + FileSystem.Setup(f => f.GetDirectoryName(fullPath)).Returns(directory); + FileSystem.Setup(f => f.GetFileName(fullPath)).Returns("test.1.5.0.nupkg"); + FileSystem.Setup(f => f.GetFilenameWithoutExtension(fullPath)).Returns("test.1.5.0"); + + var ex = TryRun(Action); + var expectedMessage = GetExpectedLocalValue(Environment.CurrentDirectory, "test", "1.5.0"); ex.Message.ShouldEqual(expectedMessage); } [Fact] - public void should_throw_exception_with_expected_message_when_installing_pre_release_nupkg() + public void Should_throw_exception_with_expected_message_when_installing_pre_release_nupkg() { Configuration.PackageNames = "test.2.0-alpha.nupkg"; var directory = Environment.CurrentDirectory; var fullPath = Path.Combine(directory, Configuration.PackageNames); - FileSystem.Setup(f => f.file_exists(Configuration.PackageNames)).Returns(true); - FileSystem.Setup(f => f.get_full_path(Configuration.PackageNames)).Returns(fullPath); - FileSystem.Setup(f => f.get_directory_name(fullPath)).Returns(directory); - FileSystem.Setup(f => f.get_file_name(fullPath)).Returns(Configuration.PackageNames); - FileSystem.Setup(f => f.get_file_name_without_extension(fullPath)).Returns("test.2.0-alpha"); - - var ex = try_run(Action); - var expectedMessage = get_expected_local_value(Environment.CurrentDirectory, "test", "2.0.0-alpha", prerelease: true); + FileSystem.Setup(f => f.FileExists(Configuration.PackageNames)).Returns(true); + FileSystem.Setup(f => f.GetFullPath(Configuration.PackageNames)).Returns(fullPath); + FileSystem.Setup(f => f.GetDirectoryName(fullPath)).Returns(directory); + FileSystem.Setup(f => f.GetFileName(fullPath)).Returns(Configuration.PackageNames); + FileSystem.Setup(f => f.GetFilenameWithoutExtension(fullPath)).Returns("test.2.0-alpha"); + + var ex = TryRun(Action); + var expectedMessage = GetExpectedLocalValue(Environment.CurrentDirectory, "test", "2.0.0-alpha", prerelease: true); ex.Message.ShouldEqual(expectedMessage); } [Fact] - public void should_throw_exception_with_expected_message_when_installing_nupkg_and_directory_path_is_null() + public void Should_throw_exception_with_expected_message_when_installing_nupkg_and_directory_path_is_null() { Configuration.PackageNames = "test.2.0.nupkg"; - FileSystem.Setup(f => f.file_exists(Configuration.PackageNames)).Returns(true); - FileSystem.Setup(f => f.get_full_path(Configuration.PackageNames)).Returns(Configuration.PackageNames); - FileSystem.Setup(f => f.get_file_name(Configuration.PackageNames)).Returns(Configuration.PackageNames); - FileSystem.Setup(f => f.get_file_name_without_extension(Configuration.PackageNames)).Returns("test.2.0"); + FileSystem.Setup(f => f.FileExists(Configuration.PackageNames)).Returns(true); + FileSystem.Setup(f => f.GetFullPath(Configuration.PackageNames)).Returns(Configuration.PackageNames); + FileSystem.Setup(f => f.GetFileName(Configuration.PackageNames)).Returns(Configuration.PackageNames); + FileSystem.Setup(f => f.GetFilenameWithoutExtension(Configuration.PackageNames)).Returns("test.2.0"); - var ex = try_run(Action); - var expectedMessage = get_expected_local_value(string.Empty, "test", "2.0.0", prerelease: false); + var ex = TryRun(Action); + var expectedMessage = GetExpectedLocalValue(string.Empty, "test", "2.0.0", prerelease: false); ex.Message.ShouldEqual(expectedMessage); } [Fact] - public void should_throw_exception_when_passed_in_path_to_nupkg_is_relative_and_it_does_not_exist() + public void Should_throw_exception_when_passed_in_path_to_nupkg_is_relative_and_it_does_not_exist() { Configuration.PackageNames = "package.nupkg"; - var ex = try_run(Action); + var ex = TryRun(Action); ex.Message.ShouldEqual("Package name cannot point directly to a local, or remote file. Please use the --source argument and point it to a local file directory, UNC directory path or a NuGet feed instead."); } [Fact] - public void should_throw_exception_when_nuspec_file_is_passed_as_package_name() + public void Should_throw_exception_when_nuspec_file_is_passed_as_package_name() { Configuration.PackageNames = "test-package.nuspec"; - var ex = try_run(Action); + var ex = TryRun(Action); ex.Message.ShouldEqual("Package name cannot point directly to a package manifest file. Please create a package by running 'choco pack' on the .nuspec file first."); } - private string get_expected_unc_value(string path, string name, string version = null, bool prerelease = false) + private string GetExpectedUncValue(string path, string name, string version = null, bool prerelease = false) { var sb = new StringBuilder("Package name cannot be a path to a file on a UNC location.") .AppendLine() @@ -320,7 +335,7 @@ private string get_expected_unc_value(string path, string name, string version = return sb.AppendLine().ToString(); } - private string get_expected_local_value(string path, string name, string version = null, bool prerelease = false) + private string GetExpectedLocalValue(string path, string name, string version = null, bool prerelease = false) { var sb = new StringBuilder("Package name cannot be a path to a file on a remote, or local file system.") .AppendLine() @@ -349,7 +364,7 @@ private string get_expected_local_value(string path, string name, string version return sb.AppendLine().ToString(); } - private static Exception try_run(Action action) + private static Exception TryRun(Action action) { try { @@ -364,31 +379,31 @@ private static Exception try_run(Action action) } } - public class when_ChocolateyPackageService_tries_to_install_noop_nupkg_file : when_ChocolateyPackageService_tries_to_install_nupkg_file + public class When_ChocolateyPackageService_tries_to_install_noop_nupkg_file : When_ChocolateyPackageService_tries_to_install_nupkg_file { public override void Context() { base.Context(); - Action = () => Service.install_noop(Configuration); + Action = () => Service.InstallDryRun(Configuration); } } - public class when_ChocolateyPackageService_tries_to_upgrade_nupkg_file : when_ChocolateyPackageService_tries_to_install_nupkg_file + public class When_ChocolateyPackageService_tries_to_upgrade_nupkg_file : When_ChocolateyPackageService_tries_to_install_nupkg_file { public override void Context() { base.Context(); - Action = () => Service.upgrade_run(Configuration); + Action = () => Service.Upgrade(Configuration); Configuration.CommandName = "upgrade"; } } - public class when_ChocolateyPackageService_tries_to_upgrade_noop_nupkg_file : when_ChocolateyPackageService_tries_to_install_nupkg_file + public class When_ChocolateyPackageService_tries_to_upgrade_noop_nupkg_file : When_ChocolateyPackageService_tries_to_install_nupkg_file { public override void Context() { base.Context(); - Action = () => Service.upgrade_noop(Configuration); + Action = () => Service.UpgradeDryRun(Configuration); Configuration.CommandName = "upgrade"; } } diff --git a/src/chocolatey.tests/infrastructure.app/services/FilesServiceSpecs.cs b/src/chocolatey.tests/infrastructure.app/services/FilesServiceSpecs.cs index b6032c8bc2..2c8bc54c9c 100644 --- a/src/chocolatey.tests/infrastructure.app/services/FilesServiceSpecs.cs +++ b/src/chocolatey.tests/infrastructure.app/services/FilesServiceSpecs.cs @@ -48,71 +48,71 @@ public override void Context() } } - public class when_FilesService_reads_from_files : FilesServiceSpecsBase + public class When_FilesService_reads_from_files : FilesServiceSpecsBase { private Func because; public override void Because() { - because = () => Service.read_from_file("fake path"); + because = () => Service.ReadPackageSnapshot("fake path"); } [Fact] - public void should_deserialize_when_file_exists() + public void Should_deserialize_when_file_exists() { Context(); - FileSystem.Setup(x => x.file_exists(It.IsAny())).Returns(true); - XmlService.Setup(x => x.deserialize(It.IsAny())).Returns(new PackageFiles()); + FileSystem.Setup(x => x.FileExists(It.IsAny())).Returns(true); + XmlService.Setup(x => x.Deserialize(It.IsAny())).Returns(new PackageFiles()); because(); } [Fact] - public void should_not_deserialize_if_file_does_not_exist() + public void Should_not_deserialize_if_file_does_not_exist() { Context(); - FileSystem.Setup(x => x.file_exists(It.IsAny())).Returns(false); + FileSystem.Setup(x => x.FileExists(It.IsAny())).Returns(false); because(); - XmlService.Verify(x => x.deserialize(It.IsAny()), Times.Never); + XmlService.Verify(x => x.Deserialize(It.IsAny()), Times.Never); } } - public class when_FilesService_saves_files : FilesServiceSpecsBase + public class When_FilesService_saves_files : FilesServiceSpecsBase { private Action because; private PackageFiles files; public override void Because() { - because = () => Service.save_to_file(files, "fake path"); + because = () => Service.SavePackageSnapshot(files, "fake path"); } [Fact] - public void should_save_if_the_snapshot_is_not_null() + public void Should_save_if_the_snapshot_is_not_null() { Context(); files = new PackageFiles(); because(); - XmlService.Verify(x => x.serialize(files, It.IsAny()), Times.Once()); + XmlService.Verify(x => x.Serialize(files, It.IsAny()), Times.Once()); } [Fact] - public void should_not_do_anything_if_the_snapshot_is_null() + public void Should_not_do_anything_if_the_snapshot_is_null() { Context(); files = null; because(); - XmlService.Verify(x => x.serialize(files, It.IsAny()), Times.Never); + XmlService.Verify(x => x.Serialize(files, It.IsAny()), Times.Never); } } - public class when_FilesService_captures_files_and_install_directory_reports_choco_install_location : FilesServiceSpecsBase + public class When_FilesService_captures_files_and_install_directory_reports_choco_install_location : FilesServiceSpecsBase { private PackageFiles result; private PackageResult packageResult; @@ -126,29 +126,29 @@ public override void Context() public override void Because() { - result = Service.capture_package_files(packageResult, config); + result = Service.CaptureSnapshot(packageResult, config); } [Fact] - public void should_not_call_get_files() + public void Should_not_call_get_files() { - FileSystem.Verify(x => x.get_files(It.IsAny(), It.IsAny(), SearchOption.AllDirectories), Times.Never); + FileSystem.Verify(x => x.GetFiles(It.IsAny(), It.IsAny(), SearchOption.AllDirectories), Times.Never); } [Fact] - public void should_return_a_warning_if_the_install_directory_matches_choco_install_location() + public void Should_return_a_warning_if_the_install_directory_matches_choco_install_location() { packageResult.Warning.ShouldBeTrue(); } [Fact] - public void should_return_null() + public void Should_return_null() { result.ShouldBeNull(); } } - public class when_FilesService_captures_files_and_install_directory_reports_packages_location : FilesServiceSpecsBase + public class When_FilesService_captures_files_and_install_directory_reports_packages_location : FilesServiceSpecsBase { private PackageFiles result; private PackageResult packageResult; @@ -162,29 +162,29 @@ public override void Context() public override void Because() { - result = Service.capture_package_files(packageResult, config); + result = Service.CaptureSnapshot(packageResult, config); } [Fact] - public void should_not_call_get_files() + public void Should_not_call_get_files() { - FileSystem.Verify(x => x.get_files(It.IsAny(), It.IsAny(), SearchOption.AllDirectories), Times.Never); + FileSystem.Verify(x => x.GetFiles(It.IsAny(), It.IsAny(), SearchOption.AllDirectories), Times.Never); } [Fact] - public void should_return_a_warning_if_the_install_directory_matches_choco_install_location() + public void Should_return_a_warning_if_the_install_directory_matches_choco_install_location() { packageResult.Warning.ShouldBeTrue(); } [Fact] - public void should_return_null() + public void Should_return_null() { result.ShouldBeNull(); } } - public class when_FilesService_captures_files_and_package_result_is_null : FilesServiceSpecsBase + public class When_FilesService_captures_files_and_package_result_is_null : FilesServiceSpecsBase { private PackageFiles result; private PackageResult packageResult; @@ -198,29 +198,29 @@ public override void Context() public override void Because() { - result = Service.capture_package_files(packageResult, config); + result = Service.CaptureSnapshot(packageResult, config); } [Fact] - public void should_not_call_get_files() + public void Should_not_call_get_files() { - FileSystem.Verify(x => x.get_files(It.IsAny(), It.IsAny(), SearchOption.AllDirectories), Times.Never); + FileSystem.Verify(x => x.GetFiles(It.IsAny(), It.IsAny(), SearchOption.AllDirectories), Times.Never); } [Fact] - public void should_return_a_non_null_object() + public void Should_return_a_non_null_object() { result.ShouldNotBeNull(); } [Fact] - public void should_return_empty_package_files() + public void Should_return_empty_package_files() { result.Files.ShouldBeEmpty(); } } - public class when_FilesService_captures_files_happy_path : FilesServiceSpecsBase + public class When_FilesService_captures_files_happy_path : FilesServiceSpecsBase { private PackageFiles result; private PackageResult packageResult; @@ -237,37 +237,37 @@ public override void Context() base.Context(); packageResult = new PackageResult("bob", "1.2.3", installDirectory); - FileSystem.Setup(x => x.get_files(ApplicationParameters.PackagesLocation + "\\bob", It.IsAny(), SearchOption.AllDirectories)).Returns(files); - HashProvider.Setup(x => x.hash_file(It.IsAny())).Returns("yes"); + FileSystem.Setup(x => x.GetFiles(ApplicationParameters.PackagesLocation + "\\bob", It.IsAny(), SearchOption.AllDirectories)).Returns(files); + HashProvider.Setup(x => x.ComputeFileHash(It.IsAny())).Returns("yes"); } public override void Because() { - result = Service.capture_package_files(packageResult, config); + result = Service.CaptureSnapshot(packageResult, config); } [Fact] - public void should_return_a_PackageFiles_object() + public void Should_return_a_PackageFiles_object() { result.ShouldNotBeNull(); } [Fact] - public void should_contain_package_files() + public void Should_contain_package_files() { result.Files.ShouldNotBeEmpty(); } [Fact] - public void should_contain_the_correct_number_of_package_files() + public void Should_contain_the_correct_number_of_package_files() { result.Files.Count.ShouldEqual(files.Count); } [Fact] - public void should_call_hash_provider_for_each_file() + public void Should_call_hash_provider_for_each_file() { - HashProvider.Verify(x => x.hash_file(It.IsAny()), Times.Exactly(files.Count)); + HashProvider.Verify(x => x.ComputeFileHash(It.IsAny()), Times.Exactly(files.Count)); } } } diff --git a/src/chocolatey.tests/infrastructure.app/services/NugetServiceSpecs.cs b/src/chocolatey.tests/infrastructure.app/services/NugetServiceSpecs.cs index f98487bcef..2450e67b70 100644 --- a/src/chocolatey.tests/infrastructure.app/services/NugetServiceSpecs.cs +++ b/src/chocolatey.tests/infrastructure.app/services/NugetServiceSpecs.cs @@ -55,7 +55,7 @@ public override void Context() } } - public class when_NugetService_backs_up_changed_files : NugetServiceSpecsBase + public class When_NugetService_backs_up_changed_files : NugetServiceSpecsBase { private Action because; private ChocolateyPackageInformation packageInfo; @@ -70,16 +70,16 @@ public override void Context() packageInfo = new ChocolateyPackageInformation(package.Object); packageInfo.FilesSnapshot = new PackageFiles(); packageFiles = new PackageFiles(); - fileSystem.Setup(x => x.directory_exists(It.IsAny())).Returns(true); + fileSystem.Setup(x => x.DirectoryExists(It.IsAny())).Returns(true); } public override void Because() { - because = () => service.backup_changed_files(filePath, config, packageInfo); + because = () => service.BackupChangedFiles(filePath, config, packageInfo); } [Fact] - public void should_ignore_an_unchanged_file() + public void Should_ignore_an_unchanged_file() { Context(); @@ -95,16 +95,16 @@ public void should_ignore_an_unchanged_file() { filePath }; - fileSystem.Setup(x => x.get_files(It.IsAny(), It.IsAny(), SearchOption.AllDirectories)).Returns(fileSystemFiles); - filesService.Setup(x => x.capture_package_files(It.IsAny(), config)).Returns(packageFiles); + fileSystem.Setup(x => x.GetFiles(It.IsAny(), It.IsAny(), SearchOption.AllDirectories)).Returns(fileSystemFiles); + filesService.Setup(x => x.CaptureSnapshot(It.IsAny(), config)).Returns(packageFiles); because(); - fileSystem.Verify(x => x.copy_file(It.IsAny(), It.IsAny(), It.IsAny()), Times.Never); + fileSystem.Verify(x => x.CopyFile(It.IsAny(), It.IsAny(), It.IsAny()), Times.Never); } [Fact] - public void should_backup_a_changed_file() + public void Should_backup_a_changed_file() { Context(); @@ -126,21 +126,21 @@ public void should_backup_a_changed_file() { filePath }; - fileSystem.Setup(x => x.get_files(It.IsAny(), It.IsAny(), SearchOption.AllDirectories)).Returns(fileSystemFiles); + fileSystem.Setup(x => x.GetFiles(It.IsAny(), It.IsAny(), SearchOption.AllDirectories)).Returns(fileSystemFiles); var updatedPackageFiles = new PackageFiles(); updatedPackageFiles.Files = new List { packageFileWithUpdatedChecksum }; - filesService.Setup(x => x.capture_package_files(It.IsAny(), config)).Returns(updatedPackageFiles); + filesService.Setup(x => x.CaptureSnapshot(It.IsAny(), config)).Returns(updatedPackageFiles); because(); - fileSystem.Verify(x => x.copy_file(It.IsAny(), It.IsAny(), It.IsAny()), Times.Once); + fileSystem.Verify(x => x.CopyFile(It.IsAny(), It.IsAny(), It.IsAny()), Times.Once); } } - public class when_NugetService_removes_installation_files_on_uninstall : NugetServiceSpecsBase + public class When_NugetService_removes_installation_files_on_uninstall : NugetServiceSpecsBase { private Action because; private ChocolateyPackageInformation packageInfo; @@ -154,20 +154,20 @@ public override void Context() packageInfo = new ChocolateyPackageInformation(package.Object); packageInfo.FilesSnapshot = new PackageFiles(); packageFiles = new List(); - fileSystem.Setup(x => x.directory_exists(It.IsAny())).Returns(true); + fileSystem.Setup(x => x.DirectoryExists(It.IsAny())).Returns(true); } public override void Because() { - because = () => service.remove_installation_files(package.Object, packageInfo); + because = () => service.RemoveInstallationFiles(package.Object, packageInfo); } [Fact] - public void should_do_nothing_if_the_directory_no_longer_exists() + public void Should_do_nothing_if_the_directory_no_longer_exists() { Context(); fileSystem.ResetCalls(); - fileSystem.Setup(x => x.directory_exists(It.IsAny())).Returns(false); + fileSystem.Setup(x => x.DirectoryExists(It.IsAny())).Returns(false); var packageFile = new PackageFile { @@ -181,17 +181,17 @@ public void should_do_nothing_if_the_directory_no_longer_exists() { filePath }; - fileSystem.Setup(x => x.get_files(It.IsAny(), It.IsAny(), SearchOption.AllDirectories)).Returns(fileSystemFiles); - filesService.Setup(x => x.get_package_file(It.IsAny())).Returns(packageFile); + fileSystem.Setup(x => x.GetFiles(It.IsAny(), It.IsAny(), SearchOption.AllDirectories)).Returns(fileSystemFiles); + filesService.Setup(x => x.GetPackageFile(It.IsAny())).Returns(packageFile); because(); - filesService.Verify(x => x.get_package_file(It.IsAny()), Times.Never); - fileSystem.Verify(x => x.delete_file(filePath), Times.Never); + filesService.Verify(x => x.GetPackageFile(It.IsAny()), Times.Never); + fileSystem.Verify(x => x.DeleteFile(filePath), Times.Never); } [Fact] - public void should_remove_an_unchanged_file() + public void Should_remove_an_unchanged_file() { Context(); @@ -207,17 +207,17 @@ public void should_remove_an_unchanged_file() { filePath }; - fileSystem.Setup(x => x.get_files(It.IsAny(), It.IsAny(), SearchOption.AllDirectories)).Returns(fileSystemFiles); - filesService.Setup(x => x.get_package_file(It.IsAny())).Returns(packageFile); - fileSystem.Setup(x => x.file_exists(filePath)).Returns(true); + fileSystem.Setup(x => x.GetFiles(It.IsAny(), It.IsAny(), SearchOption.AllDirectories)).Returns(fileSystemFiles); + filesService.Setup(x => x.GetPackageFile(It.IsAny())).Returns(packageFile); + fileSystem.Setup(x => x.FileExists(filePath)).Returns(true); because(); - fileSystem.Verify(x => x.delete_file(filePath)); + fileSystem.Verify(x => x.DeleteFile(filePath)); } [Fact] - public void should_not_delete_a_changed_file() + public void Should_not_delete_a_changed_file() { Context(); @@ -238,17 +238,17 @@ public void should_not_delete_a_changed_file() { filePath }; - fileSystem.Setup(x => x.get_files(It.IsAny(), It.IsAny(), SearchOption.AllDirectories)).Returns(fileSystemFiles); - filesService.Setup(x => x.get_package_file(It.IsAny())).Returns(packageFileWithUpdatedChecksum); - fileSystem.Setup(x => x.file_exists(filePath)).Returns(true); + fileSystem.Setup(x => x.GetFiles(It.IsAny(), It.IsAny(), SearchOption.AllDirectories)).Returns(fileSystemFiles); + filesService.Setup(x => x.GetPackageFile(It.IsAny())).Returns(packageFileWithUpdatedChecksum); + fileSystem.Setup(x => x.FileExists(filePath)).Returns(true); because(); - fileSystem.Verify(x => x.delete_file(filePath), Times.Never); + fileSystem.Verify(x => x.DeleteFile(filePath), Times.Never); } [Fact] - public void should_not_delete_an_unfound_file() + public void Should_not_delete_an_unfound_file() { Context(); @@ -271,17 +271,17 @@ public void should_not_delete_an_unfound_file() filePath }; - fileSystem.Setup(x => x.get_files(It.IsAny(), It.IsAny(), SearchOption.AllDirectories)).Returns(fileSystemFiles); - filesService.Setup(x => x.get_package_file(It.IsAny())).Returns(packageFileNotInOriginal); - fileSystem.Setup(x => x.file_exists(filePath)).Returns(false); + fileSystem.Setup(x => x.GetFiles(It.IsAny(), It.IsAny(), SearchOption.AllDirectories)).Returns(fileSystemFiles); + filesService.Setup(x => x.GetPackageFile(It.IsAny())).Returns(packageFileNotInOriginal); + fileSystem.Setup(x => x.FileExists(filePath)).Returns(false); because(); - fileSystem.Verify(x => x.delete_file(filePath), Times.Never); + fileSystem.Verify(x => x.DeleteFile(filePath), Times.Never); } } - public class when_NugetService_pack_noop : NugetServiceSpecsBase + public class When_NugetService_pack_noop : NugetServiceSpecsBase { private Action because; private readonly ChocolateyConfiguration config = new ChocolateyConfiguration(); @@ -289,21 +289,21 @@ public class when_NugetService_pack_noop : NugetServiceSpecsBase public override void Context() { base.Context(); - fileSystem.Setup(x => x.get_current_directory()).Returns("c:\\projects\\chocolatey"); + fileSystem.Setup(x => x.GetCurrentDirectory()).Returns("c:\\projects\\chocolatey"); } public override void Because() { - because = () => service.pack_noop(config); + because = () => service.PackDryRun(config); } public override void AfterEachSpec() { - MockLogger.reset(); + MockLogger.Reset(); } [Fact] - public void generated_package_should_be_in_current_directory() + public void Generated_package_should_be_in_current_directory() { Context(); @@ -315,7 +315,7 @@ public void generated_package_should_be_in_current_directory() } [Fact] - public void generated_package_should_be_in_specified_directory() + public void Generated_package_should_be_in_specified_directory() { Context(); diff --git a/src/chocolatey.tests/infrastructure.app/services/RegistryServiceSpecs.cs b/src/chocolatey.tests/infrastructure.app/services/RegistryServiceSpecs.cs index 1868a3c700..2f43bec8e6 100644 --- a/src/chocolatey.tests/infrastructure.app/services/RegistryServiceSpecs.cs +++ b/src/chocolatey.tests/infrastructure.app/services/RegistryServiceSpecs.cs @@ -35,21 +35,21 @@ public abstract class RegistryServiceSpecsBase : TinySpec public override void Context() { - reset(); + Reset(); Service = new RegistryService(XmlService.Object, FileSystem.Object); } - protected void reset() + protected void Reset() { FileSystem.ResetCalls(); XmlService.ResetCalls(); - MockLogger.reset(); + MockLogger.Reset(); } } [WindowsOnly] [Platform(Exclude = "Mono")] - public class when_RegistryService_get_installer_keys_is_called : RegistryServiceSpecsBase + public class When_RegistryService_get_installer_keys_is_called : RegistryServiceSpecsBase { private Registry _result; @@ -60,11 +60,11 @@ public override void Context() public override void Because() { - _result = Service.get_installer_keys(); + _result = Service.GetInstallerKeys(); } [Fact] - public void should_not_be_null() + public void Should_not_be_null() { _result.ShouldNotBeNull(); } @@ -72,7 +72,7 @@ public void should_not_be_null() [WindowsOnly] [Platform(Exclude = "Mono")] - public class when_RegistryService_get_key_is_called_for_a_value_that_exists : RegistryServiceSpecsBase + public class When_RegistryService_get_key_is_called_for_a_value_that_exists : RegistryServiceSpecsBase { private RegistryKey _result; private readonly RegistryHive _hive = RegistryHive.CurrentUser; @@ -85,37 +85,37 @@ public override void Context() public override void Because() { - _result = Service.get_key(_hive, _subkeyPath); + _result = Service.GetKey(_hive, _subkeyPath); } [Fact] - public void should_return_a_non_null_value() + public void Should_return_a_non_null_value() { _result.ShouldNotBeNull(); } [Fact] - public void should_return_a_value_of_type_RegistryKey() + public void Should_return_a_value_of_type_RegistryKey() { _result.ShouldBeType(); } [Fact] - public void should_contain_keys() + public void Should_contain_keys() { _result.GetSubKeyNames().ShouldNotBeEmpty(); } [Fact] - public void should_contain_values() + public void Should_contain_values() { - Service.get_key(_hive, "Environment").GetValueNames().ShouldNotBeEmpty(); + Service.GetKey(_hive, "Environment").GetValueNames().ShouldNotBeEmpty(); } } [WindowsOnly] [Platform(Exclude = "Mono")] - public class when_RegistryService_get_key_is_called_for_a_value_that_does_not_exist : RegistryServiceSpecsBase + public class When_RegistryService_get_key_is_called_for_a_value_that_does_not_exist : RegistryServiceSpecsBase { private RegistryKey _result; private readonly RegistryHive _hive = RegistryHive.CurrentUser; @@ -128,17 +128,17 @@ public override void Context() public override void Because() { - _result = Service.get_key(_hive, _subkeyPath); + _result = Service.GetKey(_hive, _subkeyPath); } [Fact] - public void should_not_error() + public void Should_not_error() { //nothing to see here } [Fact] - public void should_return_null_key() + public void Should_return_null_key() { _result.ShouldBeNull(); } diff --git a/src/chocolatey.tests/infrastructure.app/services/RulesServiceSpecs.cs b/src/chocolatey.tests/infrastructure.app/services/RulesServiceSpecs.cs new file mode 100644 index 0000000000..e9b4cd544c --- /dev/null +++ b/src/chocolatey.tests/infrastructure.app/services/RulesServiceSpecs.cs @@ -0,0 +1,73 @@ +// Copyright © 2017 - 2021 Chocolatey Software, Inc +// Copyright © 2011 - 2017 RealDimensions Software, LLC +// +// 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. + +namespace chocolatey.tests.infrastructure.app.services +{ + using System; + using System.Collections.Generic; + using System.Linq; + using System.Reflection; + using chocolatey.infrastructure.app.rules; + using chocolatey.infrastructure.app.services; + using chocolatey.infrastructure.rules; + using chocolatey.infrastructure.services; + using Should; + + public class RulesServiceSpecs : TinySpec + { + private RuleService _service; + private IReadOnlyList _detectedRules; + // We can't reference RuleIdentifiers directly as it's Internal. We should either get these from there, or do something different... + private const string EmptyRequiredElement = "CHCR0001"; + private const string InvalidTypeElement = "CHCU0001"; + private const string MissingElementOnRequiringLicenseAcceptance = "CHCR0002"; + private const string UnsupportedElementUsed = "CHCU0002"; + + public override void Context() + { + Type[] availableRules = typeof(IRuleService).Assembly + .GetTypes() + .Where(t => !t.IsInterface && !t.IsAbstract && typeof(IMetadataRule).IsAssignableFrom(t)) + .ToArray(); + var rules = new List(); + + foreach (Type availableRule in availableRules) + { + // We do first here as we want it to fail if the constructor can't be found. + var rule = availableRule.GetConstructors().First().Invoke(new object[] { }); + rules.Add((MetadataRuleBase)rule); + } + + _service = new RuleService(rules.ToArray()); + } + + public override void Because() + { + _detectedRules = _service.GetAllAvailableRules(); + } + + [Fact] + public void GetsRulesFromService() + { + _detectedRules.Count().ShouldEqual(4); + IEnumerable ruleIds = _detectedRules.Select(t => t.Id); + ruleIds.ShouldContain(UnsupportedElementUsed); + ruleIds.ShouldContain(EmptyRequiredElement); + ruleIds.ShouldContain(InvalidTypeElement); + ruleIds.ShouldContain(MissingElementOnRequiringLicenseAcceptance); + } + } +} diff --git a/src/chocolatey.tests/infrastructure.app/services/TemplateServiceSpecs.cs b/src/chocolatey.tests/infrastructure.app/services/TemplateServiceSpecs.cs index ceda4372e0..6e719aa1f5 100644 --- a/src/chocolatey.tests/infrastructure.app/services/TemplateServiceSpecs.cs +++ b/src/chocolatey.tests/infrastructure.app/services/TemplateServiceSpecs.cs @@ -50,7 +50,7 @@ public override void Context() } } - public class when_generate_noop_is_called : TemplateServiceSpecsBase + public class When_generate_noop_is_called : TemplateServiceSpecsBase { private Action because; private readonly ChocolateyConfiguration config = new ChocolateyConfiguration(); @@ -58,24 +58,24 @@ public class when_generate_noop_is_called : TemplateServiceSpecsBase public override void Context() { base.Context(); - fileSystem.Setup(x => x.get_current_directory()).Returns("c:\\chocolatey"); - fileSystem.Setup(x => x.combine_paths(It.IsAny(), It.IsAny())) + fileSystem.Setup(x => x.GetCurrentDirectory()).Returns("c:\\chocolatey"); + fileSystem.Setup(x => x.CombinePaths(It.IsAny(), It.IsAny())) .Returns((string a, string[] b) => { return a + "\\" + b[0]; }); config.NewCommand.Name = "Bob"; } public override void Because() { - because = () => service.generate_noop(config); + because = () => service.GenerateDryRun(config); } public override void BeforeEachSpec() { - MockLogger.reset(); + MockLogger.Reset(); } [Fact] - public void should_log_current_directory_if_no_outputdirectory() + public void Should_log_current_directory_if_no_outputdirectory() { because(); @@ -85,7 +85,7 @@ public void should_log_current_directory_if_no_outputdirectory() } [Fact] - public void should_log_output_directory_if_outputdirectory_is_specified() + public void Should_log_output_directory_if_outputdirectory_is_specified() { config.OutputDirectory = "c:\\packages"; @@ -97,7 +97,7 @@ public void should_log_output_directory_if_outputdirectory_is_specified() } } - public class when_generate_file_from_template_is_called : TemplateServiceSpecsBase + public class When_generate_file_from_template_is_called : TemplateServiceSpecsBase { private Action because; private readonly ChocolateyConfiguration config = new ChocolateyConfiguration(); @@ -110,7 +110,7 @@ public override void Context() { base.Context(); - fileSystem.Setup(x => x.write_file(It.Is((string fl) => fl == fileLocation), It.IsAny(), Encoding.UTF8)) + fileSystem.Setup(x => x.WriteFile(It.Is((string fl) => fl == fileLocation), It.IsAny(), Encoding.UTF8)) .Callback((string filePath, string fileContent, Encoding encoding) => this.fileContent = fileContent); templateValues.PackageName = "Bob"; @@ -118,16 +118,16 @@ public override void Context() public override void Because() { - because = () => service.generate_file_from_template(config, templateValues, template, fileLocation, Encoding.UTF8); + because = () => service.GenerateFileFromTemplate(config, templateValues, template, fileLocation, Encoding.UTF8); } public override void BeforeEachSpec() { - MockLogger.reset(); + MockLogger.Reset(); } [Fact] - public void should_write_file_withe_replaced_tokens() + public void Should_write_file_withe_replaced_tokens() { because(); @@ -137,7 +137,7 @@ public void should_write_file_withe_replaced_tokens() } [Fact] - public void should_log_info_if_regular_output() + public void Should_log_info_if_regular_output() { config.RegularOutput = true; @@ -153,7 +153,7 @@ public void should_log_info_if_regular_output() } } - public class when_generate_is_called_with_existing_directory : TemplateServiceSpecsBase + public class When_generate_is_called_with_existing_directory : TemplateServiceSpecsBase { private Action because; private readonly ChocolateyConfiguration config = new ChocolateyConfiguration(); @@ -163,10 +163,10 @@ public override void Context() { base.Context(); - fileSystem.Setup(x => x.get_current_directory()).Returns("c:\\chocolatey"); - fileSystem.Setup(x => x.combine_paths(It.IsAny(), It.IsAny())) + fileSystem.Setup(x => x.GetCurrentDirectory()).Returns("c:\\chocolatey"); + fileSystem.Setup(x => x.CombinePaths(It.IsAny(), It.IsAny())) .Returns((string a, string[] b) => { return a + "\\" + b[0]; }); - fileSystem.Setup(x => x.directory_exists(It.IsAny())).Returns( + fileSystem.Setup(x => x.DirectoryExists(It.IsAny())).Returns( x => { verifiedDirectoryPath = x; @@ -178,16 +178,16 @@ public override void Context() public override void Because() { - because = () => service.generate(config); + because = () => service.Generate(config); } public override void BeforeEachSpec() { - MockLogger.reset(); + MockLogger.Reset(); } [Fact] - public void should_throw_exception() + public void Should_throw_exception() { bool errored = false; string errorMessage = string.Empty; @@ -208,7 +208,7 @@ public void should_throw_exception() } [Fact] - public void should_throw_exception_even_with_outputdirectory() + public void Should_throw_exception_even_with_outputdirectory() { config.OutputDirectory = "c:\\packages"; @@ -231,7 +231,7 @@ public void should_throw_exception_even_with_outputdirectory() } } - public class when_generate_is_called : TemplateServiceSpecsBase + public class When_generate_is_called : TemplateServiceSpecsBase { private Action because; private readonly ChocolateyConfiguration config = new ChocolateyConfiguration(); @@ -243,8 +243,8 @@ public override void Context() { base.Context(); - fileSystem.Setup(x => x.get_current_directory()).Returns("c:\\chocolatey"); - fileSystem.Setup(x => x.combine_paths(It.IsAny(), It.IsAny())) + fileSystem.Setup(x => x.GetCurrentDirectory()).Returns("c:\\chocolatey"); + fileSystem.Setup(x => x.CombinePaths(It.IsAny(), It.IsAny())) .Returns( (string a, string[] b) => { @@ -254,13 +254,13 @@ public override void Context() } return a + "\\" + b[0]; }); - fileSystem.Setup(x => x.directory_exists(It.IsAny())).Returns(dirPath => dirPath.EndsWith("templates\\default")); - fileSystem.Setup(x => x.write_file(It.IsAny(), It.IsAny(), Encoding.UTF8)) + fileSystem.Setup(x => x.DirectoryExists(It.IsAny())).Returns(dirPath => dirPath.EndsWith("templates\\default")); + fileSystem.Setup(x => x.WriteFile(It.IsAny(), It.IsAny(), Encoding.UTF8)) .Callback((string filePath, string fileContent, Encoding encoding) => files.Add(filePath)); - fileSystem.Setup(x => x.write_file(It.IsAny(), It.IsAny(), utf8WithoutBOM)) + fileSystem.Setup(x => x.WriteFile(It.IsAny(), It.IsAny(), utf8WithoutBOM)) .Callback((string filePath, string fileContent, Encoding encoding) => files.Add(filePath)); - fileSystem.Setup(x => x.delete_directory_if_exists(It.IsAny(), true)); - fileSystem.Setup(x => x.create_directory_if_not_exists(It.IsAny())).Callback( + fileSystem.Setup(x => x.DeleteDirectoryChecked(It.IsAny(), true)); + fileSystem.Setup(x => x.EnsureDirectoryExists(It.IsAny())).Callback( (string directory) => { if (!string.IsNullOrWhiteSpace(directory)) @@ -268,28 +268,28 @@ public override void Context() directoryCreated.Add(directory); } }); - fileSystem.Setup(x => x.get_files(It.IsAny(), "*.*", SearchOption.AllDirectories)).Returns(new[] { "templates\\default\\template.nuspec", "templates\\default\\random.txt" }); - fileSystem.Setup(x => x.get_directory_name(It.IsAny())).Returns(file => Path.GetDirectoryName(file)); - fileSystem.Setup(x => x.get_file_extension(It.IsAny())).Returns(file => Path.GetExtension(file)); - fileSystem.Setup(x => x.read_file(It.IsAny())).Returns(string.Empty); + fileSystem.Setup(x => x.GetFiles(It.IsAny(), "*.*", SearchOption.AllDirectories)).Returns(new[] { "templates\\default\\template.nuspec", "templates\\default\\random.txt" }); + fileSystem.Setup(x => x.GetDirectoryName(It.IsAny())).Returns(file => Path.GetDirectoryName(file)); + fileSystem.Setup(x => x.GetFileExtension(It.IsAny())).Returns(file => Path.GetExtension(file)); + fileSystem.Setup(x => x.ReadFile(It.IsAny())).Returns(string.Empty); config.NewCommand.Name = "Bob"; } public override void Because() { - because = () => service.generate(config); + because = () => service.Generate(config); } public override void BeforeEachSpec() { - MockLogger.reset(); + MockLogger.Reset(); files.Clear(); directoryCreated.Clear(); } [Fact] - public void should_generate_all_files_and_directories() + public void Should_generate_all_files_and_directories() { because(); @@ -306,7 +306,7 @@ public void should_generate_all_files_and_directories() } [Fact] - public void should_generate_all_files_and_directories_even_with_outputdirectory() + public void Should_generate_all_files_and_directories_even_with_outputdirectory() { config.OutputDirectory = "c:\\packages"; @@ -325,7 +325,7 @@ public void should_generate_all_files_and_directories_even_with_outputdirectory( } } - public class when_generate_is_called_with_nested_folders : TemplateServiceSpecsBase + public class When_generate_is_called_with_nested_folders : TemplateServiceSpecsBase { private Action because; private readonly ChocolateyConfiguration config = new ChocolateyConfiguration(); @@ -337,8 +337,8 @@ public override void Context() { base.Context(); - fileSystem.Setup(x => x.get_current_directory()).Returns("c:\\chocolatey"); - fileSystem.Setup(x => x.combine_paths(It.IsAny(), It.IsAny())) + fileSystem.Setup(x => x.GetCurrentDirectory()).Returns("c:\\chocolatey"); + fileSystem.Setup(x => x.CombinePaths(It.IsAny(), It.IsAny())) .Returns( (string a, string[] b) => { @@ -348,17 +348,17 @@ public override void Context() } return a + "\\" + b[0]; }); - fileSystem.Setup(x => x.directory_exists(It.IsAny())).Returns(dirPath => dirPath.EndsWith("templates\\test")); - fileSystem.Setup(x => x.write_file(It.IsAny(), It.IsAny(), Encoding.UTF8)) + fileSystem.Setup(x => x.DirectoryExists(It.IsAny())).Returns(dirPath => dirPath.EndsWith("templates\\test")); + fileSystem.Setup(x => x.WriteFile(It.IsAny(), It.IsAny(), Encoding.UTF8)) .Callback((string filePath, string fileContent, Encoding encoding) => files.Add(filePath)); - fileSystem.Setup(x => x.write_file(It.IsAny(), It.IsAny(), utf8WithoutBOM)) + fileSystem.Setup(x => x.WriteFile(It.IsAny(), It.IsAny(), utf8WithoutBOM)) .Callback((string filePath, string fileContent, Encoding encoding) => files.Add(filePath)); - fileSystem.Setup(x => x.delete_directory_if_exists(It.IsAny(), true)); - fileSystem.Setup(x => x.get_files(It.IsAny(), "*.*", SearchOption.AllDirectories)) + fileSystem.Setup(x => x.DeleteDirectoryChecked(It.IsAny(), true)); + fileSystem.Setup(x => x.GetFiles(It.IsAny(), "*.*", SearchOption.AllDirectories)) .Returns(new[] { "templates\\test\\template.nuspec", "templates\\test\\random.txt", "templates\\test\\tools\\chocolateyInstall.ps1", "templates\\test\\tools\\lower\\another.ps1" }); - fileSystem.Setup(x => x.get_directories(It.IsAny(), "*.*", SearchOption.AllDirectories)) + fileSystem.Setup(x => x.GetDirectories(It.IsAny(), "*.*", SearchOption.AllDirectories)) .Returns(new[] { "templates\\test", "templates\\test\\tools", "templates\\test\\tools\\lower" }); - fileSystem.Setup(x => x.create_directory_if_not_exists(It.IsAny())).Callback( + fileSystem.Setup(x => x.EnsureDirectoryExists(It.IsAny())).Callback( (string directory) => { if (!string.IsNullOrWhiteSpace(directory)) @@ -366,9 +366,9 @@ public override void Context() directoryCreated.Add(directory); } }); - fileSystem.Setup(x => x.get_directory_name(It.IsAny())).Returns(file => Path.GetDirectoryName(file)); - fileSystem.Setup(x => x.get_file_extension(It.IsAny())).Returns(file => Path.GetExtension(file)); - fileSystem.Setup(x => x.read_file(It.IsAny())).Returns(string.Empty); + fileSystem.Setup(x => x.GetDirectoryName(It.IsAny())).Returns(file => Path.GetDirectoryName(file)); + fileSystem.Setup(x => x.GetFileExtension(It.IsAny())).Returns(file => Path.GetExtension(file)); + fileSystem.Setup(x => x.ReadFile(It.IsAny())).Returns(string.Empty); config.NewCommand.Name = "Bob"; config.NewCommand.TemplateName = "test"; @@ -376,18 +376,18 @@ public override void Context() public override void Because() { - because = () => service.generate(config); + because = () => service.Generate(config); } public override void BeforeEachSpec() { - MockLogger.reset(); + MockLogger.Reset(); files.Clear(); directoryCreated.Clear(); } [Fact] - public void should_generate_all_files_and_directories() + public void Should_generate_all_files_and_directories() { because(); @@ -407,7 +407,7 @@ public void should_generate_all_files_and_directories() } [Fact] - public void should_generate_all_files_and_directories_even_with_outputdirectory() + public void Should_generate_all_files_and_directories_even_with_outputdirectory() { config.OutputDirectory = "c:\\packages"; @@ -429,7 +429,7 @@ public void should_generate_all_files_and_directories_even_with_outputdirectory( } } - public class when_generate_is_called_with_empty_nested_folders : TemplateServiceSpecsBase + public class When_generate_is_called_with_empty_nested_folders : TemplateServiceSpecsBase { private Action because; private readonly ChocolateyConfiguration config = new ChocolateyConfiguration(); @@ -441,8 +441,8 @@ public override void Context() { base.Context(); - fileSystem.Setup(x => x.get_current_directory()).Returns("c:\\chocolatey"); - fileSystem.Setup(x => x.combine_paths(It.IsAny(), It.IsAny())) + fileSystem.Setup(x => x.GetCurrentDirectory()).Returns("c:\\chocolatey"); + fileSystem.Setup(x => x.CombinePaths(It.IsAny(), It.IsAny())) .Returns( (string a, string[] b) => { @@ -452,17 +452,17 @@ public override void Context() } return a + "\\" + b[0]; }); - fileSystem.Setup(x => x.directory_exists(It.IsAny())).Returns(dirPath => dirPath.EndsWith("templates\\test")); - fileSystem.Setup(x => x.write_file(It.IsAny(), It.IsAny(), Encoding.UTF8)) + fileSystem.Setup(x => x.DirectoryExists(It.IsAny())).Returns(dirPath => dirPath.EndsWith("templates\\test")); + fileSystem.Setup(x => x.WriteFile(It.IsAny(), It.IsAny(), Encoding.UTF8)) .Callback((string filePath, string fileContent, Encoding encoding) => files.Add(filePath)); - fileSystem.Setup(x => x.write_file(It.IsAny(), It.IsAny(), utf8WithoutBOM)) + fileSystem.Setup(x => x.WriteFile(It.IsAny(), It.IsAny(), utf8WithoutBOM)) .Callback((string filePath, string fileContent, Encoding encoding) => files.Add(filePath)); - fileSystem.Setup(x => x.delete_directory_if_exists(It.IsAny(), true)); - fileSystem.Setup(x => x.get_files(It.IsAny(), "*.*", SearchOption.AllDirectories)) + fileSystem.Setup(x => x.DeleteDirectoryChecked(It.IsAny(), true)); + fileSystem.Setup(x => x.GetFiles(It.IsAny(), "*.*", SearchOption.AllDirectories)) .Returns(new[] { "templates\\test\\template.nuspec", "templates\\test\\random.txt", "templates\\test\\tools\\chocolateyInstall.ps1", "templates\\test\\tools\\lower\\another.ps1" }); - fileSystem.Setup(x => x.get_directories(It.IsAny(), "*.*", SearchOption.AllDirectories)) + fileSystem.Setup(x => x.GetDirectories(It.IsAny(), "*.*", SearchOption.AllDirectories)) .Returns(new[] { "templates\\test", "templates\\test\\tools", "templates\\test\\tools\\lower", "templates\\test\\empty", "templates\\test\\empty\\nested" }); - fileSystem.Setup(x => x.create_directory_if_not_exists(It.IsAny())).Callback( + fileSystem.Setup(x => x.EnsureDirectoryExists(It.IsAny())).Callback( (string directory) => { if (!string.IsNullOrWhiteSpace(directory)) @@ -470,9 +470,9 @@ public override void Context() directoryCreated.Add(directory); } }); - fileSystem.Setup(x => x.get_directory_name(It.IsAny())).Returns(file => Path.GetDirectoryName(file)); - fileSystem.Setup(x => x.get_file_extension(It.IsAny())).Returns(file => Path.GetExtension(file)); - fileSystem.Setup(x => x.read_file(It.IsAny())).Returns(string.Empty); + fileSystem.Setup(x => x.GetDirectoryName(It.IsAny())).Returns(file => Path.GetDirectoryName(file)); + fileSystem.Setup(x => x.GetFileExtension(It.IsAny())).Returns(file => Path.GetExtension(file)); + fileSystem.Setup(x => x.ReadFile(It.IsAny())).Returns(string.Empty); config.NewCommand.Name = "Bob"; config.NewCommand.TemplateName = "test"; @@ -480,18 +480,18 @@ public override void Context() public override void Because() { - because = () => service.generate(config); + because = () => service.Generate(config); } public override void BeforeEachSpec() { - MockLogger.reset(); + MockLogger.Reset(); files.Clear(); directoryCreated.Clear(); } [Fact] - public void should_generate_all_files_and_directories() + public void Should_generate_all_files_and_directories() { because(); @@ -513,7 +513,7 @@ public void should_generate_all_files_and_directories() } [Fact] - public void should_generate_all_files_and_directories_even_with_outputdirectory() + public void Should_generate_all_files_and_directories_even_with_outputdirectory() { config.OutputDirectory = "c:\\packages"; @@ -537,7 +537,7 @@ public void should_generate_all_files_and_directories_even_with_outputdirectory( } } - public class when_generate_is_called_with_defaulttemplatename_in_configuration_but_template_folder_doesnt_exist : TemplateServiceSpecsBase + public class When_generate_is_called_with_defaulttemplatename_in_configuration_but_template_folder_doesnt_exist : TemplateServiceSpecsBase { private Action because; private readonly ChocolateyConfiguration config = new ChocolateyConfiguration(); @@ -546,8 +546,8 @@ public override void Context() { base.Context(); - fileSystem.Setup(x => x.get_current_directory()).Returns("c:\\chocolatey"); - fileSystem.Setup(x => x.combine_paths(It.IsAny(), It.IsAny())) + fileSystem.Setup(x => x.GetCurrentDirectory()).Returns("c:\\chocolatey"); + fileSystem.Setup(x => x.CombinePaths(It.IsAny(), It.IsAny())) .Returns((string a, string[] b) => { return a + "\\" + b[0]; }); config.NewCommand.Name = "Bob"; @@ -556,18 +556,18 @@ public override void Context() public override void Because() { - because = () => service.generate(config); + because = () => service.Generate(config); } public override void BeforeEachSpec() { - MockLogger.reset(); + MockLogger.Reset(); } [Fact] [WindowsOnly] [Platform(Exclude = "Mono")] - public void should_use_null_value_for_template() + public void Should_use_null_value_for_template() { because(); @@ -575,7 +575,7 @@ public void should_use_null_value_for_template() } } - public class when_generate_is_called_with_defaulttemplatename_in_configuration_and_template_folder_exists : TemplateServiceSpecsBase + public class When_generate_is_called_with_defaulttemplatename_in_configuration_and_template_folder_exists : TemplateServiceSpecsBase { private Action because; private readonly ChocolateyConfiguration config = new ChocolateyConfiguration(); @@ -585,10 +585,10 @@ public override void Context() { base.Context(); - fileSystem.Setup(x => x.get_current_directory()).Returns("c:\\chocolatey"); - fileSystem.Setup(x => x.combine_paths(It.IsAny(), It.IsAny())) + fileSystem.Setup(x => x.GetCurrentDirectory()).Returns("c:\\chocolatey"); + fileSystem.Setup(x => x.CombinePaths(It.IsAny(), It.IsAny())) .Returns((string a, string[] b) => { return a + "\\" + b[0]; }); - fileSystem.Setup(x => x.directory_exists(Path.Combine(ApplicationParameters.TemplatesLocation, "msi"))).Returns( + fileSystem.Setup(x => x.DirectoryExists(Path.Combine(ApplicationParameters.TemplatesLocation, "msi"))).Returns( x => { verifiedDirectoryPath = x; @@ -601,18 +601,18 @@ public override void Context() public override void Because() { - because = () => service.generate(config); + because = () => service.Generate(config); } public override void BeforeEachSpec() { - MockLogger.reset(); + MockLogger.Reset(); } [Fact] [WindowsOnly] [Platform(Exclude = "Mono")] - public void should_use_template_name_from_configuration() + public void Should_use_template_name_from_configuration() { because(); @@ -620,7 +620,7 @@ public void should_use_template_name_from_configuration() } } - public class when_generate_is_called_with_defaulttemplatename_in_configuration_and_template_name_option_set : TemplateServiceSpecsBase + public class When_generate_is_called_with_defaulttemplatename_in_configuration_and_template_name_option_set : TemplateServiceSpecsBase { private Action because; private readonly ChocolateyConfiguration config = new ChocolateyConfiguration(); @@ -630,10 +630,10 @@ public override void Context() { base.Context(); - fileSystem.Setup(x => x.get_current_directory()).Returns("c:\\chocolatey"); - fileSystem.Setup(x => x.combine_paths(It.IsAny(), It.IsAny())) + fileSystem.Setup(x => x.GetCurrentDirectory()).Returns("c:\\chocolatey"); + fileSystem.Setup(x => x.CombinePaths(It.IsAny(), It.IsAny())) .Returns((string a, string[] b) => { return a + "\\" + b[0]; }); - fileSystem.Setup(x => x.directory_exists(Path.Combine(ApplicationParameters.TemplatesLocation, "zip"))).Returns( + fileSystem.Setup(x => x.DirectoryExists(Path.Combine(ApplicationParameters.TemplatesLocation, "zip"))).Returns( x => { verifiedDirectoryPath = x; @@ -647,18 +647,18 @@ public override void Context() public override void Because() { - because = () => service.generate(config); + because = () => service.Generate(config); } public override void BeforeEachSpec() { - MockLogger.reset(); + MockLogger.Reset(); } [Fact] [WindowsOnly] [Platform(Exclude = "Mono")] - public void should_use_template_name_from_command_line_option() + public void Should_use_template_name_from_command_line_option() { because(); @@ -666,7 +666,7 @@ public void should_use_template_name_from_command_line_option() } } - public class when_generate_is_called_with_built_in_option_set : TemplateServiceSpecsBase + public class When_generate_is_called_with_built_in_option_set : TemplateServiceSpecsBase { private Action because; private readonly ChocolateyConfiguration config = new ChocolateyConfiguration(); @@ -681,18 +681,18 @@ public override void Context() public override void Because() { - because = () => service.generate(config); + because = () => service.Generate(config); } public override void BeforeEachSpec() { - MockLogger.reset(); + MockLogger.Reset(); } [Fact] [WindowsOnly] [Platform(Exclude = "Mono")] - public void should_use_null_value_for_template() + public void Should_use_null_value_for_template() { because(); @@ -700,7 +700,7 @@ public void should_use_null_value_for_template() } } - public class when_generate_is_called_with_built_in_option_set_and_defaulttemplate_in_configuration : TemplateServiceSpecsBase + public class When_generate_is_called_with_built_in_option_set_and_defaulttemplate_in_configuration : TemplateServiceSpecsBase { private Action because; private readonly ChocolateyConfiguration config = new ChocolateyConfiguration(); @@ -716,18 +716,18 @@ public override void Context() public override void Because() { - because = () => service.generate(config); + because = () => service.Generate(config); } public override void BeforeEachSpec() { - MockLogger.reset(); + MockLogger.Reset(); } [Fact] [WindowsOnly] [Platform(Exclude = "Mono")] - public void should_use_null_value_for_template() + public void Should_use_null_value_for_template() { because(); @@ -735,7 +735,7 @@ public void should_use_null_value_for_template() } } - public class when_generate_is_called_with_built_in_option_set_and_template_name_option_set_and_template_folder_exists : TemplateServiceSpecsBase + public class When_generate_is_called_with_built_in_option_set_and_template_name_option_set_and_template_folder_exists : TemplateServiceSpecsBase { private Action because; private readonly ChocolateyConfiguration config = new ChocolateyConfiguration(); @@ -745,10 +745,10 @@ public override void Context() { base.Context(); - fileSystem.Setup(x => x.get_current_directory()).Returns("c:\\chocolatey"); - fileSystem.Setup(x => x.combine_paths(It.IsAny(), It.IsAny())) + fileSystem.Setup(x => x.GetCurrentDirectory()).Returns("c:\\chocolatey"); + fileSystem.Setup(x => x.CombinePaths(It.IsAny(), It.IsAny())) .Returns((string a, string[] b) => { return a + "\\" + b[0]; }); - fileSystem.Setup(x => x.directory_exists(Path.Combine(ApplicationParameters.TemplatesLocation, "zip"))).Returns( + fileSystem.Setup(x => x.DirectoryExists(Path.Combine(ApplicationParameters.TemplatesLocation, "zip"))).Returns( x => { verifiedDirectoryPath = x; @@ -762,18 +762,18 @@ public override void Context() public override void Because() { - because = () => service.generate(config); + because = () => service.Generate(config); } public override void BeforeEachSpec() { - MockLogger.reset(); + MockLogger.Reset(); } [Fact] [WindowsOnly] [Platform(Exclude = "Mono")] - public void should_use_template_name_from_command_line_option() + public void Should_use_template_name_from_command_line_option() { because(); @@ -781,7 +781,7 @@ public void should_use_template_name_from_command_line_option() } } - public class when_generate_is_called_with_built_in_option_set_and_template_name_option_set_and_defaulttemplatename_set_and_template_folder_exists : TemplateServiceSpecsBase + public class When_generate_is_called_with_built_in_option_set_and_template_name_option_set_and_defaulttemplatename_set_and_template_folder_exists : TemplateServiceSpecsBase { private Action because; private readonly ChocolateyConfiguration config = new ChocolateyConfiguration(); @@ -791,10 +791,10 @@ public override void Context() { base.Context(); - fileSystem.Setup(x => x.get_current_directory()).Returns("c:\\chocolatey"); - fileSystem.Setup(x => x.combine_paths(It.IsAny(), It.IsAny())) + fileSystem.Setup(x => x.GetCurrentDirectory()).Returns("c:\\chocolatey"); + fileSystem.Setup(x => x.CombinePaths(It.IsAny(), It.IsAny())) .Returns((string a, string[] b) => { return a + "\\" + b[0]; }); - fileSystem.Setup(x => x.directory_exists(Path.Combine(ApplicationParameters.TemplatesLocation, "zip"))).Returns( + fileSystem.Setup(x => x.DirectoryExists(Path.Combine(ApplicationParameters.TemplatesLocation, "zip"))).Returns( x => { verifiedDirectoryPath = x; @@ -809,18 +809,18 @@ public override void Context() public override void Because() { - because = () => service.generate(config); + because = () => service.Generate(config); } public override void BeforeEachSpec() { - MockLogger.reset(); + MockLogger.Reset(); } [Fact] [WindowsOnly] [Platform(Exclude = "Mono")] - public void should_use_template_name_from_command_line_option() + public void Should_use_template_name_from_command_line_option() { because(); @@ -828,40 +828,40 @@ public void should_use_template_name_from_command_line_option() } } - public class when_list_noop_is_called : TemplateServiceSpecsBase + public class When_list_noop_is_called : TemplateServiceSpecsBase { private Action because; private readonly ChocolateyConfiguration config = new ChocolateyConfiguration(); public override void Because() { - because = () => service.list_noop(config); + because = () => service.ListDryRun(config); } public override void BeforeEachSpec() { - MockLogger.reset(); + MockLogger.Reset(); } [Fact] - public void should_log_template_location_if_no_template_name() + public void Should_log_template_location_if_no_template_name() { because(); var infos = MockLogger.MessagesFor(LogLevel.Info); infos.Count.ShouldEqual(1); - infos[0].ShouldEqual("Would have listed templates in {0}".format_with(ApplicationParameters.TemplatesLocation)); + infos[0].ShouldEqual("Would have listed templates in {0}".FormatWith(ApplicationParameters.TemplatesLocation)); } [Fact] - public void should_log_template_name_if_template_name() + public void Should_log_template_name_if_template_name() { config.TemplateCommand.Name = "msi"; because(); var infos = MockLogger.MessagesFor(LogLevel.Info); infos.Count.ShouldEqual(1); - infos[0].ShouldEqual("Would have listed information about {0}".format_with(config.TemplateCommand.Name)); + infos[0].ShouldEqual("Would have listed information about {0}".FormatWith(config.TemplateCommand.Name)); } } } diff --git a/src/chocolatey.tests/infrastructure.app/utility/ArgumentsUtilitySpecs.cs b/src/chocolatey.tests/infrastructure.app/utility/ArgumentsUtilitySpecs.cs index 21c9ac2281..a0b6c88cc6 100644 --- a/src/chocolatey.tests/infrastructure.app/utility/ArgumentsUtilitySpecs.cs +++ b/src/chocolatey.tests/infrastructure.app/utility/ArgumentsUtilitySpecs.cs @@ -35,13 +35,13 @@ public override void Context() [TestFixture("choco install bob -api-key=secretKey", true)] [TestFixture("choco install bob -api-key secretKey", true)] [TestFixture("choco install bob", false)] - public class when_ArgumentsUtility_is_testing_for_sensitive_parameters : ArgumentsUtilitySpecsBase + public class When_ArgumentsUtility_is_testing_for_sensitive_parameters : ArgumentsUtilitySpecsBase { private bool _result; private bool _expectedResult; private string _commandArguments; - public when_ArgumentsUtility_is_testing_for_sensitive_parameters(string commandArguments, bool expectedResult) + public When_ArgumentsUtility_is_testing_for_sensitive_parameters(string commandArguments, bool expectedResult) { _commandArguments = commandArguments; _expectedResult = expectedResult; @@ -49,11 +49,11 @@ public when_ArgumentsUtility_is_testing_for_sensitive_parameters(string commandA public override void Because() { - _result = ArgumentsUtility.arguments_contain_sensitive_information(_commandArguments); + _result = ArgumentsUtility.SensitiveArgumentsProvided(_commandArguments); } [Fact] - public void should_return_expected_result() + public void Should_return_expected_result() { _result.ShouldEqual(_expectedResult); } diff --git a/src/chocolatey.tests/infrastructure.app/utility/PackageUtilitySpecs.cs b/src/chocolatey.tests/infrastructure.app/utility/PackageUtilitySpecs.cs index 568e014955..f1a4895963 100644 --- a/src/chocolatey.tests/infrastructure.app/utility/PackageUtilitySpecs.cs +++ b/src/chocolatey.tests/infrastructure.app/utility/PackageUtilitySpecs.cs @@ -43,16 +43,16 @@ public override void Context() [TestFixture("dependency", "\\bob", true)] [TestFixture("dependency", "bob", true)] [TestFixture("dependency", "bob;separatedPackage", true)] - public class when_PackageUtility_is_checking_if_package_is_dependency : PackageUtilitySpecsBase + public class When_PackageUtility_is_checking_if_package_is_dependency : PackageUtilitySpecsBase { private readonly ChocolateyConfiguration _config = new ChocolateyConfiguration(); private bool _result; private bool _expectedResult; private string _packageName; - public when_PackageUtility_is_checking_if_package_is_dependency(string packageName, string configNames, bool expectedResult) + public When_PackageUtility_is_checking_if_package_is_dependency(string packageName, string configNames, bool expectedResult) { - if (Platform.get_platform() != PlatformType.Windows) configNames = configNames.Replace("\\", "/"); + if (Platform.GetPlatform() != PlatformType.Windows) configNames = configNames.Replace("\\", "/"); _packageName = packageName; _config.PackageNames = configNames; @@ -61,11 +61,11 @@ public when_PackageUtility_is_checking_if_package_is_dependency(string packageNa public override void Because() { - _result = PackageUtility.package_is_a_dependency(_config, _packageName); + _result = PackageUtility.PackageIdHasDependencySuffix(_config, _packageName); } [Fact] - public void should_return_expected_result() + public void Should_return_expected_result() { _result.ShouldEqual(_expectedResult); } diff --git a/src/chocolatey.tests/infrastructure/commandline/InteractivePromptSpecs.cs b/src/chocolatey.tests/infrastructure/commandline/InteractivePromptSpecs.cs index 20fcbd3287..183b03c635 100644 --- a/src/chocolatey.tests/infrastructure/commandline/InteractivePromptSpecs.cs +++ b/src/chocolatey.tests/infrastructure/commandline/InteractivePromptSpecs.cs @@ -35,19 +35,19 @@ public override void Context() { prompt_value = "hi"; - InteractivePrompt.initialize_with(new Lazy(() => console.Object)); + InteractivePrompt.InitializeWith(new Lazy(() => console.Object)); choices.Add("yes"); choices.Add("no"); } - public void should_have_called_Console_ReadLine() + public void Should_have_called_Console_ReadLine() { console.Verify(c => c.ReadLine(), Times.AtLeastOnce); } } - public class when_prompting_with_interactivePrompt : InteractivePromptSpecsBase + public class When_prompting_with_interactivePrompt : InteractivePromptSpecsBase { private string default_choice; private Func prompt; @@ -55,11 +55,11 @@ public class when_prompting_with_interactivePrompt : InteractivePromptSpecsBase public override void Because() { console.Setup(c => c.ReadLine()).Returns(""); //Enter pressed - prompt = () => InteractivePrompt.prompt_for_confirmation(prompt_value, choices, default_choice, requireAnswer: false); + prompt = () => InteractivePrompt.PromptForConfirmation(prompt_value, choices, default_choice, requireAnswer: false); } [Fact] - public void should_error_when_the_choicelist_is_null() + public void Should_error_when_the_choicelist_is_null() { choices = null; bool errored = false; @@ -78,7 +78,7 @@ public void should_error_when_the_choicelist_is_null() } [Fact] - public void should_error_when_the_choicelist_is_empty() + public void Should_error_when_the_choicelist_is_empty() { choices = new List(); bool errored = false; @@ -100,7 +100,7 @@ public void should_error_when_the_choicelist_is_empty() } [Fact] - public void should_error_when_the_prompt_input_is_null() + public void Should_error_when_the_prompt_input_is_null() { choices = new List { @@ -123,7 +123,7 @@ public void should_error_when_the_prompt_input_is_null() } [Fact] - public void should_error_when_the_default_choice_is_not_in_list() + public void Should_error_when_the_default_choice_is_not_in_list() { choices = new List { @@ -151,23 +151,23 @@ public void should_error_when_the_default_choice_is_not_in_list() } } - public class when_prompting_with_interactivePrompt_without_default_and_answer_is_not_required : InteractivePromptSpecsBase + public class When_prompting_with_interactivePrompt_without_default_and_answer_is_not_required : InteractivePromptSpecsBase { private Func prompt; public override void Because() { - prompt = () => InteractivePrompt.prompt_for_confirmation(prompt_value, choices, null, requireAnswer: false); + prompt = () => InteractivePrompt.PromptForConfirmation(prompt_value, choices, null, requireAnswer: false); } public override void AfterObservations() { base.AfterObservations(); - should_have_called_Console_ReadLine(); + Should_have_called_Console_ReadLine(); } [Fact] - public void should_return_null_when_no_answer_given() + public void Should_return_null_when_no_answer_given() { console.Setup(c => c.ReadLine()).Returns(""); //Enter pressed var result = prompt(); @@ -175,7 +175,7 @@ public void should_return_null_when_no_answer_given() } [Fact] - public void should_return_first_choice_when_1_is_given() + public void Should_return_first_choice_when_1_is_given() { console.Setup(c => c.ReadLine()).Returns("1"); var result = prompt(); @@ -183,7 +183,7 @@ public void should_return_first_choice_when_1_is_given() } [Fact] - public void should_return_first_choice_when_value_of_choice_is_given() + public void Should_return_first_choice_when_value_of_choice_is_given() { console.Setup(c => c.ReadLine()).Returns("yes"); var result = prompt(); @@ -191,7 +191,7 @@ public void should_return_first_choice_when_value_of_choice_is_given() } [Fact] - public void should_return_second_choice_when_2_is_given() + public void Should_return_second_choice_when_2_is_given() { console.Setup(c => c.ReadLine()).Returns("2"); var result = prompt(); @@ -199,7 +199,7 @@ public void should_return_second_choice_when_2_is_given() } [Fact] - public void should_return_null_choice_when_3_is_given() + public void Should_return_null_choice_when_3_is_given() { console.Setup(c => c.ReadLine()).Returns("3"); var result = prompt(); @@ -207,7 +207,7 @@ public void should_return_null_choice_when_3_is_given() } [Fact] - public void should_return_null_choice_when_4_is_given() + public void Should_return_null_choice_when_4_is_given() { console.Setup(c => c.ReadLine()).Returns("4"); var result = prompt(); @@ -215,7 +215,7 @@ public void should_return_null_choice_when_4_is_given() } [Fact] - public void should_return_null_choice_when_0_is_given() + public void Should_return_null_choice_when_0_is_given() { console.Setup(c => c.ReadLine()).Returns("0"); var result = prompt(); @@ -223,7 +223,7 @@ public void should_return_null_choice_when_0_is_given() } [Fact] - public void should_return_null_choice_when_negative_1_is_given() + public void Should_return_null_choice_when_negative_1_is_given() { console.Setup(c => c.ReadLine()).Returns("-1"); var result = prompt(); @@ -231,7 +231,7 @@ public void should_return_null_choice_when_negative_1_is_given() } [Fact] - public void should_return_null_choice_when_alphabetical_characters_are_given() + public void Should_return_null_choice_when_alphabetical_characters_are_given() { console.Setup(c => c.ReadLine()).Returns("abc"); var result = prompt(); @@ -239,23 +239,23 @@ public void should_return_null_choice_when_alphabetical_characters_are_given() } } - public class when_prompting_with_interactivePrompt_without_default_and_answer_is_required : InteractivePromptSpecsBase + public class When_prompting_with_interactivePrompt_without_default_and_answer_is_required : InteractivePromptSpecsBase { private Func prompt; public override void Because() { - prompt = () => InteractivePrompt.prompt_for_confirmation(prompt_value, choices, null, requireAnswer: true); + prompt = () => InteractivePrompt.PromptForConfirmation(prompt_value, choices, null, requireAnswer: true); } public override void AfterObservations() { base.AfterObservations(); - should_have_called_Console_ReadLine(); + Should_have_called_Console_ReadLine(); } [Fact] - public void should_error_when_no_answer_given() + public void Should_error_when_no_answer_given() { bool errored = false; @@ -273,7 +273,7 @@ public void should_error_when_no_answer_given() } [Fact] - public void should_return_first_choice_when_1_is_given() + public void Should_return_first_choice_when_1_is_given() { console.Setup(c => c.ReadLine()).Returns("1"); var result = prompt(); @@ -281,7 +281,7 @@ public void should_return_first_choice_when_1_is_given() } [Fact] - public void should_return_second_choice_when_2_is_given() + public void Should_return_second_choice_when_2_is_given() { console.Setup(c => c.ReadLine()).Returns("2"); var result = prompt(); @@ -289,7 +289,7 @@ public void should_return_second_choice_when_2_is_given() } [Fact] - public void should_error_when_any_choice_not_available_is_given() + public void Should_error_when_any_choice_not_available_is_given() { bool errored = false; @@ -307,23 +307,23 @@ public void should_error_when_any_choice_not_available_is_given() } } - public class when_prompting_with_interactivePrompt_with_default_and_answer_is_not_required : InteractivePromptSpecsBase + public class When_prompting_with_interactivePrompt_with_default_and_answer_is_not_required : InteractivePromptSpecsBase { private Func prompt; public override void Because() { - prompt = () => InteractivePrompt.prompt_for_confirmation(prompt_value, choices, choices[1], requireAnswer: false); + prompt = () => InteractivePrompt.PromptForConfirmation(prompt_value, choices, choices[1], requireAnswer: false); } public override void AfterObservations() { base.AfterObservations(); - should_have_called_Console_ReadLine(); + Should_have_called_Console_ReadLine(); } [Fact] - public void should_return_default_when_no_answer_given() + public void Should_return_default_when_no_answer_given() { console.Setup(c => c.ReadLine()).Returns(""); //Enter pressed var result = prompt(); @@ -331,7 +331,7 @@ public void should_return_default_when_no_answer_given() } [Fact] - public void should_return_first_choice_when_1_is_given() + public void Should_return_first_choice_when_1_is_given() { console.Setup(c => c.ReadLine()).Returns("1"); var result = prompt(); @@ -339,7 +339,7 @@ public void should_return_first_choice_when_1_is_given() } [Fact] - public void should_return_second_choice_when_2_is_given() + public void Should_return_second_choice_when_2_is_given() { console.Setup(c => c.ReadLine()).Returns("2"); var result = prompt(); @@ -347,7 +347,7 @@ public void should_return_second_choice_when_2_is_given() } [Fact] - public void should_return_null_choice_when_3_is_given() + public void Should_return_null_choice_when_3_is_given() { console.Setup(c => c.ReadLine()).Returns("3"); var result = prompt(); @@ -355,7 +355,7 @@ public void should_return_null_choice_when_3_is_given() } [Fact] - public void should_return_null_choice_when_4_is_given() + public void Should_return_null_choice_when_4_is_given() { console.Setup(c => c.ReadLine()).Returns("4"); var result = prompt(); @@ -363,7 +363,7 @@ public void should_return_null_choice_when_4_is_given() } [Fact] - public void should_return_null_choice_when_0_is_given() + public void Should_return_null_choice_when_0_is_given() { console.Setup(c => c.ReadLine()).Returns("0"); var result = prompt(); @@ -371,7 +371,7 @@ public void should_return_null_choice_when_0_is_given() } [Fact] - public void should_return_null_choice_when_negative_1_is_given() + public void Should_return_null_choice_when_negative_1_is_given() { console.Setup(c => c.ReadLine()).Returns("-1"); var result = prompt(); @@ -379,7 +379,7 @@ public void should_return_null_choice_when_negative_1_is_given() } [Fact] - public void should_return_null_choice_when_alphabetical_characters_are_given() + public void Should_return_null_choice_when_alphabetical_characters_are_given() { console.Setup(c => c.ReadLine()).Returns("abc"); var result = prompt(); @@ -387,23 +387,23 @@ public void should_return_null_choice_when_alphabetical_characters_are_given() } } - public class when_prompting_with_interactivePrompt_with_default_and_answer_is_required : InteractivePromptSpecsBase + public class When_prompting_with_interactivePrompt_with_default_and_answer_is_required : InteractivePromptSpecsBase { private Func prompt; public override void Because() { - prompt = () => InteractivePrompt.prompt_for_confirmation(prompt_value, choices, choices[0], requireAnswer: true); + prompt = () => InteractivePrompt.PromptForConfirmation(prompt_value, choices, choices[0], requireAnswer: true); } public override void AfterObservations() { base.AfterObservations(); - should_have_called_Console_ReadLine(); + Should_have_called_Console_ReadLine(); } [Fact] - public void should_error_when_no_answer_given() + public void Should_error_when_no_answer_given() { console.Setup(c => c.ReadLine()).Returns(""); //Enter pressed var result = prompt(); @@ -411,7 +411,7 @@ public void should_error_when_no_answer_given() } [Fact] - public void should_return_first_choice_when_1_is_given() + public void Should_return_first_choice_when_1_is_given() { console.Setup(c => c.ReadLine()).Returns("1"); var result = prompt(); @@ -419,7 +419,7 @@ public void should_return_first_choice_when_1_is_given() } [Fact] - public void should_return_second_choice_when_2_is_given() + public void Should_return_second_choice_when_2_is_given() { console.Setup(c => c.ReadLine()).Returns("2"); var result = prompt(); @@ -427,7 +427,7 @@ public void should_return_second_choice_when_2_is_given() } [Fact] - public void should_error_when_any_choice_not_available_is_given() + public void Should_error_when_any_choice_not_available_is_given() { bool errored = false; @@ -445,18 +445,18 @@ public void should_error_when_any_choice_not_available_is_given() } } - public class when_prompting_short_with_interactivePrompt_guard_errors : InteractivePromptSpecsBase + public class When_prompting_short_with_interactivePrompt_guard_errors : InteractivePromptSpecsBase { private Func prompt; public override void Because() { console.Setup(c => c.ReadLine()).Returns(""); //Enter pressed - prompt = () => InteractivePrompt.prompt_for_confirmation(prompt_value, choices, defaultChoice: null, requireAnswer: true, shortPrompt: true); + prompt = () => InteractivePrompt.PromptForConfirmation(prompt_value, choices, defaultChoice: null, requireAnswer: true, shortPrompt: true); } [Fact] - public void should_error_when_the_choicelist_is_null() + public void Should_error_when_the_choicelist_is_null() { choices = null; bool errored = false; @@ -475,7 +475,7 @@ public void should_error_when_the_choicelist_is_null() } [Fact] - public void should_error_when_the_choicelist_is_empty() + public void Should_error_when_the_choicelist_is_empty() { choices = new List(); bool errored = false; @@ -497,7 +497,7 @@ public void should_error_when_the_choicelist_is_empty() } [Fact] - public void should_error_when_the_prompt_input_is_null() + public void Should_error_when_the_prompt_input_is_null() { choices = new List { @@ -523,7 +523,7 @@ public void should_error_when_the_prompt_input_is_null() } [Fact] - public void should_error_when_the_choicelist_contains_empty_values() + public void Should_error_when_the_choicelist_contains_empty_values() { choices = new List { @@ -549,7 +549,7 @@ public void should_error_when_the_choicelist_contains_empty_values() } [Fact] - public void should_error_when_the_choicelist_has_multiple_items_with_same_first_letter() + public void Should_error_when_the_choicelist_has_multiple_items_with_same_first_letter() { choices = new List { @@ -575,23 +575,23 @@ public void should_error_when_the_choicelist_has_multiple_items_with_same_first_ } } - public class when_prompting_short_with_interactivePrompt : InteractivePromptSpecsBase + public class When_prompting_short_with_interactivePrompt : InteractivePromptSpecsBase { private Func prompt; public override void Because() { - prompt = () => InteractivePrompt.prompt_for_confirmation(prompt_value, choices, defaultChoice: null, requireAnswer: true, shortPrompt: true); + prompt = () => InteractivePrompt.PromptForConfirmation(prompt_value, choices, defaultChoice: null, requireAnswer: true, shortPrompt: true); } public override void AfterObservations() { base.AfterObservations(); - should_have_called_Console_ReadLine(); + Should_have_called_Console_ReadLine(); } [Fact] - public void should_error_when_no_answer_given() + public void Should_error_when_no_answer_given() { bool errored = false; @@ -609,7 +609,7 @@ public void should_error_when_no_answer_given() } [Fact] - public void should_return_yes_when_yes_is_given() + public void Should_return_yes_when_yes_is_given() { console.Setup(c => c.ReadLine()).Returns("yes"); var result = prompt(); @@ -617,7 +617,7 @@ public void should_return_yes_when_yes_is_given() } [Fact] - public void should_return_yes_when_y_is_given() + public void Should_return_yes_when_y_is_given() { console.Setup(c => c.ReadLine()).Returns("y"); var result = prompt(); @@ -625,7 +625,7 @@ public void should_return_yes_when_y_is_given() } [Fact] - public void should_return_no_choice_when_no_is_given() + public void Should_return_no_choice_when_no_is_given() { console.Setup(c => c.ReadLine()).Returns("no"); var result = prompt(); @@ -633,7 +633,7 @@ public void should_return_no_choice_when_no_is_given() } [Fact] - public void should_return_no_choice_when_n_is_given() + public void Should_return_no_choice_when_n_is_given() { console.Setup(c => c.ReadLine()).Returns("n"); var result = prompt(); @@ -641,7 +641,7 @@ public void should_return_no_choice_when_n_is_given() } [Fact] - public void should_error_when_any_choice_not_available_is_given() + public void Should_error_when_any_choice_not_available_is_given() { bool errored = false; @@ -659,7 +659,7 @@ public void should_error_when_any_choice_not_available_is_given() } } - public class when_prompting_answer_with_dash_with_interactivePrompt : InteractivePromptSpecsBase + public class When_prompting_answer_with_dash_with_interactivePrompt : InteractivePromptSpecsBase { private Func prompt; @@ -671,17 +671,17 @@ public override void Context() public override void Because() { - prompt = () => InteractivePrompt.prompt_for_confirmation(prompt_value, choices, defaultChoice: null, requireAnswer: true, shortPrompt: true); + prompt = () => InteractivePrompt.PromptForConfirmation(prompt_value, choices, defaultChoice: null, requireAnswer: true, shortPrompt: true); } public override void AfterObservations() { base.AfterObservations(); - should_have_called_Console_ReadLine(); + Should_have_called_Console_ReadLine(); } [Fact] - public void should_return_all_when_full_all_answer_is_given() + public void Should_return_all_when_full_all_answer_is_given() { console.Setup(c => c.ReadLine()).Returns("all - yes to all"); var result = prompt(); @@ -689,7 +689,7 @@ public void should_return_all_when_full_all_answer_is_given() } [Fact] - public void should_return_all_when_only_all_is_given() + public void Should_return_all_when_only_all_is_given() { console.Setup(c => c.ReadLine()).Returns("all"); var result = prompt(); diff --git a/src/chocolatey.tests/infrastructure/commands/CommandExecutorSpecs.cs b/src/chocolatey.tests/infrastructure/commands/CommandExecutorSpecs.cs index f39191418f..df582b738e 100644 --- a/src/chocolatey.tests/infrastructure/commands/CommandExecutorSpecs.cs +++ b/src/chocolatey.tests/infrastructure/commands/CommandExecutorSpecs.cs @@ -35,11 +35,11 @@ public abstract class CommandExecutorSpecsBase : TinySpec public override void Context() { commandExecutor = new CommandExecutor(fileSystem.Object); - CommandExecutor.initialize_with(new Lazy(() => fileSystem.Object), () => process.Object); + CommandExecutor.InitializeWith(new Lazy(() => fileSystem.Object), () => process.Object); } } - public class when_CommandExecutor_is_executed_normally : CommandExecutorSpecsBase + public class When_CommandExecutor_is_executed_normally : CommandExecutorSpecsBase { private int result; @@ -52,53 +52,53 @@ public override void Context() public override void Because() { - result = commandExecutor.execute("bob", "args", ApplicationParameters.DefaultWaitForExitInSeconds); + result = commandExecutor.Execute("bob", "args", ApplicationParameters.DefaultWaitForExitInSeconds); } [Fact] - public void should_call_Start() + public void Should_call_Start() { process.Verify(p => p.Start(), Times.Once); } [Fact] - public void should_have_EnableRaisingEvents_set_to_true() + public void Should_have_EnableRaisingEvents_set_to_true() { process.VerifySet(p => p.EnableRaisingEvents = true); } [Fact] - public void should_call_WaitForExit() + public void Should_call_WaitForExit() { process.Verify(p => p.WaitForExit(It.IsAny()), Times.Once); } [Fact] - public void should_call_BeginErrorReadLine() + public void Should_call_BeginErrorReadLine() { process.Verify(p => p.BeginErrorReadLine(), Times.Once); } [Fact] - public void should_call_BeginOutputReadLine() + public void Should_call_BeginOutputReadLine() { process.Verify(p => p.BeginOutputReadLine(), Times.Once); } [Fact] - public void should_call_ExitCode() + public void Should_call_ExitCode() { process.Verify(p => p.ExitCode, Times.Once); } [Fact] - public void should_return_an_exit_code_of_zero_when_finished() + public void Should_return_an_exit_code_of_zero_when_finished() { result.ShouldEqual(0); } } - public class when_CommandExecutor_has_a_long_running_process_that_takes_longer_than_wait_time : CommandExecutorSpecsBase + public class When_CommandExecutor_has_a_long_running_process_that_takes_longer_than_wait_time : CommandExecutorSpecsBase { private int result; @@ -111,45 +111,45 @@ public override void Context() public override void Because() { - result = commandExecutor.execute("bob", "args", ApplicationParameters.DefaultWaitForExitInSeconds); + result = commandExecutor.Execute("bob", "args", ApplicationParameters.DefaultWaitForExitInSeconds); } [Fact] - public void should_call_WaitForExit() + public void Should_call_WaitForExit() { process.Verify(p => p.WaitForExit(It.IsAny()), Times.Once); } [Fact] - public void should_return_an_exit_code_of_negative_one_since_it_timed_out() + public void Should_return_an_exit_code_of_negative_one_since_it_timed_out() { result.ShouldEqual(-1); } [Fact] - public void should_not_call_ExitCode() + public void Should_not_call_ExitCode() { process.Verify(p => p.ExitCode, Times.Never); } } - public class when_CommandExecutor_does_not_wait_for_exit : CommandExecutorSpecsBase + public class When_CommandExecutor_does_not_wait_for_exit : CommandExecutorSpecsBase { private int result; public override void Because() { - result = commandExecutor.execute("bob", "args", waitForExitInSeconds: 0, workingDirectory: null, stdOutAction: null, stdErrAction: null, updateProcessPath: false, allowUseWindow: true, waitForExit: false); + result = commandExecutor.Execute("bob", "args", waitForExitInSeconds: 0, workingDirectory: null, stdOutAction: null, stdErrAction: null, updateProcessPath: false, allowUseWindow: true, waitForExit: false); } [Fact] - public void should_have_an_exit_code_of_negative_one_as_it_didnt_wait_for_finish() + public void Should_have_an_exit_code_of_negative_one_as_it_didnt_wait_for_finish() { result.ShouldEqual(-1); } [Fact] - public void should_not_call_WaitForExit() + public void Should_not_call_WaitForExit() { process.Verify(p => p.WaitForExit(It.IsAny()), Times.Never); } diff --git a/src/chocolatey.tests/infrastructure/commands/ExternalCommandArgsBuilderSpecs.cs b/src/chocolatey.tests/infrastructure/commands/ExternalCommandArgsBuilderSpecs.cs index eaf079d7a8..ddd08c029c 100644 --- a/src/chocolatey.tests/infrastructure/commands/ExternalCommandArgsBuilderSpecs.cs +++ b/src/chocolatey.tests/infrastructure/commands/ExternalCommandArgsBuilderSpecs.cs @@ -24,7 +24,7 @@ namespace chocolatey.tests.infrastructure.commands public class ExternalCommandArgsBuilderSpecs { - public class when_using_ExternalCommandArgsBuilder : TinySpec + public class When_using_ExternalCommandArgsBuilder : TinySpec { private Func buildConfigs; protected IDictionary argsDictionary = new Dictionary(); @@ -40,11 +40,11 @@ public override void Context() public override void Because() { - buildConfigs = () => ExternalCommandArgsBuilder.build_arguments(configuration, argsDictionary); + buildConfigs = () => ExternalCommandArgsBuilder.BuildArguments(configuration, argsDictionary); } [Fact] - public void should_add_a_parameter_if_property_value_is_set() + public void Should_add_a_parameter_if_property_value_is_set() { argsDictionary.Clear(); argsDictionary.Add( @@ -57,7 +57,7 @@ public void should_add_a_parameter_if_property_value_is_set() } [Fact] - public void should_add_a_parameter_if_property_value_is_sub_property() + public void Should_add_a_parameter_if_property_value_is_sub_property() { argsDictionary.Clear(); argsDictionary.Add( @@ -70,7 +70,7 @@ public void should_add_a_parameter_if_property_value_is_sub_property() } [Fact] - public void should_skip_a_parameter_that_does_not_match_the_case_of_the_property_name_exactly() + public void Should_skip_a_parameter_that_does_not_match_the_case_of_the_property_name_exactly() { argsDictionary.Clear(); argsDictionary.Add( @@ -83,7 +83,7 @@ public void should_skip_a_parameter_that_does_not_match_the_case_of_the_property } [Fact] - public void should_add_a_parameter_that_does_not_match_the_case_of_the_property_name_when_dictionary_ignores_case() + public void Should_add_a_parameter_that_does_not_match_the_case_of_the_property_name_when_dictionary_ignores_case() { IDictionary ignoreCaseDictionary = new Dictionary(StringComparer.InvariantCultureIgnoreCase); ignoreCaseDictionary.Add( @@ -92,11 +92,11 @@ public void should_add_a_parameter_that_does_not_match_the_case_of_the_property_ { ArgumentOption = "-source " }); - ExternalCommandArgsBuilder.build_arguments(configuration, ignoreCaseDictionary).ShouldEqual("-source yo"); + ExternalCommandArgsBuilder.BuildArguments(configuration, ignoreCaseDictionary).ShouldEqual("-source yo"); } [Fact] - public void should_not_override_ArgumentValue_with_the_property_value_for_a_parameter() + public void Should_not_override_ArgumentValue_with_the_property_value_for_a_parameter() { argsDictionary.Clear(); argsDictionary.Add( @@ -110,7 +110,7 @@ public void should_not_override_ArgumentValue_with_the_property_value_for_a_para } [Fact] - public void should_skip_a_parameter_if_property_value_has_no_value() + public void Should_skip_a_parameter_if_property_value_has_no_value() { argsDictionary.Clear(); argsDictionary.Add( @@ -123,7 +123,7 @@ public void should_skip_a_parameter_if_property_value_has_no_value() } [Fact] - public void should_add_a_parameter_when_Required_set_true_even_if_property_has_no_value() + public void Should_add_a_parameter_when_Required_set_true_even_if_property_has_no_value() { argsDictionary.Clear(); argsDictionary.Add( @@ -137,7 +137,7 @@ public void should_add_a_parameter_when_Required_set_true_even_if_property_has_n } [Fact] - public void should_skip_a_parameter_not_found_in_the_properties_object() + public void Should_skip_a_parameter_not_found_in_the_properties_object() { argsDictionary.Clear(); argsDictionary.Add( @@ -150,7 +150,7 @@ public void should_skip_a_parameter_not_found_in_the_properties_object() } [Fact] - public void should_add_a_parameter_not_found_in_the_properties_object_when_Required_set_to_true() + public void Should_add_a_parameter_not_found_in_the_properties_object_when_Required_set_to_true() { argsDictionary.Clear(); argsDictionary.Add( @@ -164,7 +164,7 @@ public void should_add_a_parameter_not_found_in_the_properties_object_when_Requi } [Fact] - public void should_add_a_boolean_as_a_switch_when_true() + public void Should_add_a_boolean_as_a_switch_when_true() { argsDictionary.Clear(); argsDictionary.Add( @@ -177,7 +177,7 @@ public void should_add_a_boolean_as_a_switch_when_true() } [Fact] - public void should_skip_a_boolean_as_a_switch_when_false() + public void Should_skip_a_boolean_as_a_switch_when_false() { argsDictionary.Clear(); argsDictionary.Add( @@ -190,7 +190,7 @@ public void should_skip_a_boolean_as_a_switch_when_false() } [Fact] - public void should_quote_a_value_when_QuoteValue_is_set_to_true() + public void Should_quote_a_value_when_QuoteValue_is_set_to_true() { argsDictionary.Clear(); argsDictionary.Add( @@ -204,7 +204,7 @@ public void should_quote_a_value_when_QuoteValue_is_set_to_true() } [Fact] - public void should_auto_quote_an_argument_value_with_spaces() + public void Should_auto_quote_an_argument_value_with_spaces() { argsDictionary.Clear(); argsDictionary.Add( @@ -213,11 +213,11 @@ public void should_auto_quote_an_argument_value_with_spaces() { ArgumentOption = "-command " }); - buildConfigs().ShouldEqual("-command \"{0}\"".format_with(configuration.CommandName)); + buildConfigs().ShouldEqual("-command \"{0}\"".FormatWith(configuration.CommandName)); } [Fact] - public void should_not_quote_an_argument_option_with_spaces() + public void Should_not_quote_an_argument_option_with_spaces() { argsDictionary.Clear(); argsDictionary.Add( @@ -231,7 +231,7 @@ public void should_not_quote_an_argument_option_with_spaces() } [Fact] - public void should_use_only_the_value_when_UseValueOnly_is_set_to_true() + public void Should_use_only_the_value_when_UseValueOnly_is_set_to_true() { argsDictionary.Clear(); argsDictionary.Add( @@ -245,7 +245,7 @@ public void should_use_only_the_value_when_UseValueOnly_is_set_to_true() } [Fact] - public void should_use_only_the_value_when_UseValueOnly_and_Required_is_set_to_true() + public void Should_use_only_the_value_when_UseValueOnly_and_Required_is_set_to_true() { argsDictionary.Clear(); argsDictionary.Add( @@ -261,7 +261,7 @@ public void should_use_only_the_value_when_UseValueOnly_and_Required_is_set_to_t } [Fact] - public void should_not_add_a_value_when_UseValueOnly_is_set_to_true_and_no_value_is_set() + public void Should_not_add_a_value_when_UseValueOnly_is_set_to_true_and_no_value_is_set() { argsDictionary.Clear(); argsDictionary.Add( @@ -275,7 +275,7 @@ public void should_not_add_a_value_when_UseValueOnly_is_set_to_true_and_no_value } [Fact] - public void should_separate_arguments_by_one_space() + public void Should_separate_arguments_by_one_space() { argsDictionary.Clear(); argsDictionary.Add( @@ -295,7 +295,7 @@ public void should_separate_arguments_by_one_space() } [Fact] - public void should_add_items_in_order_based_on_the_dictionary() + public void Should_add_items_in_order_based_on_the_dictionary() { argsDictionary.Clear(); argsDictionary.Add( @@ -336,7 +336,7 @@ public void should_add_items_in_order_based_on_the_dictionary() Required = true }); - buildConfigs().ShouldEqual("install -outputdirectory \"bob\" -source \"{0}\" -noninteractive -nocache".format_with(configuration.Sources)); + buildConfigs().ShouldEqual("install -outputdirectory \"bob\" -source \"{0}\" -noninteractive -nocache".FormatWith(configuration.Sources)); } } } diff --git a/src/chocolatey.tests/infrastructure/commands/PowershellExecutorSpecs.cs b/src/chocolatey.tests/infrastructure/commands/PowershellExecutorSpecs.cs index 6a576e4776..02adc4c890 100644 --- a/src/chocolatey.tests/infrastructure/commands/PowershellExecutorSpecs.cs +++ b/src/chocolatey.tests/infrastructure/commands/PowershellExecutorSpecs.cs @@ -36,7 +36,7 @@ public override void Context() } } - public class when_powershellExecutor_is_searching_for_powershell_locations_and_all_locations_exist : PowerShellExecutorSpecsBase + public class When_powershellExecutor_is_searching_for_powershell_locations_and_all_locations_exist : PowerShellExecutorSpecsBase { private string result = string.Empty; private readonly string expected = Environment.ExpandEnvironmentVariables("%systemroot%\\SysNative\\WindowsPowerShell\\v1.0\\powershell.exe"); @@ -44,34 +44,34 @@ public class when_powershellExecutor_is_searching_for_powershell_locations_and_a public override void Context() { base.Context(); - FileSystem.Setup(fs => fs.file_exists(It.IsAny())).Returns(true); + FileSystem.Setup(fs => fs.FileExists(It.IsAny())).Returns(true); } public override void Because() { - result = PowershellExecutor.get_powershell_location(FileSystem.Object); + result = PowershellExecutor.GetPowerShellLocation(FileSystem.Object); } [Fact] - public void should_not_return_null() + public void Should_not_return_null() { result.ShouldNotBeNull(); } [Fact] - public void should_find_powershell() + public void Should_find_powershell() { result.ShouldNotBeEmpty(); } [Fact] - public void should_return_the_sysnative_path() + public void Should_return_the_sysnative_path() { result.ShouldEqual(expected); } } - public class when_powershellExecutor_is_searching_for_powershell_locations_there_is_no_sysnative : PowerShellExecutorSpecsBase + public class When_powershellExecutor_is_searching_for_powershell_locations_there_is_no_sysnative : PowerShellExecutorSpecsBase { private string result = string.Empty; private readonly string expected = Environment.ExpandEnvironmentVariables("%systemroot%\\System32\\WindowsPowerShell\\v1.0\\powershell.exe"); @@ -80,28 +80,28 @@ public override void Context() { base.Context(); - FileSystem.Setup(fs => fs.file_exists(expected)).Returns(true); - FileSystem.Setup(fs => fs.file_exists(It.Is(v => v != expected))).Returns(false); + FileSystem.Setup(fs => fs.FileExists(expected)).Returns(true); + FileSystem.Setup(fs => fs.FileExists(It.Is(v => v != expected))).Returns(false); } public override void Because() { - result = PowershellExecutor.get_powershell_location(FileSystem.Object); + result = PowershellExecutor.GetPowerShellLocation(FileSystem.Object); } [Fact] - public void should_return_system32_path() + public void Should_return_system32_path() { result.ShouldEqual(expected); } } - public class when_powershellExecutor_is_searching_for_powershell_locations_and_powershell_is_not_found : PowerShellExecutorSpecsBase + public class When_powershellExecutor_is_searching_for_powershell_locations_and_powershell_is_not_found : PowerShellExecutorSpecsBase { public override void Context() { base.Context(); - FileSystem.Setup(fs => fs.file_exists(It.IsAny())).Returns(false); + FileSystem.Setup(fs => fs.FileExists(It.IsAny())).Returns(false); } public override void Because() @@ -110,9 +110,9 @@ public override void Because() } [Fact] - public void should_throw_an_error() + public void Should_throw_an_error() { - Assert.Throws(() => PowershellExecutor.get_powershell_location(FileSystem.Object)); + Assert.Throws(() => PowershellExecutor.GetPowerShellLocation(FileSystem.Object)); } } } diff --git a/src/chocolatey.tests/infrastructure/configuration/ConfigSpecs.cs b/src/chocolatey.tests/infrastructure/configuration/ConfigSpecs.cs index 4606592b51..952ab866f3 100644 --- a/src/chocolatey.tests/infrastructure/configuration/ConfigSpecs.cs +++ b/src/chocolatey.tests/infrastructure/configuration/ConfigSpecs.cs @@ -26,24 +26,24 @@ public abstract class ConfigSpecsBase : TinySpec { public override void Context() { - Config.initialize_with(new ChocolateyConfiguration()); + Config.InitializeWith(new ChocolateyConfiguration()); } } - public class when_Config_is_set_normally : ConfigSpecsBase + public class When_Config_is_set_normally : ConfigSpecsBase { public override void Because() { } [Fact] - public void should_be_of_type_ChocolateyConfiguration() + public void Should_be_of_type_ChocolateyConfiguration() { - Config.get_configuration_settings().ShouldBeType(); + Config.GetConfigurationSettings().ShouldBeType(); } } - public class when_Config_is_overridden : ConfigSpecsBase + public class When_Config_is_overridden : ConfigSpecsBase { private class LocalConfig : ChocolateyConfiguration { @@ -51,13 +51,13 @@ private class LocalConfig : ChocolateyConfiguration public override void Because() { - Config.initialize_with(new LocalConfig()); + Config.InitializeWith(new LocalConfig()); } [Fact] - public void should_use_the_overridden_type() + public void Should_use_the_overridden_type() { - Config.get_configuration_settings().ShouldBeType(); + Config.GetConfigurationSettings().ShouldBeType(); } } } diff --git a/src/chocolatey.tests/infrastructure/cryptography/CryptoHashProviderSpecs.cs b/src/chocolatey.tests/infrastructure/cryptography/CryptoHashProviderSpecs.cs index 003248166c..b11a7714a8 100644 --- a/src/chocolatey.tests/infrastructure/cryptography/CryptoHashProviderSpecs.cs +++ b/src/chocolatey.tests/infrastructure/cryptography/CryptoHashProviderSpecs.cs @@ -39,7 +39,7 @@ public override void Context() } } - public class when_HashProvider_provides_a_hash : CryptoHashProviderSpecsBase + public class When_HashProvider_provides_a_hash : CryptoHashProviderSpecsBase { private string result; private readonly string filePath = "c:\\path\\does\\not\\matter.txt"; @@ -48,17 +48,17 @@ public class when_HashProvider_provides_a_hash : CryptoHashProviderSpecsBase public override void Context() { base.Context(); - FileSystem.Setup(x => x.file_exists(It.IsAny())).Returns(true); - FileSystem.Setup(x => x.read_file_bytes(filePath)).Returns(byteArray); + FileSystem.Setup(x => x.FileExists(It.IsAny())).Returns(true); + FileSystem.Setup(x => x.ReadFileBytes(filePath)).Returns(byteArray); } public override void Because() { - result = Provider.hash_file(filePath); + result = Provider.ComputeFileHash(filePath); } [Fact] - public void should_provide_the_correct_hash_based_on_a_checksum() + public void Should_provide_the_correct_hash_based_on_a_checksum() { var expected = BitConverter.ToString(SHA256.Create().ComputeHash(byteArray)).Replace("-", string.Empty); @@ -66,7 +66,7 @@ public void should_provide_the_correct_hash_based_on_a_checksum() } } - public class when_HashProvider_attempts_to_provide_a_hash_for_a_file_over_2GB : CryptoHashProviderSpecsBase + public class When_HashProvider_attempts_to_provide_a_hash_for_a_file_over_2GB : CryptoHashProviderSpecsBase { private string result; private readonly string filePath = "c:\\path\\does\\not\\matter.txt"; @@ -78,30 +78,30 @@ public override void Context() base.Context(); Provider = new CryptoHashProvider(FileSystem.Object, _hashAlgorithm.Object); - FileSystem.Setup(x => x.file_exists(It.IsAny())).Returns(true); - FileSystem.Setup(x => x.read_file_bytes(filePath)).Returns(byteArray); + FileSystem.Setup(x => x.FileExists(It.IsAny())).Returns(true); + FileSystem.Setup(x => x.ReadFileBytes(filePath)).Returns(byteArray); _hashAlgorithm.Setup(x => x.ComputeHash(byteArray)).Throws(); //IO.IO_FileTooLong2GB (over Int32.MaxValue) } public override void Because() { - result = Provider.hash_file(filePath); + result = Provider.ComputeFileHash(filePath); } [Fact] - public void should_log_a_warning() + public void Should_log_a_warning() { MockLogger.MessagesFor(LogLevel.Warn).Count.ShouldEqual(1); } [Fact] - public void should_not_throw_an_error_itself() + public void Should_not_throw_an_error_itself() { //this handles itself } [Fact] - public void should_provide_an_unchanging_hash_for_a_file_too_big_to_hash() + public void Should_provide_an_unchanging_hash_for_a_file_too_big_to_hash() { result.ShouldEqual(ApplicationParameters.HashProviderFileTooBig); } diff --git a/src/chocolatey.tests/infrastructure/events/EventSubscriptionManagerSpecs.cs b/src/chocolatey.tests/infrastructure/events/EventSubscriptionManagerSpecs.cs index 792317b6e3..f21c45ba0d 100644 --- a/src/chocolatey.tests/infrastructure/events/EventSubscriptionManagerSpecs.cs +++ b/src/chocolatey.tests/infrastructure/events/EventSubscriptionManagerSpecs.cs @@ -39,7 +39,7 @@ public override void Context() } } - public class when_using_eventSubscriptionManager_to_subscribe_to_an_event : EventSubscriptionManagerSpecsBase + public class When_using_eventSubscriptionManager_to_subscribe_to_an_event : EventSubscriptionManagerSpecsBase { private bool _wasCalled; private FakeEvent _localFakeEvent; @@ -47,7 +47,7 @@ public class when_using_eventSubscriptionManager_to_subscribe_to_an_event : Even public override void Context() { base.Context(); - SubscriptionManager.subscribe( + SubscriptionManager.Subscribe( x => { _wasCalled = true; @@ -59,35 +59,35 @@ public override void Context() public override void Because() { - SubscriptionManager.publish(Event); + SubscriptionManager.Publish(Event); } [Fact] - public void should_have_called_the_action() + public void Should_have_called_the_action() { _wasCalled.ShouldBeTrue(); } [Fact] - public void should_have_passed_the_message() + public void Should_have_passed_the_message() { _localFakeEvent.ShouldEqual(Event); } [Fact] - public void should_have_passed_the_name_correctly() + public void Should_have_passed_the_name_correctly() { _localFakeEvent.Name.ShouldEqual("yo"); } [Fact] - public void should_have_passed_the_digits_correctly() + public void Should_have_passed_the_digits_correctly() { _localFakeEvent.Digits.ShouldEqual(12d); } } - public class when_using_eventSubscriptionManager_with_long_running_event_subscriber : EventSubscriptionManagerSpecsBase + public class When_using_eventSubscriptionManager_with_long_running_event_subscriber : EventSubscriptionManagerSpecsBase { private bool _wasCalled; private FakeEvent _localFakeEvent; @@ -95,7 +95,7 @@ public class when_using_eventSubscriptionManager_with_long_running_event_subscri public override void Context() { base.Context(); - SubscriptionManager.subscribe( + SubscriptionManager.Subscribe( m => { //stuff is happening @@ -110,24 +110,24 @@ public override void Context() public override void Because() { - SubscriptionManager.publish(Event); + SubscriptionManager.Publish(Event); } [Fact] - public void should_wait_the_event_to_complete() + public void Should_wait_the_event_to_complete() { Console.WriteLine("event complete should be above this"); _wasCalled.ShouldBeTrue(); } [Fact] - public void should_have_passed_the_message() + public void Should_have_passed_the_message() { _localFakeEvent.ShouldEqual(Event); } } - public class when_using_eventSubscriptionManager_to_subscribe_to_an_event_with_a_filter_that_the_event_satisfies : EventSubscriptionManagerSpecsBase + public class When_using_eventSubscriptionManager_to_subscribe_to_an_event_with_a_filter_that_the_event_satisfies : EventSubscriptionManagerSpecsBase { private bool _wasCalled; private FakeEvent _localFakeEvent; @@ -135,7 +135,7 @@ public class when_using_eventSubscriptionManager_to_subscribe_to_an_event_with_a public override void Context() { base.Context(); - SubscriptionManager.subscribe( + SubscriptionManager.Subscribe( x => { _wasCalled = true; @@ -147,35 +147,35 @@ public override void Context() public override void Because() { - SubscriptionManager.publish(Event); + SubscriptionManager.Publish(Event); } [Fact] - public void should_have_called_the_action() + public void Should_have_called_the_action() { _wasCalled.ShouldBeTrue(); } [Fact] - public void should_have_passed_the_message() + public void Should_have_passed_the_message() { _localFakeEvent.ShouldEqual(Event); } [Fact] - public void should_have_passed_the_name_correctly() + public void Should_have_passed_the_name_correctly() { _localFakeEvent.Name.ShouldEqual("yo"); } [Fact] - public void should_have_passed_the_digits_correctly() + public void Should_have_passed_the_digits_correctly() { _localFakeEvent.Digits.ShouldEqual(12d); } } - public class when_using_eventSubscriptionManager_to_subscribe_to_an_event_with_a_filter_that_the_event_does_not_satisfy : EventSubscriptionManagerSpecsBase + public class When_using_eventSubscriptionManager_to_subscribe_to_an_event_with_a_filter_that_the_event_does_not_satisfy : EventSubscriptionManagerSpecsBase { private bool _wasCalled; private FakeEvent _localFakeEvent; @@ -183,7 +183,7 @@ public class when_using_eventSubscriptionManager_to_subscribe_to_an_event_with_a public override void Context() { base.Context(); - SubscriptionManager.subscribe( + SubscriptionManager.Subscribe( x => { _wasCalled = true; @@ -195,23 +195,23 @@ public override void Context() public override void Because() { - SubscriptionManager.publish(Event); + SubscriptionManager.Publish(Event); } [Fact] - public void should_not_have_called_the_action() + public void Should_not_have_called_the_action() { _wasCalled.ShouldBeFalse(); } [Fact] - public void should_not_have_passed_the_message() + public void Should_not_have_passed_the_message() { _localFakeEvent.ShouldNotEqual(Event); } } - public class when_using_eventSubscriptionManager_and_multiple_parties_subscribe_to_the_same_event : EventSubscriptionManagerSpecsBase + public class When_using_eventSubscriptionManager_and_multiple_parties_subscribe_to_the_same_event : EventSubscriptionManagerSpecsBase { private IList _list; @@ -229,11 +229,11 @@ public override void Context() public override void Because() { - SubscriptionManager.publish(Event); + SubscriptionManager.Publish(Event); } } - public class when_using_eventSubscriptionManager_to_send_a_null_event_message : EventSubscriptionManagerSpecsBase + public class When_using_eventSubscriptionManager_to_send_a_null_event_message : EventSubscriptionManagerSpecsBase { private bool _errored; @@ -241,7 +241,7 @@ public override void Because() { try { - SubscriptionManager.publish(null); + SubscriptionManager.Publish(null); } catch (Exception) { @@ -250,9 +250,9 @@ public override void Because() } [Fact] - public void should_throw_an_error() + public void Should_throw_an_error() { - Assert.Throws(() => SubscriptionManager.publish(null)); + Assert.Throws(() => SubscriptionManager.Publish(null)); _errored.ShouldBeTrue(); } } diff --git a/src/chocolatey.tests/infrastructure/events/context/FakeSubscriber.cs b/src/chocolatey.tests/infrastructure/events/context/FakeSubscriber.cs index 4bbc4e8f59..eae6170814 100644 --- a/src/chocolatey.tests/infrastructure/events/context/FakeSubscriber.cs +++ b/src/chocolatey.tests/infrastructure/events/context/FakeSubscriber.cs @@ -23,7 +23,7 @@ public class FakeSubscriber { public FakeSubscriber(IEventSubscriptionManagerService subscriptionManager) { - subscriptionManager.subscribe( + subscriptionManager.Subscribe( x => { WasCalled = true; diff --git a/src/chocolatey.tests/infrastructure/filesystem/DotNetFileSystemSpecs.cs b/src/chocolatey.tests/infrastructure/filesystem/DotNetFileSystemSpecs.cs index 8eae702d01..39a7ccf298 100644 --- a/src/chocolatey.tests/infrastructure/filesystem/DotNetFileSystemSpecs.cs +++ b/src/chocolatey.tests/infrastructure/filesystem/DotNetFileSystemSpecs.cs @@ -38,7 +38,7 @@ public override void Context() } } - public class when_doing_file_system_path_operations_with_dotNetFileSystem : DotNetFileSystemSpecsBase + public class When_doing_file_system_path_operations_with_dotNetFileSystem : DotNetFileSystemSpecsBase { public override void Because() { @@ -47,38 +47,38 @@ public override void Because() [Fact] public void GetFullPath_should_return_the_full_path_to_an_item() { - FileSystem.get_full_path("test.txt").ShouldEqual(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "test.txt")); + FileSystem.GetFullPath("test.txt").ShouldEqual(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "test.txt")); } [Fact] public void GetFileNameWithoutExtension_should_return_a_file_name_without_an_extension() { - FileSystem.get_file_name_without_extension("test.txt").ShouldEqual("test"); + FileSystem.GetFilenameWithoutExtension("test.txt").ShouldEqual("test"); } [Fact] public void GetFileNameWithoutExtension_should_return_a_file_name_without_an_extension_even_with_a_full_path() { - FileSystem.get_file_name_without_extension("C:\\temp\\test.txt").ShouldEqual("test"); + FileSystem.GetFilenameWithoutExtension("C:\\temp\\test.txt").ShouldEqual("test"); } [Fact] public void GetExtension_should_return_the_extension_of_the_filename() { - FileSystem.get_file_extension("test.txt").ShouldEqual(".txt"); + FileSystem.GetFileExtension("test.txt").ShouldEqual(".txt"); } [Fact] public void GetExtension_should_return_the_extension_of_the_filename_even_with_a_full_path() { - FileSystem.get_file_extension("C:\\temp\\test.txt").ShouldEqual(".txt"); + FileSystem.GetFileExtension("C:\\temp\\test.txt").ShouldEqual(".txt"); } [Fact] public void GetDirectoryName_should_return_the_directory_of_the_path_to_the_file() { - FileSystem.get_directory_name("C:\\temp\\test.txt").ShouldEqual( - Platform.get_platform() == PlatformType.Windows + FileSystem.GetDirectoryName("C:\\temp\\test.txt").ShouldEqual( + Platform.GetPlatform() == PlatformType.Windows ? "C:\\temp" : "C:/temp"); } @@ -86,8 +86,8 @@ public void GetDirectoryName_should_return_the_directory_of_the_path_to_the_file [Fact] public void Combine_should_combine_the_file_paths_of_all_the_included_items_together() { - FileSystem.combine_paths("C:\\temp", "yo", "filename.txt").ShouldEqual( - Platform.get_platform() == PlatformType.Windows + FileSystem.CombinePaths("C:\\temp", "yo", "filename.txt").ShouldEqual( + Platform.GetPlatform() == PlatformType.Windows ? "C:\\temp\\yo\\filename.txt" : "C:/temp/yo/filename.txt"); } @@ -95,8 +95,8 @@ public void Combine_should_combine_the_file_paths_of_all_the_included_items_toge [Fact] public void Combine_should_combine_when_paths_have_backslashes_in_subpaths() { - FileSystem.combine_paths("C:\\temp", "yo\\timmy", "filename.txt").ShouldEqual( - Platform.get_platform() == PlatformType.Windows + FileSystem.CombinePaths("C:\\temp", "yo\\timmy", "filename.txt").ShouldEqual( + Platform.GetPlatform() == PlatformType.Windows ? "C:\\temp\\yo\\timmy\\filename.txt" : "C:/temp/yo/timmy/filename.txt"); } @@ -104,8 +104,8 @@ public void Combine_should_combine_when_paths_have_backslashes_in_subpaths() [Fact] public void Combine_should_combine_when_paths_start_with_backslashes_in_subpaths() { - FileSystem.combine_paths("C:\\temp", "\\yo", "filename.txt").ShouldEqual( - Platform.get_platform() == PlatformType.Windows + FileSystem.CombinePaths("C:\\temp", "\\yo", "filename.txt").ShouldEqual( + Platform.GetPlatform() == PlatformType.Windows ? "C:\\temp\\yo\\filename.txt" : "C:/temp/yo/filename.txt"); } @@ -113,8 +113,8 @@ public void Combine_should_combine_when_paths_start_with_backslashes_in_subpaths [Fact] public void Combine_should_combine_when_paths_start_with_forwardslashes_in_subpaths() { - FileSystem.combine_paths("C:\\temp", "/yo", "filename.txt").ShouldEqual( - Platform.get_platform() == PlatformType.Windows + FileSystem.CombinePaths("C:\\temp", "/yo", "filename.txt").ShouldEqual( + Platform.GetPlatform() == PlatformType.Windows ? "C:\\temp\\yo\\filename.txt" : "C:/temp/yo/filename.txt"); } @@ -122,13 +122,13 @@ public void Combine_should_combine_when_paths_start_with_forwardslashes_in_subpa [Fact] public void Combine_should_error_if_any_path_but_the_primary_contains_colon() { - Assert.That(() => FileSystem.combine_paths("C:\\temp", "C:"), + Assert.That(() => FileSystem.CombinePaths("C:\\temp", "C:"), Throws.TypeOf() .And.Message.StartsWith("Cannot combine a path with")); } } - public class when_finding_paths_to_executables_with_dotNetFileSystem : DotNetFileSystemSpecsBase + public class When_finding_paths_to_executables_with_dotNetFileSystem : DotNetFileSystemSpecsBase { public Mock _environment = new Mock(); @@ -138,9 +138,9 @@ public override void Context() _environment.Setup(x => x.GetEnvironmentVariable(ApplicationParameters.Environment.PathExtensions)).Returns(".COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC;.CPL"); _environment.Setup(x => x.GetEnvironmentVariable(ApplicationParameters.Environment.Path)).Returns( @"C:\ProgramData\Chocolatey\bin{0}C:\Program Files\Microsoft\Web Platform Installer\{0}C:\Users\yes\AppData\Roaming\Boxstarter{0}C:\tools\ChocolateyPackageUpdater{0}C:\Windows\system32{0}C:\Windows{0}C:\Windows\System32\Wbem{0}C:\Windows\System32\WindowsPowerShell\v1.0\{0}" - .format_with(Path.PathSeparator) + .FormatWith(Path.PathSeparator) ); - FileSystem.initialize_with(new Lazy(() => _environment.Object)); + FileSystem.InitializeWith(new Lazy(() => _environment.Object)); } public override void Because() @@ -155,8 +155,8 @@ private void reset() [Fact] public void GetExecutablePath_should_find_existing_executable() { - FileSystem.get_executable_path("cmd").to_lower().ShouldEqual( - Platform.get_platform() == PlatformType.Windows + FileSystem.GetExecutablePath("cmd").ToLowerSafe().ShouldEqual( + Platform.GetPlatform() == PlatformType.Windows ? "c:\\windows\\system32\\cmd.exe" : "cmd", StringComparer.OrdinalIgnoreCase @@ -166,8 +166,8 @@ public void GetExecutablePath_should_find_existing_executable() [Fact] public void GetExecutablePath_should_find_existing_executable_with_extension() { - FileSystem.get_executable_path("cmd.exe").to_lower().ShouldEqual( - Platform.get_platform() == PlatformType.Windows + FileSystem.GetExecutablePath("cmd.exe").ToLowerSafe().ShouldEqual( + Platform.GetPlatform() == PlatformType.Windows ? "c:\\windows\\system32\\cmd.exe" : "cmd.exe", StringComparer.OrdinalIgnoreCase @@ -177,23 +177,23 @@ public void GetExecutablePath_should_find_existing_executable_with_extension() [Fact] public void GetExecutablePath_should_return_same_value_when_executable_is_not_found() { - FileSystem.get_executable_path("daslakjsfdasdfwea").ShouldEqual("daslakjsfdasdfwea"); + FileSystem.GetExecutablePath("daslakjsfdasdfwea").ShouldEqual("daslakjsfdasdfwea"); } [Fact] public void GetExecutablePath_should_return_empty_string_when_value_is_null() { - FileSystem.get_executable_path(null).ShouldEqual(string.Empty); + FileSystem.GetExecutablePath(null).ShouldEqual(string.Empty); } [Fact] public void GetExecutablePath_should_return_empty_string_when_value_is_empty_string() { - FileSystem.get_executable_path(string.Empty).ShouldEqual(string.Empty); + FileSystem.GetExecutablePath(string.Empty).ShouldEqual(string.Empty); } } - public class when_finding_paths_to_executables_with_dotNetFileSystem_with_empty_path_extensions : DotNetFileSystemSpecsBase + public class When_finding_paths_to_executables_with_dotNetFileSystem_with_empty_path_extensions : DotNetFileSystemSpecsBase { public Mock _environment = new Mock(); @@ -203,9 +203,9 @@ public override void Context() _environment.Setup(x => x.GetEnvironmentVariable(ApplicationParameters.Environment.PathExtensions)).Returns(string.Empty); _environment.Setup(x => x.GetEnvironmentVariable(ApplicationParameters.Environment.Path)).Returns( "/usr/local/bin{0}/usr/bin/{0}/bin{0}/usr/sbin{0}/sbin" - .format_with(Path.PathSeparator) + .FormatWith(Path.PathSeparator) ); - FileSystem.initialize_with(new Lazy(() => _environment.Object)); + FileSystem.InitializeWith(new Lazy(() => _environment.Object)); } public override void Because() @@ -215,35 +215,35 @@ public override void Because() [Fact] public void GetExecutablePath_should_find_existing_executable() { - if (Platform.get_platform() == PlatformType.Windows) + if (Platform.GetPlatform() == PlatformType.Windows) { - FileSystem.get_executable_path("ls").ShouldEqual("ls"); + FileSystem.GetExecutablePath("ls").ShouldEqual("ls"); } else { new string[] { "/bin/ls", "/usr/bin/ls" - }.ShouldContain(FileSystem.get_executable_path("ls")); + }.ShouldContain(FileSystem.GetExecutablePath("ls")); } } [Fact] public void GetExecutablePath_should_return_same_value_when_executable_is_not_found() { - FileSystem.get_executable_path("daslakjsfdasdfwea").ShouldEqual("daslakjsfdasdfwea"); + FileSystem.GetExecutablePath("daslakjsfdasdfwea").ShouldEqual("daslakjsfdasdfwea"); } [Fact] public void GetExecutablePath_should_return_empty_string_when_value_is_null() { - FileSystem.get_executable_path(null).ShouldEqual(string.Empty); + FileSystem.GetExecutablePath(null).ShouldEqual(string.Empty); } [Fact] public void GetExecutablePath_should_return_empty_string_when_value_is_empty_string() { - FileSystem.get_executable_path(string.Empty).ShouldEqual(string.Empty); + FileSystem.GetExecutablePath(string.Empty).ShouldEqual(string.Empty); } } } diff --git a/src/chocolatey.tests/infrastructure/guards/EnsureSpecs.cs b/src/chocolatey.tests/infrastructure/guards/EnsureSpecs.cs index 79b04518d1..2db5c954c5 100644 --- a/src/chocolatey.tests/infrastructure/guards/EnsureSpecs.cs +++ b/src/chocolatey.tests/infrastructure/guards/EnsureSpecs.cs @@ -31,137 +31,137 @@ public override void Context() } } - public class when_Ensure_is_being_set_to_a_type : EnsureSpecsBase + public class When_Ensure_is_being_set_to_a_type : EnsureSpecsBase { private object result; private readonly object bob = "something"; public override void Because() { - result = Ensure.that(() => bob); + result = Ensure.That(() => bob); } [Fact] - public void should_return_a_type_of_object_for_ensuring() + public void Should_return_a_type_of_object_for_ensuring() { result.ShouldBeType>(); } [Fact] - public void should_have_the_value_specified() + public void Should_have_the_value_specified() { var bobEnsure = result as Ensure; bobEnsure.Value.ShouldEqual(bob); } } - public class when_Ensure_is_a_string_type : EnsureSpecsBase + public class When_Ensure_is_a_string_type : EnsureSpecsBase { private object result; private readonly string bob = "something"; public override void Because() { - result = Ensure.that(() => bob); + result = Ensure.That(() => bob); } [Fact] - public void should_return_a_ensure_string_type() + public void Should_return_a_ensure_string_type() { result.ShouldBeType(); } [Fact] - public void should_have_the_value_specified() + public void Should_have_the_value_specified() { var bobEnsure = result as EnsureString; bobEnsure.Value.ShouldEqual(bob); } } - public class when_using_EnsureString : EnsureSpecsBase + public class When_using_EnsureString : EnsureSpecsBase { public override void Because() { } [Fact] - public void when_testing_a_string_against_null_value_should_fail() + public void When_testing_a_string_against_null_value_should_fail() { string test = null; - Action a = () => Ensure.that(() => test).is_not_null_or_whitespace(); + Action a = () => Ensure.That(() => test).NotNullOrWhitespace(); a.ShouldThrow(); } [Fact] - public void when_testing_a_string_against_an_empty_value_should_fail() + public void When_testing_a_string_against_an_empty_value_should_fail() { - Action a = () => Ensure.that(() => string.Empty).is_not_null_or_whitespace(); + Action a = () => Ensure.That(() => string.Empty).NotNullOrWhitespace(); a.ShouldThrow(); } [Fact] - public void when_testing_a_string_against_a_whitespace_value_should_fail() + public void When_testing_a_string_against_a_whitespace_value_should_fail() { var test = " "; - Action a = () => Ensure.that(() => test).is_not_null_or_whitespace(); + Action a = () => Ensure.That(() => test).NotNullOrWhitespace(); a.ShouldThrow(); } [Fact] - public void when_testing_a_string_against_a_non_empty_value_should_pass() + public void When_testing_a_string_against_a_non_empty_value_should_pass() { var test = "some value"; - Ensure.that(() => test).is_not_null_or_whitespace(); + Ensure.That(() => test).NotNullOrWhitespace(); } [Fact] - public void when_testing_a_string_without_expected_extension_should_fail() + public void When_testing_a_string_without_expected_extension_should_fail() { var test = "some-file.png"; - Action a = () => Ensure.that(() => test).has_any_extension(".jpg", ".bmp", ".gif"); + Action a = () => Ensure.That(() => test).HasExtension(".jpg", ".bmp", ".gif"); a.ShouldThrow(); } [Fact] - public void when_testing_a_string_with_expected_extension_should_pass() + public void When_testing_a_string_with_expected_extension_should_pass() { var test = "some-file.png"; - Ensure.that(() => test).has_any_extension(".jpg", ".bmp", ".gif", ".png"); + Ensure.That(() => test).HasExtension(".jpg", ".bmp", ".gif", ".png"); } } - public class when_using_Ensure : EnsureSpecsBase + public class When_using_Ensure : EnsureSpecsBase { public override void Because() { } [Fact] - public void when_testing_a_string_against_is_not_null_should_pass() + public void When_testing_a_string_against_is_not_null_should_pass() { string test = "value"; - Ensure.that(() => test).is_not_null(); + Ensure.That(() => test).NotNull(); } [Fact] - public void when_testing_a_null_string_against_is_not_null_should_throw_an_Argument_exception() + public void When_testing_a_null_string_against_is_not_null_should_throw_an_Argument_exception() { string test = null; object exceptionType = null; var exceptionMessage = string.Empty; try { - Ensure.that(() => test).is_not_null(); + Ensure.That(() => test).NotNull(); } catch (Exception ex) { @@ -174,21 +174,21 @@ public void when_testing_a_null_string_against_is_not_null_should_throw_an_Argum } [Fact] - public void when_testing_a_Func_against_is_not_null_should_pass() + public void When_testing_a_Func_against_is_not_null_should_pass() { Func test = () => "value"; - Ensure.that(() => test).is_not_null(); + Ensure.That(() => test).NotNull(); } [Fact] - public void when_testing_a_null_Func_against_is_not_null_should_throw_an_Argument_exception() + public void When_testing_a_null_Func_against_is_not_null_should_throw_an_Argument_exception() { Func test = null; object exceptionType = null; var exceptionMessage = string.Empty; try { - Ensure.that(() => test).is_not_null(); + Ensure.That(() => test).NotNull(); } catch (Exception ex) { @@ -201,21 +201,21 @@ public void when_testing_a_null_Func_against_is_not_null_should_throw_an_Argumen } [Fact] - public void when_testing_a_class_against_is_not_null_should_pass() + public void When_testing_a_class_against_is_not_null_should_pass() { var test = new ChocolateyConfiguration(); - Ensure.that(() => test).is_not_null(); + Ensure.That(() => test).NotNull(); } [Fact] - public void when_testing_an_uninstantiated_class_against_is_not_null_should_throw_an_Argument_exception() + public void When_testing_an_uninstantiated_class_against_is_not_null_should_throw_an_Argument_exception() { ChocolateyConfiguration test = null; object exceptionType = null; var exceptionMessage = string.Empty; try { - Ensure.that(() => test).is_not_null(); + Ensure.That(() => test).NotNull(); } catch (Exception ex) { @@ -228,14 +228,14 @@ public void when_testing_an_uninstantiated_class_against_is_not_null_should_thro } [Fact] - public void when_testing_meets_with_null_ensureFunction_against_string_value_should_throw_ArgumentNullException_on_ensureFunction() + public void When_testing_meets_with_null_ensureFunction_against_string_value_should_throw_ArgumentNullException_on_ensureFunction() { string test = "bob"; object exceptionType = null; var exceptionMessage = string.Empty; try { - Ensure.that(() => test).meets( + Ensure.That(() => test).Meets( null, (name, value) => { throw new ApplicationException("this is what we throw."); }); } @@ -250,14 +250,14 @@ public void when_testing_meets_with_null_ensureFunction_against_string_value_sho } [Fact] - public void when_testing_meets_with_null_exceptionAction_against_string_value_that_passes_should_throw_ArgumentNullException_on_exceptionAction() + public void When_testing_meets_with_null_exceptionAction_against_string_value_that_passes_should_throw_ArgumentNullException_on_exceptionAction() { string test = "bob"; object exceptionType = null; var exceptionMessage = string.Empty; try { - Ensure.that(() => test).meets( + Ensure.That(() => test).Meets( s => s == s.ToLower(), null); } @@ -273,14 +273,14 @@ public void when_testing_meets_with_null_exceptionAction_against_string_value_th } [Fact] - public void when_testing_meets_with_null_exceptionAction_against_string_value_that_fails_should_throw_ArgumentNullException_on_exceptionAction() + public void When_testing_meets_with_null_exceptionAction_against_string_value_that_fails_should_throw_ArgumentNullException_on_exceptionAction() { string test = "bob"; object exceptionType = null; var exceptionMessage = string.Empty; try { - Ensure.that(() => test).meets( + Ensure.That(() => test).Meets( s => s == s.ToUpper(), null); } @@ -296,14 +296,14 @@ public void when_testing_meets_with_null_exceptionAction_against_string_value_th } [Fact] - public void when_testing_meets_with_null_ensureFunction_against_null_value_should_throw_ArgumentNullException_on_ensureFunction() + public void When_testing_meets_with_null_ensureFunction_against_null_value_should_throw_ArgumentNullException_on_ensureFunction() { string test = null; object exceptionType = null; var exceptionMessage = string.Empty; try { - Ensure.that(() => test).meets( + Ensure.That(() => test).Meets( null, (name, value) => { throw new ApplicationException("this is what we throw."); }); } @@ -319,14 +319,14 @@ public void when_testing_meets_with_null_ensureFunction_against_null_value_shoul } [Fact] - public void when_testing_meets_with_null_exceptionAction_against_null_value_should_throw_ArgumentNullException_on_exceptionAction() + public void When_testing_meets_with_null_exceptionAction_against_null_value_should_throw_ArgumentNullException_on_exceptionAction() { string test = null; object exceptionType = null; var exceptionMessage = string.Empty; try { - Ensure.that(() => test).meets( + Ensure.That(() => test).Meets( s => s == s.ToLower(), null); } @@ -342,14 +342,14 @@ public void when_testing_meets_with_null_exceptionAction_against_null_value_shou } [Fact] - public void when_testing_meets_with_null_everything_should_throw_ArgumentNullException_on_ensureFunction() + public void When_testing_meets_with_null_everything_should_throw_ArgumentNullException_on_ensureFunction() { string test = null; object exceptionType = null; var exceptionMessage = string.Empty; try { - Ensure.that(() => test).meets( + Ensure.That(() => test).Meets( null, null); } @@ -365,7 +365,7 @@ public void when_testing_meets_with_null_everything_should_throw_ArgumentNullExc } } - public class when_testing_Ensure_meets_against_a_string_value_that_passes : EnsureSpecsBase + public class When_testing_Ensure_meets_against_a_string_value_that_passes : EnsureSpecsBase { private object exceptionType; private string exceptionMessage = string.Empty; @@ -377,7 +377,7 @@ public override void Because() try { - Ensure.that(() => test).meets( + Ensure.That(() => test).Meets( s => s == s.ToLower(), (name, value) => { @@ -393,31 +393,31 @@ public override void Because() } [Fact] - public void should_not_invoke_the_exceptionAction() + public void Should_not_invoke_the_exceptionAction() { exceptionActionInvoked.ShouldBeFalse(); } [Fact] - public void should_not_return_a_specified_exception_since_there_was_no_failure() + public void Should_not_return_a_specified_exception_since_there_was_no_failure() { exceptionType.ShouldBeNull(); } [Fact] - public void should_not_return_the_specified_error_message() + public void Should_not_return_the_specified_error_message() { exceptionMessage.ShouldNotContain("this is what we throw."); } [Fact] - public void should_not_log_an_error() + public void Should_not_log_an_error() { MockLogger.Verify(l => l.Error(It.IsAny()), Times.Never); } } - public class when_testing_Ensure_meets_against_a_string_value_that_fails : EnsureSpecsBase + public class When_testing_Ensure_meets_against_a_string_value_that_fails : EnsureSpecsBase { private object exceptionType; private string exceptionMessage = string.Empty; @@ -429,7 +429,7 @@ public override void Because() try { - Ensure.that(() => test).meets( + Ensure.That(() => test).Meets( s => s == s.ToLower(), (name, value) => { @@ -445,31 +445,31 @@ public override void Because() } [Fact] - public void should_invoke_the_exceptionAction() + public void Should_invoke_the_exceptionAction() { exceptionActionInvoked.ShouldBeTrue(); } [Fact] - public void should_return_the_specified_exception_of_type_ApplicationException() + public void Should_return_the_specified_exception_of_type_ApplicationException() { exceptionType.ShouldBeType(); } [Fact] - public void should_return_the_specified_error_message() + public void Should_return_the_specified_error_message() { exceptionMessage.ShouldContain("this is what we throw."); } [Fact] - public void should_not_log_an_error() + public void Should_not_log_an_error() { MockLogger.Verify(l => l.Error(It.IsAny()), Times.Never); } } - public class when_testing_Ensure_meets_against_a_null_value_without_guarding_the_value : EnsureSpecsBase + public class When_testing_Ensure_meets_against_a_null_value_without_guarding_the_value : EnsureSpecsBase { private object exceptionType; private string exceptionMessage = string.Empty; @@ -481,7 +481,7 @@ public override void Because() try { - Ensure.that(() => test).meets( + Ensure.That(() => test).Meets( s => s == s.ToLower(), (name, value) => { @@ -497,37 +497,37 @@ public override void Because() } [Fact] - public void should_not_invoke_the_exceptionAction() + public void Should_not_invoke_the_exceptionAction() { exceptionActionInvoked.ShouldBeFalse(); } [Fact] - public void should_throw_an_error() + public void Should_throw_an_error() { exceptionType.ShouldNotBeNull(); } [Fact] - public void should_not_return_the_specified_exception_of_type_ApplicationException() + public void Should_not_return_the_specified_exception_of_type_ApplicationException() { exceptionType.ShouldNotBeType(); } [Fact] - public void should_not_return_the_specified_error_message() + public void Should_not_return_the_specified_error_message() { exceptionMessage.ShouldNotContain("this is what we throw."); } //[Fact] - //public void should_log_an_error() + //public void Should_log_an_error() //{ // MockLogger.Verify(l => l.Error(It.IsAny()), Times.Once); //} // [Fact] - // public void should_log_the_error_we_expect() + // public void Should_log_the_error_we_expect() // { // var messages = MockLogger.MessagesFor(LogLevel.Error); // messages.ShouldNotBeEmpty(); diff --git a/src/chocolatey.tests/infrastructure/information/VersionInformationSpecs.cs b/src/chocolatey.tests/infrastructure/information/VersionInformationSpecs.cs index 66c069d19b..645d6a2e15 100644 --- a/src/chocolatey.tests/infrastructure/information/VersionInformationSpecs.cs +++ b/src/chocolatey.tests/infrastructure/information/VersionInformationSpecs.cs @@ -29,35 +29,35 @@ public override void Context() } } - public class when_calling_VersionInformation_to_get_current_assembly_version : VersionInformationSpecsBase + public class When_calling_VersionInformation_to_get_current_assembly_version : VersionInformationSpecsBase { public string result = null; public override void Because() { - result = VersionInformation.get_current_assembly_version(); + result = VersionInformation.GetCurrentAssemblyVersion(); } [Fact] - public void should_not_be_null() + public void Should_not_be_null() { result.ShouldNotBeNull(); } [Fact] - public void should_not_be_empty() + public void Should_not_be_empty() { result.ShouldNotBeEmpty(); } [Fact] - public void should_be_transferable_to_Version() + public void Should_be_transferable_to_Version() { new Version(result).ShouldNotBeNull(); } [Fact] - public void should_not_equal_zero_dot_zero_dot_zero_dot_zero() + public void Should_not_equal_zero_dot_zero_dot_zero_dot_zero() { result.ShouldNotEqual("0.0.0.0"); } diff --git a/src/chocolatey.tests/infrastructure/platforms/PlatformSpecs.cs b/src/chocolatey.tests/infrastructure/platforms/PlatformSpecs.cs index 7fccd56dbe..543cde7987 100644 --- a/src/chocolatey.tests/infrastructure/platforms/PlatformSpecs.cs +++ b/src/chocolatey.tests/infrastructure/platforms/PlatformSpecs.cs @@ -33,28 +33,28 @@ public abstract class PlatformSpecsBase : TinySpec public override void Context() { - Platform.initialize_with(new Lazy(() => MockEnvironment.Object), new Lazy(() => MockFileSystem.Object)); + Platform.InitializeWith(new Lazy(() => MockEnvironment.Object), new Lazy(() => MockFileSystem.Object)); MockEnvironment.Setup(e => e.OSVersion).Returns(Environment.OSVersion); } } - public class when_calling_Platform_get_platform : PlatformSpecsBase + public class When_calling_Platform_get_platform : PlatformSpecsBase { private PlatformType result; public override void Because() { - result = Platform.get_platform(); + result = Platform.GetPlatform(); } [Fact] - public void should_not_be_Unknown() + public void Should_not_be_Unknown() { result.ShouldNotEqual(PlatformType.Unknown); } } - public class when_calling_Platform_get_platform_on_Windows : PlatformSpecsBase + public class When_calling_Platform_get_platform_on_Windows : PlatformSpecsBase { private PlatformType result; @@ -66,17 +66,17 @@ public override void Context() public override void Because() { - result = Platform.get_platform(); + result = Platform.GetPlatform(); } [Fact] - public void should_return_Windows() + public void Should_return_Windows() { result.ShouldEqual(PlatformType.Windows); } } - public class when_calling_Platform_get_platform_on_MacOSX : PlatformSpecsBase + public class When_calling_Platform_get_platform_on_MacOSX : PlatformSpecsBase { private PlatformType result; @@ -88,17 +88,17 @@ public override void Context() public override void Because() { - result = Platform.get_platform(); + result = Platform.GetPlatform(); } [Fact] - public void should_return_Mac() + public void Should_return_Mac() { result.ShouldEqual(PlatformType.Mac); } } - public class when_calling_Platform_get_platform_on_Linux : PlatformSpecsBase + public class When_calling_Platform_get_platform_on_Linux : PlatformSpecsBase { private PlatformType result; @@ -106,22 +106,22 @@ public override void Context() { base.Context(); MockEnvironment.Setup(e => e.OSVersion).Returns(new OperatingSystem(PlatformID.Unix, new Version(2, 1, 0, 0))); - MockFileSystem.Setup(f => f.directory_exists(It.IsAny())).Returns(false); + MockFileSystem.Setup(f => f.DirectoryExists(It.IsAny())).Returns(false); } public override void Because() { - result = Platform.get_platform(); + result = Platform.GetPlatform(); } [Fact] - public void should_return_Linux() + public void Should_return_Linux() { result.ShouldEqual(PlatformType.Linux); } } - public class when_calling_Platform_get_platform_on_PlatformId_Linux_with_MacOSX_folder_structure : PlatformSpecsBase + public class When_calling_Platform_get_platform_on_PlatformId_Linux_with_MacOSX_folder_structure : PlatformSpecsBase { private PlatformType result; @@ -129,16 +129,16 @@ public override void Context() { base.Context(); MockEnvironment.Setup(e => e.OSVersion).Returns(new OperatingSystem(PlatformID.Unix, new Version(2, 1, 0, 0))); - MockFileSystem.Setup(f => f.directory_exists(It.IsAny())).Returns(true); + MockFileSystem.Setup(f => f.DirectoryExists(It.IsAny())).Returns(true); } public override void Because() { - result = Platform.get_platform(); + result = Platform.GetPlatform(); } [Fact] - public void should_return_Mac() + public void Should_return_Mac() { result.ShouldEqual(PlatformType.Mac); } diff --git a/src/chocolatey.tests/infrastructure/tokens/TokenReplacerSpecs.cs b/src/chocolatey.tests/infrastructure/tokens/TokenReplacerSpecs.cs index 61eab919b9..d3f48a2be5 100644 --- a/src/chocolatey.tests/infrastructure/tokens/TokenReplacerSpecs.cs +++ b/src/chocolatey.tests/infrastructure/tokens/TokenReplacerSpecs.cs @@ -30,7 +30,7 @@ public override void Context() } } - public class when_using_TokenReplacer : TokenReplacerSpecsBase + public class When_using_TokenReplacer : TokenReplacerSpecsBase { public ChocolateyConfiguration configuration = new ChocolateyConfiguration(); public string name = "bob"; @@ -41,73 +41,73 @@ public override void Because() } [Fact] - public void when_given_brace_brace_CommandName_brace_brace_should_replace_with_the_Name_from_the_configuration() + public void When_given_brace_brace_CommandName_brace_brace_should_replace_with_the_Name_from_the_configuration() { - TokenReplacer.replace_tokens(configuration, "Hi! My name is [[CommandName]]").ShouldEqual("Hi! My name is " + name); + TokenReplacer.ReplaceTokens(configuration, "Hi! My name is [[CommandName]]").ShouldEqual("Hi! My name is " + name); } [Fact] - public void when_given_brace_CommandName_brace_should_NOT_replace_the_value() + public void When_given_brace_CommandName_brace_should_NOT_replace_the_value() { - TokenReplacer.replace_tokens(configuration, "Hi! My name is [CommandName]").ShouldEqual("Hi! My name is [CommandName]"); + TokenReplacer.ReplaceTokens(configuration, "Hi! My name is [CommandName]").ShouldEqual("Hi! My name is [CommandName]"); } [Fact] - public void when_given_a_value_that_is_the_name_of_a_configuration_item_but_is_not_properly_tokenized_it_should_NOT_replace_the_value() + public void When_given_a_value_that_is_the_name_of_a_configuration_item_but_is_not_properly_tokenized_it_should_NOT_replace_the_value() { - TokenReplacer.replace_tokens(configuration, "Hi! My name is CommandName").ShouldEqual("Hi! My name is CommandName"); + TokenReplacer.ReplaceTokens(configuration, "Hi! My name is CommandName").ShouldEqual("Hi! My name is CommandName"); } [Fact] - public void when_given_brace_brace_commandname_brace_brace_should_replace_with_the_Name_from_the_configuration() + public void When_given_brace_brace_commandname_brace_brace_should_replace_with_the_Name_from_the_configuration() { - TokenReplacer.replace_tokens(configuration, "Hi! My name is [[commandname]]").ShouldEqual("Hi! My name is " + name); + TokenReplacer.ReplaceTokens(configuration, "Hi! My name is [[commandname]]").ShouldEqual("Hi! My name is " + name); } [Fact] - public void when_given_brace_brace_COMMANDNAME_brace_brace_should_replace_with_the_Name_from_the_configuration() + public void When_given_brace_brace_COMMANDNAME_brace_brace_should_replace_with_the_Name_from_the_configuration() { - TokenReplacer.replace_tokens(configuration, "Hi! My name is [[COMMANDNAME]]").ShouldEqual("Hi! My name is " + name); + TokenReplacer.ReplaceTokens(configuration, "Hi! My name is [[COMMANDNAME]]").ShouldEqual("Hi! My name is " + name); } [Fact] - public void when_given_brace_brace_cOMmAnDnAMe_brace_brace_should_replace_with_the_Name_from_the_configuration() + public void When_given_brace_brace_cOMmAnDnAMe_brace_brace_should_replace_with_the_Name_from_the_configuration() { - TokenReplacer.replace_tokens(configuration, "Hi! My name is [[cOMmAnDnAMe]]").ShouldEqual("Hi! My name is " + name); + TokenReplacer.ReplaceTokens(configuration, "Hi! My name is [[cOMmAnDnAMe]]").ShouldEqual("Hi! My name is " + name); } [Fact] - public void if_given_brace_brace_Version_brace_brace_should_NOT_replace_with_the_Name_from_the_configuration() + public void If_given_brace_brace_Version_brace_brace_should_NOT_replace_with_the_Name_from_the_configuration() { - TokenReplacer.replace_tokens(configuration, "Go to [[Version]]").ShouldNotContain(name); + TokenReplacer.ReplaceTokens(configuration, "Go to [[Version]]").ShouldNotContain(name); } [Fact] - public void if_given_a_value_that_is_not_set_should_return_that_value_as_string_Empty() + public void If_given_a_value_that_is_not_set_should_return_that_value_as_string_Empty() { - TokenReplacer.replace_tokens(configuration, "Go to [[Version]]").ShouldEqual("Go to " + string.Empty); + TokenReplacer.ReplaceTokens(configuration, "Go to [[Version]]").ShouldEqual("Go to " + string.Empty); } [Fact] - public void if_given_a_value_that_does_not_exist_should_return_the_original_value_unchanged() + public void If_given_a_value_that_does_not_exist_should_return_the_original_value_unchanged() { - TokenReplacer.replace_tokens(configuration, "Hi! My name is [[DataBase]]").ShouldEqual("Hi! My name is [[DataBase]]"); + TokenReplacer.ReplaceTokens(configuration, "Hi! My name is [[DataBase]]").ShouldEqual("Hi! My name is [[DataBase]]"); } [Fact] - public void if_given_an_empty_value_should_return_the_empty_value() + public void If_given_an_empty_value_should_return_the_empty_value() { - TokenReplacer.replace_tokens(configuration, "").ShouldEqual(""); + TokenReplacer.ReplaceTokens(configuration, "").ShouldEqual(""); } [Fact] - public void if_given_an_null_value_should_return_the_ll_value() + public void If_given_an_null_value_should_return_the_ll_value() { - TokenReplacer.replace_tokens(configuration, null).ShouldEqual(""); + TokenReplacer.ReplaceTokens(configuration, null).ShouldEqual(""); } } - public class when_using_TokenReplacer_with_a_Dictionary : TokenReplacerSpecsBase + public class When_using_TokenReplacer_with_a_Dictionary : TokenReplacerSpecsBase { public Dictionary tokens = new Dictionary(); private readonly string value = "sweet"; @@ -118,9 +118,9 @@ public override void Because() } [Fact] - public void when_given_a_proper_token_it_should_replace_with_the_dictionary_value() + public void When_given_a_proper_token_it_should_replace_with_the_dictionary_value() { - TokenReplacer.replace_tokens(tokens, "Hi! My name is [[dude]]").ShouldEqual("Hi! My name is " + value); + TokenReplacer.ReplaceTokens(tokens, "Hi! My name is [[dude]]").ShouldEqual("Hi! My name is " + value); } } } diff --git a/src/chocolatey.tests/infrastructure/tolerance/FaultToleranceSpecs.cs b/src/chocolatey.tests/infrastructure/tolerance/FaultToleranceSpecs.cs index e02b8c9e73..935bd0487a 100644 --- a/src/chocolatey.tests/infrastructure/tolerance/FaultToleranceSpecs.cs +++ b/src/chocolatey.tests/infrastructure/tolerance/FaultToleranceSpecs.cs @@ -31,22 +31,22 @@ public override void Context() protected void reset() { - MockLogger.reset(); + MockLogger.Reset(); } } - public class when_retrying_an_action : FaultToleranceSpecsBase + public class When_retrying_an_action : FaultToleranceSpecsBase { public override void Because() { } [Fact] - public void should_not_allow_the_number_of_retries_to_be_zero() + public void Should_not_allow_the_number_of_retries_to_be_zero() { reset(); - Action m = () => FaultTolerance.retry( + Action m = () => FaultTolerance.Retry( 0, () => { @@ -56,23 +56,23 @@ public void should_not_allow_the_number_of_retries_to_be_zero() } [Fact] - public void should_throw_an_error_if_retries_are_reached() + public void Should_throw_an_error_if_retries_are_reached() { reset(); - Action m = () => FaultTolerance.retry(2, () => { throw new Exception("YIKES"); }, waitDurationMilliseconds: 0); + Action m = () => FaultTolerance.Retry(2, () => { throw new Exception("YIKES"); }, waitDurationMilliseconds: 0); m.ShouldThrow(); } [Fact] - public void should_log_warning_each_time() + public void Should_log_warning_each_time() { reset(); try { - FaultTolerance.retry(3, () => { throw new Exception("YIKES"); }, waitDurationMilliseconds: 0); + FaultTolerance.Retry(3, () => { throw new Exception("YIKES"); }, waitDurationMilliseconds: 0); } catch { @@ -83,14 +83,14 @@ public void should_log_warning_each_time() } [Fact] - public void should_retry_the_number_of_times_specified() + public void Should_retry_the_number_of_times_specified() { reset(); var i = 0; try { - FaultTolerance.retry( + FaultTolerance.Retry( 10, () => { @@ -108,12 +108,12 @@ public void should_retry_the_number_of_times_specified() } [Fact] - public void should_return_immediately_when_successful() + public void Should_return_immediately_when_successful() { reset(); var i = 0; - FaultTolerance.retry(3, () => { i += 1; }, waitDurationMilliseconds: 0); + FaultTolerance.Retry(3, () => { i += 1; }, waitDurationMilliseconds: 0); i.ShouldEqual(1); @@ -121,18 +121,18 @@ public void should_return_immediately_when_successful() } } - public class when_wrapping_a_function_with_try_catch : FaultToleranceSpecsBase + public class When_wrapping_a_function_with_try_catch : FaultToleranceSpecsBase { public override void Because() { } [Fact] - public void should_log_an_error_message() + public void Should_log_an_error_message() { reset(); - FaultTolerance.try_catch_with_logging_exception( + FaultTolerance.TryCatchWithLoggingException( () => { throw new Exception("This is the message"); }, "You have an error" ); @@ -141,24 +141,24 @@ public void should_log_an_error_message() } [Fact] - public void should_log_the_expected_error_message() + public void Should_log_the_expected_error_message() { reset(); - FaultTolerance.try_catch_with_logging_exception( + FaultTolerance.TryCatchWithLoggingException( () => { throw new Exception("This is the message"); }, "You have an error" ); - MockLogger.MessagesFor(LogLevel.Error)[0].ShouldEqual("You have an error:{0} This is the message".format_with(Environment.NewLine)); + MockLogger.MessagesFor(LogLevel.Error)[0].ShouldEqual("You have an error:{0} This is the message".FormatWith(Environment.NewLine)); } [Fact] - public void should_log_a_warning_message_when_set_to_warn() + public void Should_log_a_warning_message_when_set_to_warn() { reset(); - FaultTolerance.try_catch_with_logging_exception( + FaultTolerance.TryCatchWithLoggingException( () => { throw new Exception("This is the message"); }, "You have an error", logWarningInsteadOfError: true @@ -168,11 +168,11 @@ public void should_log_a_warning_message_when_set_to_warn() } [Fact] - public void should_throw_an_error_if_throwError_set_to_true() + public void Should_throw_an_error_if_throwError_set_to_true() { reset(); - Action m = () => FaultTolerance.try_catch_with_logging_exception( + Action m = () => FaultTolerance.TryCatchWithLoggingException( () => { throw new Exception("This is the message"); }, "You have an error", throwError: true @@ -182,11 +182,11 @@ public void should_throw_an_error_if_throwError_set_to_true() } [Fact] - public void should_still_throw_an_error_when_warn_is_set_if_throwError_set_to_true() + public void Should_still_throw_an_error_when_warn_is_set_if_throwError_set_to_true() { reset(); - Action m = () => FaultTolerance.try_catch_with_logging_exception( + Action m = () => FaultTolerance.TryCatchWithLoggingException( () => { throw new Exception("This is the message"); }, "You have an error", logWarningInsteadOfError: true, diff --git a/src/chocolatey.tests/packages.config b/src/chocolatey.tests/packages.config index 49eaa94486..7b628043aa 100644 --- a/src/chocolatey.tests/packages.config +++ b/src/chocolatey.tests/packages.config @@ -1,18 +1,18 @@  - - - - - - - - - - - - - + + + + + + + + + + + + + diff --git a/src/chocolatey/AssemblyExtensions.cs b/src/chocolatey/AssemblyExtensions.cs index 4f37aedb6b..dd9330e67c 100644 --- a/src/chocolatey/AssemblyExtensions.cs +++ b/src/chocolatey/AssemblyExtensions.cs @@ -36,7 +36,7 @@ public static class AssemblyExtensions /// The assembly. /// The manifest resource stream location. /// - public static string get_manifest_string(this IAssembly assembly, string manifestResourceStreamLocation) + public static string GetManifestString(this IAssembly assembly, string manifestResourceStreamLocation) { string manifestFileText = ""; @@ -62,7 +62,7 @@ public static string get_manifest_string(this IAssembly assembly, string manifes /// The assembly. /// The manifest resource stream location. /// - public static Stream get_manifest_stream(this IAssembly assembly, string manifestResourceStreamLocation) + public static Stream GetManifestStream(this IAssembly assembly, string manifestResourceStreamLocation) { return assembly.GetManifestResourceStream(manifestResourceStreamLocation); } @@ -73,14 +73,14 @@ public static Stream get_manifest_stream(this IAssembly assembly, string manifes /// The assembly. /// /// Borrowed heavily from http://dhvik.blogspot.com/2009/05/assemblynamegetpublickeytoken-tostring.html - public static string get_public_key_token(this IAssembly assembly) + public static string GetPublicKeyToken(this IAssembly assembly) { if (assembly == null) return string.Empty; - return assembly.GetName().get_public_key_token(); + return assembly.GetName().GetPublicKeyTokenString(); } - public static string get_public_key_token(this AssemblyName assemblyName) + public static string GetPublicKeyTokenString(this AssemblyName assemblyName) { if (assemblyName == null) return string.Empty; @@ -91,7 +91,7 @@ public static string get_public_key_token(this AssemblyName assemblyName) return publicKeyToken.Select(x => x.ToString("x2")).Aggregate((x, y) => x + y); } - public static IEnumerable get_loadable_types(this IAssembly assembly) + public static IEnumerable GetLoadableTypes(this IAssembly assembly) { // Code originates from the following stack overflow answer: https://stackoverflow.com/a/11915414 if (assembly == null) @@ -109,14 +109,14 @@ public static IEnumerable get_loadable_types(this IAssembly assembly) } } - public static IEnumerable get_extension_modules(this IAssembly assembly) + public static IEnumerable GetExtensionModules(this IAssembly assembly) { var result = new List(); "chocolatey".Log().Debug("Gathering exported extension registration modules!"); var registrationTypes = assembly - .get_loadable_types() + .GetLoadableTypes() .Where(t => t.IsClass && !t.IsAbstract && !t.IsGenericType && typeof(IExtensionModule).IsAssignableFrom(t)); foreach (var extensionType in registrationTypes) @@ -138,5 +138,31 @@ public static IEnumerable get_extension_modules(this IAssembly return result; } + +#pragma warning disable IDE1006 + [Obsolete("This overload is deprecated and will be removed in v3.")] + public static string get_manifest_string(this IAssembly assembly, string manifestResourceStreamLocation) + => GetManifestString(assembly, manifestResourceStreamLocation); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public static Stream get_manifest_stream(this IAssembly assembly, string manifestResourceStreamLocation) + => GetManifestStream(assembly, manifestResourceStreamLocation); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public static string get_public_key_token(this IAssembly assembly) + => GetPublicKeyToken(assembly); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public static string get_public_key_token(this AssemblyName assemblyName) + => GetPublicKeyTokenString(assemblyName); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public static IEnumerable get_loadable_types(this IAssembly assembly) + => GetLoadableTypes(assembly); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public static IEnumerable get_extension_modules(this IAssembly assembly) + => GetExtensionModules(assembly); +#pragma warning restore IDE1006 } } diff --git a/src/chocolatey/BannedSymbols.txt b/src/chocolatey/BannedSymbols.txt index e0a2fa1218..80cc711ec0 100644 --- a/src/chocolatey/BannedSymbols.txt +++ b/src/chocolatey/BannedSymbols.txt @@ -1,4 +1,10 @@ -M:NuGet.Versioning.SemanticVersion.ToFullString;Use to_full_string() extension method instead. -M:Chocolatey.NuGet.Versioning.SemanticVersion.ToFullString();Use to_full_string() extension method instead. -M:NuGet.Versioning.SemanticVersion.ToNormalizedString;Use to_normalized_string() extension method instead. -M:Chocolatey.NuGet.Versioning.SemanticVersion.ToNormalizedString();Use to_normalized_string() extension method instead. \ No newline at end of file +M:NuGet.Versioning.SemanticVersion.ToFullString;Use ToFullStringChecked() extension method instead. +M:Chocolatey.NuGet.Versioning.SemanticVersion.ToFullString();Use ToFullStringChecked() extension method instead. +M:NuGet.Versioning.SemanticVersion.ToNormalizedString;Use ToNormalizedStringChecked() extension method instead. +M:Chocolatey.NuGet.Versioning.SemanticVersion.ToNormalizedString();Use ToNormalizedStringChecked() extension method instead. +M:System.StringComparer.InvariantCultureIgnoreCase;Use OrdinalIgnoreCase comparer instead. +M:NuGet.Protocol.Core.Types.SourceRepository.GetResource`1;Get the NuGet cached endpoint. +M:NuGet.Protocol.Core.Types.SourceRepository.GetResourceAsync`1;Get the NuGet cached endpoint. +M:System.String.Equals(System.String); Use extension method IsEqualTo to make case insensitive comparison. +M:System.String.Equals(System.String,System.String); Use overload to pass in StringComparison, or use IsEqualTo overload for case insensitive comparison. +M:System.String.Compare(System.String,System.String); Use overload to pass in StringComparison. diff --git a/src/chocolatey/EnumExtensions.cs b/src/chocolatey/EnumExtensions.cs index 74096815b7..de8d879604 100644 --- a/src/chocolatey/EnumExtensions.cs +++ b/src/chocolatey/EnumExtensions.cs @@ -30,7 +30,7 @@ public static class EnumExtensions /// Gets the description [Description("")] or ToString() value of an enumeration. /// /// The enumeration item. - public static string get_description_or_value(this Enum enumeration) + public static string DescriptionOrValue(this Enum enumeration) { string description = enumeration.ToString(); @@ -50,19 +50,14 @@ public static string get_description_or_value(this Enum enumeration) return description; } - public static TEnum parse_enum_from_description(this string description) - where TEnum : struct + public static TEnum ParseEnumDescription(this string description) + where TEnum : struct, Enum { - if (!typeof (TEnum).IsEnum) - { - throw new InvalidEnumArgumentException("TEnum must be of type Enum"); - } - Type type = typeof (TEnum); foreach (var fieldInfo in type.GetFields()) { var attr = fieldInfo.GetCustomAttributes(typeof (DescriptionAttribute), false).Cast().SingleOrDefault(); - if (attr != null && attr.Description.Equals(description)) + if (attr != null && attr.Description.Equals(description, StringComparison.Ordinal)) { return (TEnum) fieldInfo.GetValue(null); } @@ -70,5 +65,16 @@ public static TEnum parse_enum_from_description(this string description) return default(TEnum); } + +#pragma warning disable IDE1006 + [Obsolete("This overload is deprecated and will be removed in v3.")] + public static string get_description_or_value(this Enum enumeration) + => DescriptionOrValue(enumeration); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public static TEnum parse_enum_from_description(this string description) + where TEnum : struct, Enum + => ParseEnumDescription(description); +#pragma warning restore IDE1006 } } diff --git a/src/chocolatey/EnumerableExtensions.cs b/src/chocolatey/EnumerableExtensions.cs index 3a58c5604f..1880e7fd32 100644 --- a/src/chocolatey/EnumerableExtensions.cs +++ b/src/chocolatey/EnumerableExtensions.cs @@ -16,6 +16,7 @@ namespace chocolatey { + using System; using System.Collections; using System.Collections.Generic; using System.Linq; @@ -31,9 +32,9 @@ public static class EnumerableExtensions /// /// The source. /// - /// Source if not null; otherwise Enumerable.Empty<> + /// Source if not null; otherwise Enumerable.Empty<> /// - public static IEnumerable or_empty_list_if_null(this IEnumerable source) + public static IEnumerable OrEmpty(this IEnumerable source) { return source ?? Enumerable.Empty(); } @@ -43,7 +44,7 @@ public static IEnumerable or_empty_list_if_null(this IEnumerable source /// /// The source. /// Source if not null; otherwise new ArrayList - public static IEnumerable or_empty_list_if_null(this IEnumerable source) + public static IEnumerable OrEmpty(this IEnumerable source) { return source ?? new ArrayList(); } @@ -54,7 +55,7 @@ public static IEnumerable or_empty_list_if_null(this IEnumerable source) /// The source. /// The value to put in between elements /// - public static string join(this IEnumerable source, string separator) + public static string Join(this IEnumerable source, string separator) { return string.Join(separator, source); } @@ -63,7 +64,7 @@ public static string join(this IEnumerable source, string separator) /// Returns a distinct set of elements using the comparer specified. This implementation will pick the last occurrence /// of each element instead of picking the first. This method assumes that similar items occur in order. /// - public static IEnumerable distinct_last(this IEnumerable source, IEqualityComparer equalityComparer, IComparer comparer) + public static IEnumerable LastDistinct(this IEnumerable source, IEqualityComparer equalityComparer, IComparer comparer) { bool first = true; bool maxElementHasValue = false; @@ -109,7 +110,7 @@ public static IEnumerable distinct_last(this IEnumerable source, IEqual /// /// Taken from here: https://stackoverflow.com/a/30758270/671491 /// - public static int get_sequence_hash_code(this IEnumerable source) + public static int SequenceHashCode(this IEnumerable source) { const int seed = 487; const int modifier = 31; @@ -120,5 +121,27 @@ public static int get_sequence_hash_code(this IEnumerable source) (current*modifier) + item.GetHashCode()); } } + +#pragma warning disable IDE1006 + [Obsolete("This overload is deprecated and will be removed in v3.")] + public static IEnumerable or_empty_list_if_null(this IEnumerable source) + => OrEmpty(source); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public static IEnumerable or_empty_list_if_null(this IEnumerable source) + => OrEmpty(source); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public static string join(this IEnumerable source, string separator) + => Join(source, separator); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public static IEnumerable distinct_last(this IEnumerable source, IEqualityComparer equalityComparer, IComparer comparer) + => LastDistinct(source, equalityComparer, comparer); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public static int get_sequence_hash_code(this IEnumerable source) + => SequenceHashCode(source); +#pragma warning restore IDE1006 } } diff --git a/src/chocolatey/FileSystemExtensions.cs b/src/chocolatey/FileSystemExtensions.cs index e7497f5bfd..9791cdde24 100644 --- a/src/chocolatey/FileSystemExtensions.cs +++ b/src/chocolatey/FileSystemExtensions.cs @@ -28,24 +28,24 @@ namespace chocolatey public static class FileSystemExtensions { - internal static IEnumerable get_extension_assemblies(this IFileSystem fileSystem) + internal static IEnumerable GetExtensionAssemblies(this IFileSystem fileSystem) { var result = new List(); - if (!fileSystem.directory_exists(ApplicationParameters.ExtensionsLocation)) + if (!fileSystem.DirectoryExists(ApplicationParameters.ExtensionsLocation)) { return result; } - var extensionDllFiles = fileSystem.get_files(ApplicationParameters.ExtensionsLocation, "*.dll", SearchOption.AllDirectories); + var extensionDllFiles = fileSystem.GetFiles(ApplicationParameters.ExtensionsLocation, "*.dll", SearchOption.AllDirectories); foreach (var extensionFile in extensionDllFiles) { - var name = fileSystem.get_file_name_without_extension(extensionFile); + var name = fileSystem.GetFilenameWithoutExtension(extensionFile); try { - var assembly = AssemblyResolution.load_extension(name); + var assembly = AssemblyResolution.LoadExtension(name); if (assembly == null) { @@ -65,5 +65,11 @@ internal static IEnumerable get_extension_assemblies(this IFileSystem return result.Distinct(); } + +#pragma warning disable IDE1006 + [Obsolete("This overload is deprecated and will be removed in v3.")] + internal static IEnumerable get_extension_assemblies(this IFileSystem fileSystem) + => GetExtensionAssemblies(fileSystem); +#pragma warning restore IDE1006 } } diff --git a/src/chocolatey/GetChocolatey.cs b/src/chocolatey/GetChocolatey.cs index 8c1f2498ff..c4f2814062 100644 --- a/src/chocolatey/GetChocolatey.cs +++ b/src/chocolatey/GetChocolatey.cs @@ -44,8 +44,6 @@ namespace chocolatey using ILog = infrastructure.logging.ILog; using System.Linq; - // ReSharper disable InconsistentNaming - /// /// Entry point for API /// @@ -53,9 +51,9 @@ public static class Lets { private static readonly log4net.ILog _logger = LogManager.GetLogger(typeof(Lets)); - private static GetChocolatey set_up(bool initializeLogging) + private static GetChocolatey Setup(bool initializeLogging) { - add_assembly_resolver(); + AddAssemblyResolver(); return new GetChocolatey(initializeLogging); } @@ -67,12 +65,12 @@ public static GetChocolatey GetChocolatey() public static GetChocolatey GetChocolatey(bool initializeLogging) { - return GlobalMutex.enter(() => set_up(initializeLogging), 10); + return GlobalMutex.Enter(() => Setup(initializeLogging), 10); } - private static void add_assembly_resolver() + private static void AddAssemblyResolver() { - AppDomain.CurrentDomain.AssemblyResolve += AssemblyResolution.resolve_extension_or_merged_assembly; + AppDomain.CurrentDomain.AssemblyResolve += AssemblyResolution.ResolveExtensionOrMergedAssembly; } } @@ -105,13 +103,13 @@ public GetChocolatey(bool initializeLogging) { string loggingLocation = ApplicationParameters.LoggingLocation; var fileSystem = _container.GetInstance(); - fileSystem.create_directory_if_not_exists(loggingLocation); + fileSystem.EnsureDirectoryExists(loggingLocation); - Log4NetAppenderConfiguration.configure(loggingLocation, excludeLoggerNames: ChocolateyLoggers.Trace.to_string()); + Log4NetAppenderConfiguration.Configure(loggingLocation, excludeLoggerNames: ChocolateyLoggers.Trace.ToStringSafe()); Log.InitializeWith(new AggregateLog(new List() { new Log4NetLog(), _logSinkLogger })); "chocolatey".Log().Debug("XmlConfiguration is now operational"); } - _license = License.validate_license(); + _license = License.ValidateLicense(); } /// @@ -140,15 +138,15 @@ public GetChocolatey SetCustomLogging(ILog logger, bool logExistingMessages, boo Log.InitializeWith(aggregateLog, resetLoggers: false); if (logExistingMessages) { - drain_log_sink(logger); + DrainLogSink(logger); } return this; } - private void drain_log_sink(ILog logger) + private void DrainLogSink(ILog logger) { - foreach (var logMessage in _logSinkLogger.Messages.or_empty_list_if_null()) + foreach (var logMessage in _logSinkLogger.Messages.OrEmpty()) { switch (logMessage.LogLevel) { @@ -300,16 +298,16 @@ public Container Container() /// public void Run() { - ensure_environment(); - extract_resources(); + EnsureEnvironment(); + ExtractResources(); - ensure_original_configuration(new List(), + EnsureOriginalConfiguration(new List(), (config) => { var runner = new GenericRunner(); - runner.run(config, _container, isConsole: false, parseArgs: command => + runner.Run(config, _container, isConsole: false, parseArgs: command => { - command.handle_validation(config); + command.Validate(config); }); }); } @@ -327,14 +325,14 @@ public void Run() /// Commandline arguments to add to configuration. public void RunConsole(string[] args) { - ensure_environment(); - extract_resources(); + EnsureEnvironment(); + ExtractResources(); - ensure_original_configuration(new List(args), + EnsureOriginalConfiguration(new List(args), (config) => { var runner = new ConsoleApplication(); - runner.run(args, config, _container); + runner.Run(args, config, _container); }); } @@ -352,14 +350,14 @@ public void RunConsole(string[] args) /// The typer of results you're expecting back. public IEnumerable List() { - ensure_environment(); - extract_resources(); + EnsureEnvironment(); + ExtractResources(); - return ensure_original_configuration(new List(), + return EnsureOriginalConfiguration(new List(), (config) => { var runner = new GenericRunner(); - return runner.list(config, _container, isConsole: false, parseArgs: null); + return runner.List(config, _container, isConsole: false, parseArgs: null); }); } @@ -380,14 +378,14 @@ public IEnumerable List() /// public int ListCount() { - ensure_environment(); - extract_resources(); + EnsureEnvironment(); + ExtractResources(); - return ensure_original_configuration(new List(), + return EnsureOriginalConfiguration(new List(), (config) => { var runner = new GenericRunner(); - return runner.count(config, _container, isConsole: false, parseArgs: null); + return runner.Count(config, _container, isConsole: false, parseArgs: null); }); } @@ -398,11 +396,11 @@ public int ListCount() /// Only call this once you have registered all container components with Chocolatey public ChocolateyConfiguration GetConfiguration() { - ensure_environment(); + EnsureEnvironment(); // ensure_original_configuration() already calls create_configuration() // so no need to repeat, just grab the result - var configuration = ensure_original_configuration( + var configuration = EnsureOriginalConfiguration( new List(), (config) => config ); @@ -410,9 +408,9 @@ public ChocolateyConfiguration GetConfiguration() return configuration; } - private void ensure_original_configuration(IList args, Action action) + private void EnsureOriginalConfiguration(IList args, Action action) { - var success = ensure_original_configuration(args, + var success = EnsureOriginalConfiguration(args, (config) => { if (action != null) action.Invoke(config); @@ -430,10 +428,10 @@ private void ensure_original_configuration(IList args, ActionThe arguments. /// The function. /// - private T ensure_original_configuration(IList args, Func function) + private T EnsureOriginalConfiguration(IList args, Func function) { - var originalConfig = Config.get_configuration_settings().deep_copy(); - var configuration = create_configuration(args); + var originalConfig = Config.GetConfigurationSettings().DeepCopy(); + var configuration = CreateConfiguration(args); var returnValue = default(T); try { @@ -442,17 +440,17 @@ private T ensure_original_configuration(IList args, Func(IList args, Func /// The arguments. /// The configuration for Chocolatey - private ChocolateyConfiguration create_configuration(IList args) + private ChocolateyConfiguration CreateConfiguration(IList args) { // get or create a ChocolateyConfiguration. This maps directly // to the same thing that is loaded into the container - var configuration = Config.get_configuration_settings(); - ConfigurationBuilder.set_up_configuration( + var configuration = Config.GetConfigurationSettings(); + ConfigurationBuilder.SetupConfiguration( args, configuration, _container, @@ -487,7 +485,7 @@ private ChocolateyConfiguration create_configuration(IList args) return configuration; } - private void ensure_environment() + private void EnsureEnvironment() { string chocolateyInstall = string.Empty; @@ -507,7 +505,7 @@ private void ensure_environment() Environment.SetEnvironmentVariable(ApplicationParameters.ChocolateyInstallEnvironmentVariableName, chocolateyInstall); } - private void extract_resources() + private void ExtractResources() { //refactor - thank goodness this is temporary, cuz manifest resource streams are dumb IList folders = new List @@ -521,16 +519,14 @@ private void extract_resources() #if !NoResources try { - AssemblyFileExtractor.extract_all_resources_to_relative_directory(_container.GetInstance(), Assembly.GetAssembly(typeof(ChocolateyResourcesAssembly)), ApplicationParameters.InstallLocation, folders, ApplicationParameters.ChocolateyFileResources); + AssemblyFileExtractor.ExtractAssemblyResourcesToRelativeDirectory(_container.GetInstance(), Assembly.GetAssembly(typeof(ChocolateyResourcesAssembly)), ApplicationParameters.InstallLocation, folders, ApplicationParameters.ChocolateyFileResources); } catch (Exception ex) { this.Log().Warn(ChocolateyLoggers.Important, "Please ensure that ChocolateyInstall environment variable is set properly and you've run once as an administrator to ensure all resources are extracted."); - this.Log().Error("Unable to extract resources. Please ensure the ChocolateyInstall environment variable is set properly. You may need to run once as an admin to ensure all resources are extracted. Details:{0} {1}".format_with(Environment.NewLine, ex.ToString())); + this.Log().Error("Unable to extract resources. Please ensure the ChocolateyInstall environment variable is set properly. You may need to run once as an admin to ensure all resources are extracted. Details:{0} {1}".FormatWith(Environment.NewLine, ex.ToString())); } #endif } } - - // ReSharper restore InconsistentNaming } diff --git a/src/chocolatey/ILogExtensions.cs b/src/chocolatey/ILogExtensions.cs index 0c9bd5a122..fa4d2ae227 100644 --- a/src/chocolatey/ILogExtensions.cs +++ b/src/chocolatey/ILogExtensions.cs @@ -20,8 +20,6 @@ namespace chocolatey using System.Runtime; using infrastructure.logging; - // ReSharper disable InconsistentNaming - /// /// Extensions for ILog /// @@ -35,13 +33,13 @@ public static class ILogExtensions [TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")] public static void Trace(this ILog logger, string message, params object[] formatting) { - if (LogTraceMessages) ChocolateyLoggers.Trace.to_string().Log().Debug(message, formatting); + if (LogTraceMessages) ChocolateyLoggers.Trace.ToStringSafe().Log().Debug(message, formatting); } [TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")] public static void Trace(this ILog logger, Func message) { - if (LogTraceMessages) ChocolateyLoggers.Trace.to_string().Log().Debug(message); + if (LogTraceMessages) ChocolateyLoggers.Trace.ToStringSafe().Log().Debug(message); } [TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")] @@ -57,7 +55,7 @@ public static void Debug(this ILog logger, ChocolateyLoggers logType, string mes Trace(logger,message,formatting); break; default: - logType.to_string().Log().Debug(message, formatting); + logType.ToStringSafe().Log().Debug(message, formatting); break; } } @@ -74,7 +72,7 @@ public static void Debug(this ILog logger, ChocolateyLoggers logType, Func /// Extensions to help make logging awesome /// @@ -73,6 +71,4 @@ public static ILog Log(this string objectName) return _dictionary.Value.GetOrAdd(objectName, infrastructure.logging.Log.GetLoggerFor(objectName)); } } - - // ReSharper restore InconsistentNaming } diff --git a/src/chocolatey/NuGetVersionExtensions.cs b/src/chocolatey/NuGetVersionExtensions.cs index 1f2cc32842..6bef91eda4 100644 --- a/src/chocolatey/NuGetVersionExtensions.cs +++ b/src/chocolatey/NuGetVersionExtensions.cs @@ -16,43 +16,57 @@ namespace chocolatey { using NuGet.Versioning; + using System; /// /// Helper methods for dealing with the the nuget version returned by /// the NuGet.Client libraries to ensure they can be easily used. /// - /// The class is marked as internal on purpose to ensure it will not be part of the public API - internal static class NuGetVersionExtensions + public static class NuGetVersionExtensions { +#pragma warning disable RS0030 // Do not used banned APIs /// - /// Wrapper object to prevent null reference exceptions happening. - /// Will return an empty string if the passed in is null. - /// Otherwise it will return the result of its call to ToFullString(). + /// Wrapper method to prevent null reference exceptions, calls into . /// /// The NuGet version to transform to a string. /// An empty string if is null; otherwise the result of its call to ToFullString. - public static string to_full_string(this NuGetVersion version) + public static string ToFullStringChecked(this NuGetVersion version) { if (version is null) { return string.Empty; } -#pragma warning disable RS0030 // Do not used banned APIs return version.ToFullString(); -#pragma warning restore RS0030 // Do not used banned APIs } +#pragma warning restore RS0030 // Do not used banned APIs - public static string to_normalized_string(this NuGetVersion version) + +#pragma warning disable RS0030 // Do not used banned APIs + /// + /// Wrapper method to prevent null reference exceptions, calls into . + /// + /// The NuGet version to transform to a string. + /// An empty string if is null; otherwise the result of its call to ToFullString. + public static string ToNormalizedStringChecked(this NuGetVersion version) { if (version is null) { return string.Empty; } -#pragma warning disable RS0030 // Do not used banned APIs return version.ToNormalizedString(); -#pragma warning restore RS0030 // Do not used banned APIs } +#pragma warning restore RS0030 // Do not used banned APIs + +#pragma warning disable IDE1006 + [Obsolete("This overload is deprecated and will be removed in v3.")] + public static string to_full_string(this NuGetVersion version) + => ToFullStringChecked(version); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public static string to_normalized_string(this NuGetVersion version) + => ToNormalizedStringChecked(version); +#pragma warning restore IDE1006 } } diff --git a/src/chocolatey/ObjectExtensions.cs b/src/chocolatey/ObjectExtensions.cs index 61db79e376..f7a7a7c546 100644 --- a/src/chocolatey/ObjectExtensions.cs +++ b/src/chocolatey/ObjectExtensions.cs @@ -16,6 +16,7 @@ namespace chocolatey { + using System; using System.IO; using System.Runtime.Serialization.Formatters.Binary; @@ -25,18 +26,18 @@ namespace chocolatey public static class ObjectExtensions { /// - /// A null safe variant of ToString(). + /// A null safe variant of . /// /// The input. - /// String.Empty if input is null, otherwise input.ToString() - public static string to_string(this object input) + /// if is null, otherwise .ToString() + public static string ToStringSafe(this object input) { if (input == null) return string.Empty; return input.ToString(); } - public static T deep_copy(this T other) + public static T DeepCopy(this T other) { using (var ms = new MemoryStream()) { @@ -46,5 +47,15 @@ public static T deep_copy(this T other) return (T)formatter.Deserialize(ms); } } + +#pragma warning disable IDE1006 + [Obsolete("This overload is deprecated and will be removed in v3.")] + public static string to_string(this object input) + => ToStringSafe(input); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public static T deep_copy(this T other) + => DeepCopy(other); +#pragma warning restore IDE1006 } } diff --git a/src/chocolatey/RuleResultExtensions.cs b/src/chocolatey/RuleResultExtensions.cs index 1b417219e1..50a1a1504d 100644 --- a/src/chocolatey/RuleResultExtensions.cs +++ b/src/chocolatey/RuleResultExtensions.cs @@ -15,6 +15,7 @@ namespace chocolatey { + using System; using System.Collections.Generic; using System.Linq; using chocolatey.infrastructure.rules; @@ -27,7 +28,7 @@ public static class RuleResultExtensions /// The rule results to apply the filter to. /// True if the applied filters should exclude unsupported and deprecated rules; otherwise False /// The passed in rule results with the applied filters. - public static IEnumerable where_unsupported_or_deprecated(this IEnumerable ruleResults, bool inverse = false) + public static IEnumerable WhereUnsupportedOrDeprecated(this IEnumerable ruleResults, bool inverse = false) { if (!inverse) { @@ -35,9 +36,16 @@ public static IEnumerable where_unsupported_or_deprecated(this IEnum .Where(r => r != null && !string.IsNullOrEmpty(r.Id)) .Where(r => r.Id.StartsWith("CHCU") || r.Id.StartsWith("CHCD")); } + return ruleResults .Where(r => r != null) .Where(r => string.IsNullOrEmpty(r.Id) || (!r.Id.StartsWith("CHCU") && !r.Id.StartsWith("CHCD"))); } + +#pragma warning disable IDE1006 + [Obsolete("This overload is deprecated and will be removed in v3.")] + public static IEnumerable where_unsupported_or_deprecated(this IEnumerable ruleResults, bool inverse = false) + => WhereUnsupportedOrDeprecated(ruleResults, inverse); +#pragma warning restore IDE1006 } } diff --git a/src/chocolatey/StringExtensions.cs b/src/chocolatey/StringExtensions.cs index 7d9052261c..4b830da846 100644 --- a/src/chocolatey/StringExtensions.cs +++ b/src/chocolatey/StringExtensions.cs @@ -30,12 +30,12 @@ namespace chocolatey public static class StringExtensions { /// - /// Formats string with the formatting passed in. This is a shortcut to string.Format(). + /// Formats string with the formatting passed in. This is a null-safe wrapper for . /// /// The input. /// The formatting. - /// A formatted string. - public static string format_with(this string input, params object[] formatting) + /// A formatted string, or if is null. + public static string FormatWith(this string input, params object[] formatting) { if (string.IsNullOrWhiteSpace(input)) return string.Empty; @@ -55,7 +55,7 @@ public static string format_with(this string input, params object[] formatting) /// /// The input. /// - public static string trim_safe(this string input) + public static string TrimSafe(this string input) { if (string.IsNullOrWhiteSpace(input)) return string.Empty; @@ -67,7 +67,7 @@ public static string trim_safe(this string input) /// /// The input. /// - public static string to_lower(this string input) + public static string ToLowerSafe(this string input) { if (string.IsNullOrWhiteSpace(input)) return string.Empty; @@ -79,7 +79,7 @@ public static string to_lower(this string input) /// /// The input. /// - public static string to_string(this string input) + public static string ToStringSafe(this string input) { if (string.IsNullOrWhiteSpace(input)) return string.Empty; @@ -91,7 +91,7 @@ public static string to_string(this string input) /// /// The input. /// - public static SecureString to_secure_string(this string input) + public static SecureString ToSecureStringSafe(this string input) { var secureString = new SecureString(); @@ -105,7 +105,7 @@ public static SecureString to_secure_string(this string input) return secureString; } - public static string from_secure_string(this SecureString input) + public static string FromSecureStringSafe(this SecureString input) { if (input == null) return string.Empty; @@ -128,13 +128,13 @@ public static string from_secure_string(this SecureString input) /// /// The input. /// - public static string wrap_spaces_in_quotes(this string input) + public static string QuoteIfContainsSpaces(this string input) { if (string.IsNullOrWhiteSpace(input)) return input; if (_spacePattern.IsMatch(input)) { - return "\"{0}\"".format_with(input); + return "\"{0}\"".FormatWith(input); } return input; @@ -146,7 +146,7 @@ public static string wrap_spaces_in_quotes(this string input) /// The input. /// The value to compare to /// True if these are the same - public static bool is_equal_to(this string input, string other) + public static bool IsEqualTo(this string input, string other) { return string.Compare(input, other, ignoreCase: true, culture: CultureInfo.InvariantCulture) == 0; } @@ -158,9 +158,9 @@ public static bool is_equal_to(this string input, string other) /// The value to search for. /// The comparison. /// True if the value to search for is in the input string - public static bool contains(this string input, string search, StringComparison comparison = StringComparison.OrdinalIgnoreCase) + public static bool ContainsSafe(this string input, string search, StringComparison comparison = StringComparison.OrdinalIgnoreCase) { - return input.to_string().IndexOf(search, 0, comparison) >= 0; + return input.ToStringSafe().IndexOf(search, 0, comparison) >= 0; } /// @@ -168,13 +168,13 @@ public static bool contains(this string input, string search, StringComparison c /// /// The input. /// - public static string remove_surrounding_quotes(this string input) + public static string UnquoteSafe(this string input) { if (string.IsNullOrWhiteSpace(input)) return string.Empty; if (input.StartsWith(" ")) { - input = input.trim_safe(); + input = input.TrimSafe(); } if ((input.StartsWith("\"") && input.EndsWith("\"")) @@ -186,14 +186,14 @@ public static string remove_surrounding_quotes(this string input) return input; } - private static Regex open_brace_regex = new Regex("(? @@ -201,14 +201,63 @@ public static string escape_curly_braces(this string input) /// /// The input. /// The input, but with double quotes if there is a pipe character found in the string. - public static string quote_if_pipe_found(this string input) + public static string QuoteIfContainsPipe(this string input) { - if (string.IsNullOrWhiteSpace(input)) return input.to_string(); + if (string.IsNullOrWhiteSpace(input)) return input.ToStringSafe(); - if (input.contains("|")) return "\"{0}\"".format_with(input); + if (input.ContainsSafe("|")) return "\"{0}\"".FormatWith(input); return input; } +#pragma warning disable IDE1006 + [Obsolete("This overload is deprecated and will be removed in v3.")] + public static string format_with(this string input, params object[] formatting) + => FormatWith(input, formatting); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public static string trim_safe(this string input) + => TrimSafe(input); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public static string to_lower(this string input) + => ToLowerSafe(input); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public static string to_string(this string input) + => ToStringSafe(input); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public static SecureString to_secure_string(this string input) + => ToSecureStringSafe(input); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public static string from_secure_string(this SecureString input) + => FromSecureStringSafe(input); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public static string wrap_spaces_in_quotes(this string input) + => QuoteIfContainsSpaces(input); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public static bool is_equal_to(this string input, string other) + => IsEqualTo(input, other); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public static bool contains(this string input, string search, StringComparison comparison = StringComparison.OrdinalIgnoreCase) + => ContainsSafe(input, search, comparison); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public static string remove_surrounding_quotes(this string input) + => UnquoteSafe(input); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public static string escape_curly_braces(this string input) + => EscapeCurlyBraces(input); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public static string quote_if_pipe_found(this string input) + => QuoteIfContainsPipe(input); +#pragma warning restore IDE1006 } } diff --git a/src/chocolatey/TypeExtensions.cs b/src/chocolatey/TypeExtensions.cs index d185a2f97b..29457b3165 100644 --- a/src/chocolatey/TypeExtensions.cs +++ b/src/chocolatey/TypeExtensions.cs @@ -28,7 +28,7 @@ public static class TypeExtensions /// /// The type. /// true if meets criteria for system type - public static bool is_built_in_system_type(this Type type) + public static bool IsBuiltinType(this Type type) { if (type == null) return false; @@ -36,7 +36,7 @@ public static bool is_built_in_system_type(this Type type) return type.IsPrimitive || type.IsValueType || (type == typeof (string)) - || type.Namespace.Equals("System"); + || type.Namespace.Equals("System", StringComparison.Ordinal); } /// @@ -44,12 +44,23 @@ public static bool is_built_in_system_type(this Type type) /// /// The type. /// true if enumerable - public static bool is_collections_type(this Type type) + public static bool IsCollectionType(this Type type) { if (type == null) return false; + // Surely we can do a check around "is ICollection" / "is ICollection<>" here? return type.IsArray || type.Namespace.Contains("System.Collections"); } + +#pragma warning disable IDE1006 + [Obsolete("This overload is deprecated and will be removed in v3.")] + public static bool is_built_in_system_type(this Type type) + => IsBuiltinType(type); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public static bool is_collections_type(this Type type) + => IsCollectionType(type); +#pragma warning restore IDE1006 } } diff --git a/src/chocolatey/chocolatey.csproj b/src/chocolatey/chocolatey.csproj index 1b28493a5c..30f8827977 100644 --- a/src/chocolatey/chocolatey.csproj +++ b/src/chocolatey/chocolatey.csproj @@ -1,4 +1,4 @@ - + @@ -101,44 +101,44 @@ False ..\packages\AlphaFS.2.1.3\lib\net40\AlphaFS.dll - - ..\packages\Chocolatey.NuGet.Commands.3.0.0-alpha-20230315-204\lib\net472\Chocolatey.NuGet.Commands.dll + + ..\packages\Chocolatey.NuGet.Commands.3.1.0\lib\net472\Chocolatey.NuGet.Commands.dll - - ..\packages\Chocolatey.NuGet.Common.3.0.0-alpha-20230315-204\lib\net472\Chocolatey.NuGet.Common.dll + + ..\packages\Chocolatey.NuGet.Common.3.1.0\lib\net472\Chocolatey.NuGet.Common.dll - - ..\packages\Chocolatey.NuGet.Configuration.3.0.0-alpha-20230315-204\lib\net472\Chocolatey.NuGet.Configuration.dll + + ..\packages\Chocolatey.NuGet.Configuration.3.1.0\lib\net472\Chocolatey.NuGet.Configuration.dll - - ..\packages\Chocolatey.NuGet.Credentials.3.0.0-alpha-20230315-204\lib\net472\Chocolatey.NuGet.Credentials.dll + + ..\packages\Chocolatey.NuGet.Credentials.3.1.0\lib\net472\Chocolatey.NuGet.Credentials.dll - - ..\packages\Chocolatey.NuGet.DependencyResolver.Core.3.0.0-alpha-20230315-204\lib\net472\Chocolatey.NuGet.DependencyResolver.Core.dll + + ..\packages\Chocolatey.NuGet.DependencyResolver.Core.3.1.0\lib\net472\Chocolatey.NuGet.DependencyResolver.Core.dll - - ..\packages\Chocolatey.NuGet.Frameworks.3.0.0-alpha-20230315-204\lib\net472\Chocolatey.NuGet.Frameworks.dll + + ..\packages\Chocolatey.NuGet.Frameworks.3.1.0\lib\net472\Chocolatey.NuGet.Frameworks.dll - - ..\packages\Chocolatey.NuGet.LibraryModel.3.0.0-alpha-20230315-204\lib\net472\Chocolatey.NuGet.LibraryModel.dll + + ..\packages\Chocolatey.NuGet.LibraryModel.3.1.0\lib\net472\Chocolatey.NuGet.LibraryModel.dll - - ..\packages\Chocolatey.NuGet.PackageManagement.3.0.0-alpha-20230315-204\lib\net472\Chocolatey.NuGet.PackageManagement.dll + + ..\packages\Chocolatey.NuGet.PackageManagement.3.1.0\lib\net472\Chocolatey.NuGet.PackageManagement.dll - - ..\packages\Chocolatey.NuGet.Packaging.3.0.0-alpha-20230315-204\lib\net472\Chocolatey.NuGet.Packaging.dll + + ..\packages\Chocolatey.NuGet.Packaging.3.1.0\lib\net472\Chocolatey.NuGet.Packaging.dll - - ..\packages\Chocolatey.NuGet.ProjectModel.3.0.0-alpha-20230315-204\lib\net472\Chocolatey.NuGet.ProjectModel.dll + + ..\packages\Chocolatey.NuGet.ProjectModel.3.1.0\lib\net472\Chocolatey.NuGet.ProjectModel.dll - - ..\packages\Chocolatey.NuGet.Protocol.3.0.0-alpha-20230315-204\lib\net472\Chocolatey.NuGet.Protocol.dll + + ..\packages\Chocolatey.NuGet.Protocol.3.1.0\lib\net472\Chocolatey.NuGet.Protocol.dll - - ..\packages\Chocolatey.NuGet.Resolver.3.0.0-alpha-20230315-204\lib\net472\Chocolatey.NuGet.Resolver.dll + + ..\packages\Chocolatey.NuGet.Resolver.3.1.0\lib\net472\Chocolatey.NuGet.Resolver.dll - - ..\packages\Chocolatey.NuGet.Versioning.3.0.0-alpha-20230315-204\lib\net472\Chocolatey.NuGet.Versioning.dll + + ..\packages\Chocolatey.NuGet.Versioning.3.1.0\lib\net472\Chocolatey.NuGet.Versioning.dll ..\packages\log4net.2.0.12\lib\net45\log4net.dll @@ -210,6 +210,8 @@ + + @@ -270,7 +272,9 @@ + + diff --git a/src/chocolatey/infrastructure.app/ApplicationParameters.cs b/src/chocolatey/infrastructure.app/ApplicationParameters.cs index 311ad43937..122e6ddfa9 100644 --- a/src/chocolatey/infrastructure.app/ApplicationParameters.cs +++ b/src/chocolatey/infrastructure.app/ApplicationParameters.cs @@ -35,48 +35,48 @@ public static class ApplicationParameters #if FORCE_CHOCOLATEY_OFFICIAL_KEY // always look at the official location of the machine installation - public static readonly string InstallLocation = System.Environment.GetEnvironmentVariable(ChocolateyInstallEnvironmentVariableName) ?? _fileSystem.get_directory_name(_fileSystem.get_current_assembly_path()); - public static readonly string LicensedAssemblyLocation = _fileSystem.combine_paths(InstallLocation, "extensions", "chocolatey", "chocolatey.licensed.dll"); + public static readonly string InstallLocation = System.Environment.GetEnvironmentVariable(ChocolateyInstallEnvironmentVariableName) ?? _fileSystem.GetDirectoryName(_fileSystem.GetCurrentAssemblyPath()); + public static readonly string LicensedAssemblyLocation = _fileSystem.CombinePaths(InstallLocation, "extensions", "chocolatey", "chocolatey.licensed.dll"); #elif DEBUG // Install location is choco.exe or chocolatey.dll - public static readonly string InstallLocation = _fileSystem.get_directory_name(_fileSystem.get_current_assembly_path()); + public static readonly string InstallLocation = _fileSystem.GetDirectoryName(_fileSystem.GetCurrentAssemblyPath()); // when being used as a reference, start by looking next to Chocolatey, then in a subfolder. - public static readonly string LicensedAssemblyLocation = _fileSystem.file_exists(_fileSystem.combine_paths(InstallLocation, "chocolatey.licensed.dll")) ? _fileSystem.combine_paths(InstallLocation, "chocolatey.licensed.dll") : _fileSystem.combine_paths(InstallLocation, "extensions", "chocolatey", "chocolatey.licensed.dll"); + public static readonly string LicensedAssemblyLocation = _fileSystem.FileExists(_fileSystem.CombinePaths(InstallLocation, "chocolatey.licensed.dll")) ? _fileSystem.CombinePaths(InstallLocation, "chocolatey.licensed.dll") : _fileSystem.CombinePaths(InstallLocation, "extensions", "chocolatey", "chocolatey.licensed.dll"); #else - // Install locations is chocolatey.dll or choco.exe - In Release mode + // Install locations is Chocolatey.dll or choco.exe - In Release mode // we might be testing on a server or in the local debugger. Either way, // start from the assembly location and if unfound, head to the machine // locations instead. This is a merge of official and Debug modes. private static IAssembly _assemblyForLocation = Assembly.GetEntryAssembly().UnderlyingType != null ? Assembly.GetEntryAssembly() : Assembly.GetExecutingAssembly(); - public static readonly string InstallLocation = _fileSystem.file_exists(_fileSystem.combine_paths(_fileSystem.get_directory_name(_assemblyForLocation.CodeBase.Replace(Platform.get_platform() == PlatformType.Windows ? "file:///" : "file://", string.Empty)), "chocolatey.dll")) || - _fileSystem.file_exists(_fileSystem.combine_paths(_fileSystem.get_directory_name(_assemblyForLocation.CodeBase.Replace(Platform.get_platform() == PlatformType.Windows ? "file:///" : "file://", string.Empty)), "choco.exe")) ? - _fileSystem.get_directory_name(_assemblyForLocation.CodeBase.Replace(Platform.get_platform() == PlatformType.Windows ? "file:///" : "file://", string.Empty)) : + public static readonly string InstallLocation = _fileSystem.FileExists(_fileSystem.CombinePaths(_fileSystem.GetDirectoryName(_assemblyForLocation.CodeBase.Replace(Platform.GetPlatform() == PlatformType.Windows ? "file:///" : "file://", string.Empty)), "chocolatey.dll")) || + _fileSystem.FileExists(_fileSystem.CombinePaths(_fileSystem.GetDirectoryName(_assemblyForLocation.CodeBase.Replace(Platform.GetPlatform() == PlatformType.Windows ? "file:///" : "file://", string.Empty)), "choco.exe")) ? + _fileSystem.GetDirectoryName(_assemblyForLocation.CodeBase.Replace(Platform.GetPlatform() == PlatformType.Windows ? "file:///" : "file://", string.Empty)) : !string.IsNullOrWhiteSpace(System.Environment.GetEnvironmentVariable(ChocolateyInstallEnvironmentVariableName)) ? System.Environment.GetEnvironmentVariable(ChocolateyInstallEnvironmentVariableName) : @"C:\ProgramData\Chocolatey" ; // when being used as a reference, start by looking next to Chocolatey, then in a subfolder. - public static readonly string LicensedAssemblyLocation = _fileSystem.file_exists(_fileSystem.combine_paths(InstallLocation, "chocolatey.licensed.dll")) ? _fileSystem.combine_paths(InstallLocation, "chocolatey.licensed.dll") : _fileSystem.combine_paths(InstallLocation, "extensions", "chocolatey", "chocolatey.licensed.dll"); + public static readonly string LicensedAssemblyLocation = _fileSystem.FileExists(_fileSystem.CombinePaths(InstallLocation, "chocolatey.licensed.dll")) ? _fileSystem.CombinePaths(InstallLocation, "chocolatey.licensed.dll") : _fileSystem.CombinePaths(InstallLocation, "extensions", "chocolatey", "chocolatey.licensed.dll"); #endif - public static readonly string CommonAppDataChocolatey = _fileSystem.combine_paths(System.Environment.GetFolderPath(System.Environment.SpecialFolder.CommonApplicationData), Name); - public static readonly string LoggingLocation = _fileSystem.combine_paths(InstallLocation, "logs"); + public static readonly string CommonAppDataChocolatey = _fileSystem.CombinePaths(System.Environment.GetFolderPath(System.Environment.SpecialFolder.CommonApplicationData), Name); + public static readonly string LoggingLocation = _fileSystem.CombinePaths(InstallLocation, "logs"); public static readonly string LoggingFile = @"chocolatey.log"; public static readonly string LoggingSummaryFile = @"choco.summary.log"; public static readonly string Log4NetConfigurationAssembly = @"chocolatey"; public static string Log4NetConfigurationResource = @"chocolatey.infrastructure.logging.log4net.config.xml"; public static readonly string ChocolateyFileResources = "chocolatey.resources"; public static readonly string ChocolateyConfigFileResource = @"chocolatey.infrastructure.app.configuration.chocolatey.config"; - public static readonly string GlobalConfigFileLocation = _fileSystem.combine_paths(InstallLocation, "config", "chocolatey.config"); - public static readonly string LicenseFileLocation = _fileSystem.combine_paths(InstallLocation, "license", "chocolatey.license.xml"); + public static readonly string GlobalConfigFileLocation = _fileSystem.CombinePaths(InstallLocation, "config", "chocolatey.config"); + public static readonly string LicenseFileLocation = _fileSystem.CombinePaths(InstallLocation, "license", "chocolatey.license.xml"); public static readonly string UserProfilePath = !string.IsNullOrWhiteSpace(System.Environment.GetFolderPath(System.Environment.SpecialFolder.UserProfile, System.Environment.SpecialFolderOption.DoNotVerify)) ? System.Environment.GetFolderPath(System.Environment.SpecialFolder.UserProfile, System.Environment.SpecialFolderOption.DoNotVerify) : CommonAppDataChocolatey; - public static readonly string HttpCacheUserLocation = _fileSystem.combine_paths(UserProfilePath, ".chocolatey", "http-cache"); - public static readonly string HttpCacheLocation = get_http_cache_location(); + public static readonly string HttpCacheUserLocation = _fileSystem.CombinePaths(UserProfilePath, ".chocolatey", "http-cache"); + public static readonly string HttpCacheLocation = GetHttpCacheLocation(); - public static readonly string UserLicenseFileLocation = _fileSystem.combine_paths(UserProfilePath, "chocolatey.license.xml"); + public static readonly string UserLicenseFileLocation = _fileSystem.CombinePaths(UserProfilePath, "chocolatey.license.xml"); public static readonly string LicensedChocolateyAssemblySimpleName = "chocolatey.licensed"; public static readonly string LicensedComponentRegistry = @"chocolatey.licensed.infrastructure.app.registration.ContainerBinding"; public static readonly string LicensedConfigurationBuilder = @"chocolatey.licensed.infrastructure.app.builders.ConfigurationBuilder"; @@ -85,14 +85,14 @@ public static class ApplicationParameters public static readonly string UnofficialChocolateyPublicKey = "fd112f53c3ab578c"; public static readonly string OfficialChocolateyPublicKey = "79d02ea9cad655eb"; - public static string PackagesLocation = _fileSystem.combine_paths(InstallLocation, "lib"); - public static readonly string PackageFailuresLocation = _fileSystem.combine_paths(InstallLocation, "lib-bad"); - public static readonly string PackageBackupLocation = _fileSystem.combine_paths(InstallLocation, "lib-bkp"); - public static readonly string ShimsLocation = _fileSystem.combine_paths(InstallLocation, "bin"); - public static readonly string ChocolateyPackageInfoStoreLocation = _fileSystem.combine_paths(InstallLocation, ".chocolatey"); - public static readonly string ExtensionsLocation = _fileSystem.combine_paths(InstallLocation, "extensions"); - public static readonly string TemplatesLocation = _fileSystem.combine_paths(InstallLocation, "templates"); - public static readonly string HooksLocation = _fileSystem.combine_paths(InstallLocation, "hooks"); + public static string PackagesLocation = _fileSystem.CombinePaths(InstallLocation, "lib"); + public static readonly string PackageFailuresLocation = _fileSystem.CombinePaths(InstallLocation, "lib-bad"); + public static readonly string PackageBackupLocation = _fileSystem.CombinePaths(InstallLocation, "lib-bkp"); + public static readonly string ShimsLocation = _fileSystem.CombinePaths(InstallLocation, "bin"); + public static readonly string ChocolateyPackageInfoStoreLocation = _fileSystem.CombinePaths(InstallLocation, ".chocolatey"); + public static readonly string ExtensionsLocation = _fileSystem.CombinePaths(InstallLocation, "extensions"); + public static readonly string TemplatesLocation = _fileSystem.CombinePaths(InstallLocation, "templates"); + public static readonly string HooksLocation = _fileSystem.CombinePaths(InstallLocation, "hooks"); public static readonly string HookPackageIdExtension = ".hook"; public static readonly string ChocolateyCommunityFeedPushSourceOld = "https://chocolatey.org/"; public static readonly string ChocolateyCommunityFeedPushSource = "https://push.chocolatey.org/"; @@ -103,14 +103,14 @@ public static class ApplicationParameters public static readonly string UserAgent = "Chocolatey Command Line"; public static readonly string RegistryValueInstallLocation = "InstallLocation"; public static readonly string AllPackages = "all"; - public static readonly string PowerShellModulePathProcessProgramFiles = _fileSystem.combine_paths(System.Environment.GetFolderPath(System.Environment.SpecialFolder.ProgramFiles), "WindowsPowerShell\\Modules"); - public static readonly string PowerShellModulePathProcessDocuments = _fileSystem.combine_paths(System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyDocuments), "WindowsPowerShell\\Modules"); + public static readonly string PowerShellModulePathProcessProgramFiles = _fileSystem.CombinePaths(System.Environment.GetFolderPath(System.Environment.SpecialFolder.ProgramFiles), "WindowsPowerShell\\Modules"); + public static readonly string PowerShellModulePathProcessDocuments = _fileSystem.CombinePaths(System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyDocuments), "WindowsPowerShell\\Modules"); public static readonly string LocalSystemSidString = "S-1-5-18"; public static readonly SecurityIdentifier LocalSystemSid = new SecurityIdentifier(LocalSystemSidString); - private static string get_http_cache_location() + private static string GetHttpCacheLocation() { - if (ProcessInformation.process_is_elevated() || string.IsNullOrEmpty(System.Environment.GetFolderPath(System.Environment.SpecialFolder.UserProfile, System.Environment.SpecialFolderOption.DoNotVerify))) + if (ProcessInformation.IsElevated() || string.IsNullOrEmpty(System.Environment.GetFolderPath(System.Environment.SpecialFolder.UserProfile, System.Environment.SpecialFolderOption.DoNotVerify))) { // CommonAppDataChocolatey is always set to ProgramData\Chocolatey. // So we append HttpCache to that name if it is possible. @@ -131,7 +131,7 @@ public static class Environment public static readonly string SystemUserName = "SYSTEM"; public static readonly string Username = "USERNAME"; public static readonly string ProcessorArchitecture = "PROCESSOR_ARCHITECTURE"; - public const string ARM64_PROCESSOR_ARCHITECTURE = "ARM64"; + public const string Arm64ProcessorArchitecture = "ARM64"; public static readonly string EnvironmentSeparator = ";"; public static readonly string ChocolateyToolsLocation = "ChocolateyToolsLocation"; @@ -178,7 +178,7 @@ public static class ExitCodes public static class Tools { - public static readonly string ShimGenExe = _fileSystem.combine_paths(InstallLocation, "tools", "shimgen.exe"); + public static readonly string ShimGenExe = _fileSystem.CombinePaths(InstallLocation, "tools", "shimgen.exe"); } public static class ConfigSettings @@ -233,26 +233,14 @@ public static class Messages public static readonly string NugetEventActionHeader = "Nuget called an event"; } - private static T try_get_config(Func func, T defaultValue) - { - try - { - return func.Invoke(); - } - catch (Exception) - { - return defaultValue; - } - } - - public static bool is_debug_mode_cli_primitive() + public static bool IsDebugModeCliPrimitive() { var args = System.Environment.GetCommandLineArgs(); var isDebug = false; // no access to the good stuff here, need to go a bit primitive in parsing args - foreach (var arg in args.or_empty_list_if_null()) + foreach (var arg in args.OrEmpty()) { - if (arg.contains("-debug") || arg.is_equal_to("-d") || arg.is_equal_to("/d")) + if (arg.ContainsSafe("-debug") || arg.IsEqualTo("-d") || arg.IsEqualTo("/d")) { isDebug = true; break; @@ -262,12 +250,10 @@ public static bool is_debug_mode_cli_primitive() return isDebug; } - ///// - ///// Are we in Debug Mode? - ///// - //public static bool IsDebug - //{ - // get { return TryGetConfig(() => Config.GetConfigurationSettings().Debug, false); } - //} +#pragma warning disable IDE1006 + [Obsolete("This overload is deprecated and will be removed in v3.")] + public static bool is_debug_mode_cli_primitive() + => IsDebugModeCliPrimitive(); +#pragma warning restore IDE1006 } } diff --git a/src/chocolatey/infrastructure.app/builders/ConfigurationBuilder.cs b/src/chocolatey/infrastructure.app/builders/ConfigurationBuilder.cs index 9c83aa6299..b0c88aa11c 100644 --- a/src/chocolatey/infrastructure.app/builders/ConfigurationBuilder.cs +++ b/src/chocolatey/infrastructure.app/builders/ConfigurationBuilder.cs @@ -1,4 +1,4 @@ -// Copyright © 2017 - 2022 Chocolatey Software, Inc +// Copyright © 2017 - 2022 Chocolatey Software, Inc // Copyright © 2011 - 2017 RealDimensions Software, LLC // // Licensed under the Apache License, Version 2.0 (the "License"); @@ -32,8 +32,10 @@ namespace chocolatey.infrastructure.app.builders using infrastructure.services; using licensing; using logging; + using Microsoft.Win32; using nuget; using platforms; + using services; using tolerance; using Assembly = adapters.Assembly; using Container = SimpleInjector.Container; @@ -44,11 +46,11 @@ namespace chocolatey.infrastructure.app.builders /// public static class ConfigurationBuilder { - private const string SET_CONFIGURATION_METHOD = "SetConfiguration"; + private const string SetConfigurationMethod = "SetConfiguration"; private static Lazy _environmentInitializer = new Lazy(() => new Environment()); [EditorBrowsable(EditorBrowsableState.Never)] - public static void initialize_with(Lazy environment) + public static void InitializeWith(Lazy environment) { _environmentInitializer = environment; } @@ -58,11 +60,11 @@ private static IEnvironment Environment get { return _environmentInitializer.Value; } } - public static bool is_compatibility_checks_disabled(IFileSystem filesystem, IXmlService xmlService) + public static bool AreCompatibilityChecksDisabled(IFileSystem filesystem, IXmlService xmlService) { - var config = get_config_file_settings(filesystem, xmlService); + var config = GetConfigFileSettings(filesystem, xmlService); - var feature = config.Features.FirstOrDefault(f => f.Name.is_equal_to("disableCompatibilityChecks")); + var feature = config.Features.FirstOrDefault(f => f.Name.IsEqualTo("disableCompatibilityChecks")); return feature != null && feature.Enabled; } @@ -75,51 +77,52 @@ public static bool is_compatibility_checks_disabled(IFileSystem filesystem, IXml /// The container. /// The license. /// Notify warn logging action - public static void set_up_configuration(IList args, ChocolateyConfiguration config, Container container, ChocolateyLicense license, Action notifyWarnLoggingAction) + public static void SetupConfiguration(IList args, ChocolateyConfiguration config, Container container, ChocolateyLicense license, Action notifyWarnLoggingAction) { var fileSystem = container.GetInstance(); var xmlService = container.GetInstance(); - var configFileSettings = get_config_file_settings(fileSystem, xmlService); + var configFileSettings = GetConfigFileSettings(fileSystem, xmlService); // must be done prior to setting the file configuration - add_or_remove_licensed_source(license, configFileSettings); - set_file_configuration(config, configFileSettings, fileSystem, notifyWarnLoggingAction); - ConfigurationOptions.reset_options(); - set_global_options(args, config, container); - set_environment_options(config); - EnvironmentSettings.set_environment_variables(config); + AddOrRemoveLicensedSource(license, configFileSettings); + SetFileConfiguration(config, configFileSettings, fileSystem, notifyWarnLoggingAction); + ConfigurationOptions.ClearOptions(); + SetGlobalOptions(args, config, container); + SetEnvironmentOptions(config); + EnvironmentSettings.SetEnvironmentVariables(config); + SetProxyOptions(config, container); // must be done last for overrides - set_licensed_options(config, license, configFileSettings); + SetLicensedOptions(config, license, configFileSettings); // save all changes if there are any - set_config_file_settings(configFileSettings, xmlService, config); - set_hash_provider(config, container); + SetConfigFileSettings(configFileSettings, xmlService, config); + SetHashProvider(config, container); } - private static ConfigFileSettings get_config_file_settings(IFileSystem fileSystem, IXmlService xmlService) + private static ConfigFileSettings GetConfigFileSettings(IFileSystem fileSystem, IXmlService xmlService) { var globalConfigPath = ApplicationParameters.GlobalConfigFileLocation; - AssemblyFileExtractor.extract_text_file_from_assembly(fileSystem, Assembly.GetExecutingAssembly(), ApplicationParameters.ChocolateyConfigFileResource, globalConfigPath); + AssemblyFileExtractor.ExtractTextFileFromAssembly(fileSystem, Assembly.GetExecutingAssembly(), ApplicationParameters.ChocolateyConfigFileResource, globalConfigPath); - return xmlService.deserialize(globalConfigPath); + return xmlService.Deserialize(globalConfigPath); } - private static void set_config_file_settings(ConfigFileSettings configFileSettings, IXmlService xmlService, ChocolateyConfiguration config) + private static void SetConfigFileSettings(ConfigFileSettings configFileSettings, IXmlService xmlService, ChocolateyConfiguration config) { var shouldLogSilently = (!config.Information.IsProcessElevated || !config.Information.IsUserAdministrator); var globalConfigPath = ApplicationParameters.GlobalConfigFileLocation; // save so all updated configuration items get set to existing config - FaultTolerance.try_catch_with_logging_exception( - () => xmlService.serialize(configFileSettings, globalConfigPath, isSilent: shouldLogSilently), - "Error updating '{0}'. Please ensure you have permissions to do so".format_with(globalConfigPath), + FaultTolerance.TryCatchWithLoggingException( + () => xmlService.Serialize(configFileSettings, globalConfigPath, isSilent: shouldLogSilently), + "Error updating '{0}'. Please ensure you have permissions to do so".FormatWith(globalConfigPath), logDebugInsteadOfError: true, isSilent: shouldLogSilently); } - private static void add_or_remove_licensed_source(ChocolateyLicense license, ConfigFileSettings configFileSettings) + private static void AddOrRemoveLicensedSource(ChocolateyLicense license, ConfigFileSettings configFileSettings) { // do not enable or disable the source, in case the user has disabled it var addOrUpdate = license.IsValid; - var sources = configFileSettings.Sources.or_empty_list_if_null().ToList(); + var sources = configFileSettings.Sources.OrEmpty().ToList(); var configSource = new ConfigFileSourceSetting { @@ -134,8 +137,8 @@ private static void add_or_remove_licensed_source(ChocolateyLicense license, Con }; if (addOrUpdate && !sources.Any(s => - s.Id.is_equal_to(ApplicationParameters.ChocolateyLicensedFeedSourceName) - && NugetEncryptionUtility.DecryptString(s.Password).is_equal_to(license.Id) + s.Id.IsEqualTo(ApplicationParameters.ChocolateyLicensedFeedSourceName) + && NugetEncryptionUtility.DecryptString(s.Password).IsEqualTo(license.Id) ) ) { @@ -144,36 +147,36 @@ private static void add_or_remove_licensed_source(ChocolateyLicense license, Con if (!addOrUpdate) { - configFileSettings.Sources.RemoveWhere(s => s.Id.is_equal_to(configSource.Id)); + configFileSettings.Sources.RemoveWhere(s => s.Id.IsEqualTo(configSource.Id)); } // ensure only one licensed source - helpful when moving between licenses - configFileSettings.Sources.RemoveWhere(s => s.Id.is_equal_to(configSource.Id) && !NugetEncryptionUtility.DecryptString(s.Password).is_equal_to(license.Id)); + configFileSettings.Sources.RemoveWhere(s => s.Id.IsEqualTo(configSource.Id) && !NugetEncryptionUtility.DecryptString(s.Password).IsEqualTo(license.Id)); } - private static void set_file_configuration(ChocolateyConfiguration config, ConfigFileSettings configFileSettings, IFileSystem fileSystem, Action notifyWarnLoggingAction) + private static void SetFileConfiguration(ChocolateyConfiguration config, ConfigFileSettings configFileSettings, IFileSystem fileSystem, Action notifyWarnLoggingAction) { - set_sources_in_priority_order(config, configFileSettings); - set_machine_sources(config, configFileSettings); - set_config_items(config, configFileSettings, fileSystem); + SetSourcesInPriorityOrder(config, configFileSettings); + SetMachineSources(config, configFileSettings); + SetAllConfigItems(config, configFileSettings, fileSystem); - FaultTolerance.try_catch_with_logging_exception( - () => fileSystem.create_directory_if_not_exists(config.CacheLocation), - "Could not create cache location / temp directory at '{0}'".format_with(config.CacheLocation), + FaultTolerance.TryCatchWithLoggingException( + () => fileSystem.EnsureDirectoryExists(config.CacheLocation), + "Could not create cache location / temp directory at '{0}'".FormatWith(config.CacheLocation), logWarningInsteadOfError: true); - set_feature_flags(config, configFileSettings); + SetAllFeatureFlags(config, configFileSettings); } - private static void set_sources_in_priority_order(ChocolateyConfiguration config, ConfigFileSettings configFileSettings) + private static void SetSourcesInPriorityOrder(ChocolateyConfiguration config, ConfigFileSettings configFileSettings) { var sources = new StringBuilder(); - var defaultSourcesInOrder = configFileSettings.Sources.Where(s => !s.Disabled).or_empty_list_if_null().ToList(); + var defaultSourcesInOrder = configFileSettings.Sources.Where(s => !s.Disabled).OrEmpty().ToList(); if (configFileSettings.Sources.Any(s => s.Priority > 0)) { - defaultSourcesInOrder = configFileSettings.Sources.Where(s => !s.Disabled && s.Priority != 0).OrderBy(s => s.Priority).or_empty_list_if_null().ToList(); - defaultSourcesInOrder.AddRange(configFileSettings.Sources.Where(s => !s.Disabled && s.Priority == 0).or_empty_list_if_null().ToList()); + defaultSourcesInOrder = configFileSettings.Sources.Where(s => !s.Disabled && s.Priority != 0).OrderBy(s => s.Priority).OrEmpty().ToList(); + defaultSourcesInOrder.AddRange(configFileSettings.Sources.Where(s => !s.Disabled && s.Priority == 0).OrEmpty().ToList()); } foreach (var source in defaultSourcesInOrder) @@ -186,13 +189,13 @@ private static void set_sources_in_priority_order(ChocolateyConfiguration config } } - private static void set_machine_sources(ChocolateyConfiguration config, ConfigFileSettings configFileSettings) + private static void SetMachineSources(ChocolateyConfiguration config, ConfigFileSettings configFileSettings) { - var defaultSourcesInOrder = configFileSettings.Sources.Where(s => !s.Disabled).or_empty_list_if_null().ToList(); + var defaultSourcesInOrder = configFileSettings.Sources.Where(s => !s.Disabled).OrEmpty().ToList(); if (configFileSettings.Sources.Any(s => s.Priority > 0)) { - defaultSourcesInOrder = configFileSettings.Sources.Where(s => !s.Disabled && s.Priority != 0).OrderBy(s => s.Priority).or_empty_list_if_null().ToList(); - defaultSourcesInOrder.AddRange(configFileSettings.Sources.Where(s => !s.Disabled && s.Priority == 0).or_empty_list_if_null().ToList()); + defaultSourcesInOrder = configFileSettings.Sources.Where(s => !s.Disabled && s.Priority != 0).OrderBy(s => s.Priority).OrEmpty().ToList(); + defaultSourcesInOrder.AddRange(configFileSettings.Sources.Where(s => !s.Disabled && s.Priority == 0).OrEmpty().ToList()); } foreach (var source in defaultSourcesInOrder) @@ -213,26 +216,26 @@ private static void set_machine_sources(ChocolateyConfiguration config, ConfigFi } } - private static void set_config_items(ChocolateyConfiguration config, ConfigFileSettings configFileSettings, IFileSystem fileSystem) + private static void SetAllConfigItems(ChocolateyConfiguration config, ConfigFileSettings configFileSettings, IFileSystem fileSystem) { if (string.IsNullOrWhiteSpace(config.CacheLocation)) { - config.CacheLocation = fileSystem.get_temp_path(); // System.Environment.GetEnvironmentVariable("TEMP"); + config.CacheLocation = fileSystem.GetTempPath(); // System.Environment.GetEnvironmentVariable("TEMP"); // TEMP gets set in EnvironmentSettings, so it may already have // chocolatey in the path when it installs the next package from // the API. - if (!string.Equals(fileSystem.get_directory_info_for(config.CacheLocation).Name, "chocolatey", StringComparison.OrdinalIgnoreCase)) + if (!string.Equals(fileSystem.GetDirectoryInfo(config.CacheLocation).Name, "chocolatey", StringComparison.OrdinalIgnoreCase)) { - config.CacheLocation = fileSystem.combine_paths(fileSystem.get_temp_path(), "chocolatey"); + config.CacheLocation = fileSystem.CombinePaths(fileSystem.GetTempPath(), "chocolatey"); } } // if it is still empty, use temp in the Chocolatey install directory. - if (string.IsNullOrWhiteSpace(config.CacheLocation)) config.CacheLocation = fileSystem.combine_paths(ApplicationParameters.InstallLocation, "temp"); + if (string.IsNullOrWhiteSpace(config.CacheLocation)) config.CacheLocation = fileSystem.CombinePaths(ApplicationParameters.InstallLocation, "temp"); var commandExecutionTimeoutSeconds = 0; var commandExecutionTimeout = configFileSettings.ConfigSettings - .Where(f => f.Key.is_equal_to(ApplicationParameters.ConfigSettings.CommandExecutionTimeoutSeconds)) + .Where(f => f.Key.IsEqualTo(ApplicationParameters.ConfigSettings.CommandExecutionTimeoutSeconds)) .Select(c => c.Value) .FirstOrDefault(); @@ -240,38 +243,38 @@ private static void set_config_items(ChocolateyConfiguration config, ConfigFileS config.CommandExecutionTimeoutSeconds = commandExecutionTimeoutSeconds; if (commandExecutionTimeout != "0" && commandExecutionTimeoutSeconds <= 0) { - set_config_item(ApplicationParameters.ConfigSettings.CommandExecutionTimeoutSeconds, configFileSettings, ApplicationParameters.DefaultWaitForExitInSeconds.to_string(), "Default timeout for command execution. '0' for infinite (starting in 0.10.4). It is recommended that organizations bump this up to at least 4 hours (14400).", forceSettingValue: true); + SetConfigItem(ApplicationParameters.ConfigSettings.CommandExecutionTimeoutSeconds, configFileSettings, ApplicationParameters.DefaultWaitForExitInSeconds.ToStringSafe(), "Default timeout for command execution. Set to '0' for infinite. It is recommended that organizations bump this up to at least 4 hours (14400).", forceSettingValue: true); config.CommandExecutionTimeoutSeconds = ApplicationParameters.DefaultWaitForExitInSeconds; } var webRequestTimeoutSeconds = -1; int.TryParse( - set_config_item( + SetConfigItem( ApplicationParameters.ConfigSettings.WebRequestTimeoutSeconds, configFileSettings, - ApplicationParameters.DefaultWebRequestTimeoutInSeconds.to_string(), - "Default timeout for web requests. Available in 0.9.10+."), + ApplicationParameters.DefaultWebRequestTimeoutInSeconds.ToStringSafe(), + "Default timeout for web requests."), out webRequestTimeoutSeconds); if (webRequestTimeoutSeconds <= 0) { webRequestTimeoutSeconds = ApplicationParameters.DefaultWebRequestTimeoutInSeconds; - set_config_item(ApplicationParameters.ConfigSettings.WebRequestTimeoutSeconds, configFileSettings, ApplicationParameters.DefaultWebRequestTimeoutInSeconds.to_string(), "Default timeout for web requests. Available in 0.9.10+.", forceSettingValue: true); + SetConfigItem(ApplicationParameters.ConfigSettings.WebRequestTimeoutSeconds, configFileSettings, ApplicationParameters.DefaultWebRequestTimeoutInSeconds.ToStringSafe(), "Default timeout for web requests.", forceSettingValue: true); } config.WebRequestTimeoutSeconds = webRequestTimeoutSeconds; - config.Proxy.Location = set_config_item(ApplicationParameters.ConfigSettings.Proxy, configFileSettings, string.Empty, "Explicit proxy location. Available in 0.9.9.9+."); - config.Proxy.User = set_config_item(ApplicationParameters.ConfigSettings.ProxyUser, configFileSettings, string.Empty, "Optional proxy user. Available in 0.9.9.9+."); - config.Proxy.EncryptedPassword = set_config_item(ApplicationParameters.ConfigSettings.ProxyPassword, configFileSettings, string.Empty, "Optional proxy password. Encrypted. Available in 0.9.9.9+."); - config.Proxy.BypassList = set_config_item(ApplicationParameters.ConfigSettings.ProxyBypassList, configFileSettings, string.Empty, "Optional proxy bypass list. Comma separated. Available in 0.10.4+."); - config.Proxy.BypassOnLocal = set_config_item(ApplicationParameters.ConfigSettings.ProxyBypassOnLocal, configFileSettings, "true", "Bypass proxy for local connections. Available in 0.10.4+.").is_equal_to(bool.TrueString); - config.UpgradeCommand.PackageNamesToSkip = set_config_item(ApplicationParameters.ConfigSettings.UpgradeAllExceptions, configFileSettings, string.Empty, "A comma-separated list of package names that should not be upgraded when running `choco upgrade all'. Defaults to empty. Available in 0.10.14+."); - config.DefaultTemplateName = set_config_item(ApplicationParameters.ConfigSettings.DefaultTemplateName, configFileSettings, string.Empty, "Default template name used when running 'choco new' command. Available in 0.12.0+."); - config.PushCommand.DefaultSource = set_config_item(ApplicationParameters.ConfigSettings.DefaultPushSource, configFileSettings, string.Empty, "Default source to push packages to when running 'choco push' command. Available in 2.0.0+."); + config.Proxy.Location = SetConfigItem(ApplicationParameters.ConfigSettings.Proxy, configFileSettings, string.Empty, "Explicit proxy location."); + config.Proxy.User = SetConfigItem(ApplicationParameters.ConfigSettings.ProxyUser, configFileSettings, string.Empty, "Optional proxy user."); + config.Proxy.EncryptedPassword = SetConfigItem(ApplicationParameters.ConfigSettings.ProxyPassword, configFileSettings, string.Empty, "Optional proxy password. Encrypted."); + config.Proxy.BypassList = SetConfigItem(ApplicationParameters.ConfigSettings.ProxyBypassList, configFileSettings, string.Empty, "Optional proxy bypass list. Comma separated."); + config.Proxy.BypassOnLocal = SetConfigItem(ApplicationParameters.ConfigSettings.ProxyBypassOnLocal, configFileSettings, "true", "Bypass proxy for local connections.").IsEqualTo(bool.TrueString); + config.UpgradeCommand.PackageNamesToSkip = SetConfigItem(ApplicationParameters.ConfigSettings.UpgradeAllExceptions, configFileSettings, string.Empty, "A comma-separated list of package names that should not be upgraded when running `choco upgrade all'. Defaults to empty."); + config.DefaultTemplateName = SetConfigItem(ApplicationParameters.ConfigSettings.DefaultTemplateName, configFileSettings, string.Empty, "Default template name used when running 'choco new' command."); + config.PushCommand.DefaultSource = SetConfigItem(ApplicationParameters.ConfigSettings.DefaultPushSource, configFileSettings, string.Empty, "Default source to push packages to when running 'choco push' command."); } - private static string set_config_item(string configName, ConfigFileSettings configFileSettings, string defaultValue, string description, bool forceSettingValue = false) + private static string SetConfigItem(string configName, ConfigFileSettings configFileSettings, string defaultValue, string description, bool forceSettingValue = false) { - var config = configFileSettings.ConfigSettings.FirstOrDefault(f => f.Key.is_equal_to(configName)); + var config = configFileSettings.ConfigSettings.FirstOrDefault(f => f.Key.IsEqualTo(configName)); if (config == null) { config = new ConfigFileConfigSetting @@ -293,40 +296,40 @@ private static string set_config_item(string configName, ConfigFileSettings conf return config.Value; } - private static void set_feature_flags(ChocolateyConfiguration config, ConfigFileSettings configFileSettings) + private static void SetAllFeatureFlags(ChocolateyConfiguration config, ConfigFileSettings configFileSettings) { - config.Features.ChecksumFiles = set_feature_flag(ApplicationParameters.Features.ChecksumFiles, configFileSettings, defaultEnabled: true, description: "Checksum files when pulled in from internet (based on package)."); - config.Features.AllowEmptyChecksums = set_feature_flag(ApplicationParameters.Features.AllowEmptyChecksums, configFileSettings, defaultEnabled: false, description: "Allow packages to have empty/missing checksums for downloaded resources from non-secure locations (HTTP, FTP). Enabling is not recommended if using sources that download resources from the internet. Available in 0.10.0+."); - config.Features.AllowEmptyChecksumsSecure = set_feature_flag(ApplicationParameters.Features.AllowEmptyChecksumsSecure, configFileSettings, defaultEnabled: true, description: "Allow packages to have empty/missing checksums for downloaded resources from secure locations (HTTPS). Available in 0.10.0+."); - config.Features.AutoUninstaller = set_feature_flag(ApplicationParameters.Features.AutoUninstaller, configFileSettings, defaultEnabled: true, description: "Uninstall from programs and features without requiring an explicit uninstall script."); - config.Features.FailOnAutoUninstaller = set_feature_flag(ApplicationParameters.Features.FailOnAutoUninstaller, configFileSettings, defaultEnabled: false, description: "Fail if automatic uninstaller fails."); - config.Features.FailOnStandardError = set_feature_flag(ApplicationParameters.Features.FailOnStandardError, configFileSettings, defaultEnabled: false, description: "Fail if install provider writes to stderr. Not recommended for use. Available in 0.9.10+."); - config.Features.UsePowerShellHost = set_feature_flag(ApplicationParameters.Features.UsePowerShellHost, configFileSettings, defaultEnabled: true, description: "Use Chocolatey's built-in PowerShell host. Available in 0.9.10+."); - config.Features.LogEnvironmentValues = set_feature_flag(ApplicationParameters.Features.LogEnvironmentValues, configFileSettings, defaultEnabled: false, description: "Log Environment Values - will log values of environment before and after install (could disclose sensitive data). Available in 0.9.10+."); - config.Features.VirusCheck = set_feature_flag(ApplicationParameters.Features.VirusCheck, configFileSettings, defaultEnabled: false, description: "Virus Check - perform virus checking on downloaded files. Available in 0.9.10+. Licensed versions only."); - config.Features.FailOnInvalidOrMissingLicense = set_feature_flag(ApplicationParameters.Features.FailOnInvalidOrMissingLicense, configFileSettings, defaultEnabled: false, description: "Fail On Invalid Or Missing License - allows knowing when a license is expired or not applied to a machine. Available in 0.9.10+."); - config.Features.IgnoreInvalidOptionsSwitches = set_feature_flag(ApplicationParameters.Features.IgnoreInvalidOptionsSwitches, configFileSettings, defaultEnabled: true, description: "Ignore Invalid Options/Switches - If a switch or option is passed that is not recognized, should choco fail? Available in 0.9.10+."); - config.Features.UsePackageExitCodes = set_feature_flag(ApplicationParameters.Features.UsePackageExitCodes, configFileSettings, defaultEnabled: true, description: "Use Package Exit Codes - Package scripts can provide exit codes. With this on, package exit codes will be what choco uses for exit when non-zero (this value can come from a dependency package). Chocolatey defines valid exit codes as 0, 1605, 1614, 1641, 3010. With this feature off, choco will exit with 0, 1, or -1 (matching previous behavior). Available in 0.9.10+."); - config.Features.UseEnhancedExitCodes = set_feature_flag(ApplicationParameters.Features.UseEnhancedExitCodes, configFileSettings, defaultEnabled: false, description: "Use Enhanced Exit Codes - Chocolatey is able to provide enhanced exit codes surrounding list, search, info, outdated and other commands that don't deal directly with package operations. To see enhanced exit codes and their meanings, please run `choco [cmdname] -?`. With this feature off, choco will exit with 0, 1, or -1 (matching previous behavior). Available in 0.10.12+."); - config.Features.ExitOnRebootDetected = set_feature_flag(ApplicationParameters.Features.ExitOnRebootDetected, configFileSettings, defaultEnabled: false, description: "Exit On Reboot Detected - Stop running install, upgrade, or uninstall when a reboot request is detected. Requires '{0}' feature to be turned on. Will exit with either {1} or {2}. When it exits with {1}, it means pending reboot discovered prior to running operation. When it exits with {2}, it means some work completed prior to reboot request being detected. Available in 0.10.12+.".format_with(ApplicationParameters.Features.UsePackageExitCodes, ApplicationParameters.ExitCodes.ErrorFailNoActionReboot, ApplicationParameters.ExitCodes.ErrorInstallSuspend)); - config.Features.UseFipsCompliantChecksums = set_feature_flag(ApplicationParameters.Features.UseFipsCompliantChecksums, configFileSettings, defaultEnabled: false, description: "Use FIPS Compliant Checksums - Ensure checksumming done by choco uses FIPS compliant algorithms. Not recommended unless required by FIPS Mode. Enabling on an existing installation could have unintended consequences related to upgrades/uninstalls. Available in 0.9.10+."); - config.Features.ShowNonElevatedWarnings = set_feature_flag(ApplicationParameters.Features.ShowNonElevatedWarnings, configFileSettings, defaultEnabled: true, description: "Show Non-Elevated Warnings - Display non-elevated warnings. Available in 0.10.4+."); - config.Features.ShowDownloadProgress = set_feature_flag(ApplicationParameters.Features.ShowDownloadProgress, configFileSettings, defaultEnabled: true, description: "Show Download Progress - Show download progress percentages in the CLI. Available in 0.10.4+."); - config.Features.StopOnFirstPackageFailure = set_feature_flag(ApplicationParameters.Features.StopOnFirstPackageFailure, configFileSettings, defaultEnabled: false, description: "Stop On First Package Failure - Stop running install, upgrade or uninstall on first package failure instead of continuing with others. As this will affect upgrade all, it is normally recommended to leave this off. Available in 0.10.4+."); - config.Features.UseRememberedArgumentsForUpgrades = set_feature_flag(ApplicationParameters.Features.UseRememberedArgumentsForUpgrades, configFileSettings, defaultEnabled: false, description: "Use Remembered Arguments For Upgrades - When running upgrades, use arguments for upgrade that were used for installation ('remembered'). This is helpful when running upgrade for all packages. Available in 0.10.4+. This is considered in preview for 0.10.4 and will be flipped to on by default in a future release."); - config.Features.IgnoreUnfoundPackagesOnUpgradeOutdated = set_feature_flag(ApplicationParameters.Features.IgnoreUnfoundPackagesOnUpgradeOutdated, configFileSettings, defaultEnabled: false, description: "Ignore Unfound Packages On Upgrade Outdated - When checking outdated or upgrades, if a package is not found against sources specified, don't report the package at all. Available in 0.10.9+."); - config.Features.SkipPackageUpgradesWhenNotInstalled = set_feature_flag(ApplicationParameters.Features.SkipPackageUpgradesWhenNotInstalled, configFileSettings, defaultEnabled: false, description: "Skip Packages Not Installed During Upgrade - if a package is not installed, do not install it during the upgrade process. Available in 0.10.12+."); - config.Features.RemovePackageInformationOnUninstall = set_feature_flag(ApplicationParameters.Features.RemovePackageInformationOnUninstall, configFileSettings, defaultEnabled: false, description: "Remove Stored Package Information On Uninstall - When a package is uninstalled, should the stored package information also be removed? Available in 0.10.9+."); - config.Features.LogWithoutColor = set_feature_flag(ApplicationParameters.Features.LogWithoutColor, configFileSettings, defaultEnabled: false, description: "Log without color - Do not show colorization in logging output. Available in 0.10.9+."); - config.Features.LogValidationResultsOnWarnings = set_feature_flag(ApplicationParameters.Features.LogValidationResultsOnWarnings, configFileSettings, defaultEnabled: true, description: "Log validation results on warnings - Should the validation results be logged if there are warnings? Available in 0.10.12+."); - config.Features.UsePackageRepositoryOptimizations = set_feature_flag(ApplicationParameters.Features.UsePackageRepositoryOptimizations, configFileSettings, defaultEnabled: true, description: "Use Package Repository Optimizations - Turn on optimizations for reducing bandwidth with repository queries during package install/upgrade/outdated operations. Should generally be left enabled, unless a repository needs to support older methods of query. When disabled, this makes queries similar to the way they were done in Chocolatey v0.10.11 and before. Available in 0.10.14+."); - config.PromptForConfirmation = !set_feature_flag(ApplicationParameters.Features.AllowGlobalConfirmation, configFileSettings, defaultEnabled: false, description: "Prompt for confirmation in scripts or bypass."); - config.DisableCompatibilityChecks = set_feature_flag(ApplicationParameters.Features.DisableCompatibilityChecks, configFileSettings, defaultEnabled: false, description: "Disable Compatibility Checks - Should a warning we shown, before and after command execution, when a runtime compatibility check determines that there is an incompatibility between Chocolatey and Chocolatey Licensed Extension. Available in 1.1.0+"); + config.Features.ChecksumFiles = SetFeatureFlag(ApplicationParameters.Features.ChecksumFiles, configFileSettings, defaultEnabled: true, description: "Checksum files when pulled in from internet (based on package)."); + config.Features.AllowEmptyChecksums = SetFeatureFlag(ApplicationParameters.Features.AllowEmptyChecksums, configFileSettings, defaultEnabled: false, description: "Allow packages to have empty/missing checksums for downloaded resources from non-secure locations (HTTP, FTP). Enabling is not recommended if using sources that download resources from the internet."); + config.Features.AllowEmptyChecksumsSecure = SetFeatureFlag(ApplicationParameters.Features.AllowEmptyChecksumsSecure, configFileSettings, defaultEnabled: true, description: "Allow packages to have empty/missing checksums for downloaded resources from secure locations (HTTPS)."); + config.Features.AutoUninstaller = SetFeatureFlag(ApplicationParameters.Features.AutoUninstaller, configFileSettings, defaultEnabled: true, description: "Uninstall from programs and features without requiring an explicit uninstall script."); + config.Features.FailOnAutoUninstaller = SetFeatureFlag(ApplicationParameters.Features.FailOnAutoUninstaller, configFileSettings, defaultEnabled: false, description: "Fail if automatic uninstaller fails."); + config.Features.FailOnStandardError = SetFeatureFlag(ApplicationParameters.Features.FailOnStandardError, configFileSettings, defaultEnabled: false, description: "Fail if install provider writes to stderr. Not recommended for use."); + config.Features.UsePowerShellHost = SetFeatureFlag(ApplicationParameters.Features.UsePowerShellHost, configFileSettings, defaultEnabled: true, description: "Use Chocolatey's built-in PowerShell host."); + config.Features.LogEnvironmentValues = SetFeatureFlag(ApplicationParameters.Features.LogEnvironmentValues, configFileSettings, defaultEnabled: false, description: "Log Environment Values - will log values of environment before and after install (could disclose sensitive data)."); + config.Features.VirusCheck = SetFeatureFlag(ApplicationParameters.Features.VirusCheck, configFileSettings, defaultEnabled: false, description: "Virus Check - perform virus checking on downloaded files. Licensed versions only."); + config.Features.FailOnInvalidOrMissingLicense = SetFeatureFlag(ApplicationParameters.Features.FailOnInvalidOrMissingLicense, configFileSettings, defaultEnabled: false, description: "Fail On Invalid Or Missing License - allows knowing when a license is expired or not applied to a machine."); + config.Features.IgnoreInvalidOptionsSwitches = SetFeatureFlag(ApplicationParameters.Features.IgnoreInvalidOptionsSwitches, configFileSettings, defaultEnabled: true, description: "Ignore Invalid Options/Switches - If a switch or option is passed that is not recognized, should choco fail?"); + config.Features.UsePackageExitCodes = SetFeatureFlag(ApplicationParameters.Features.UsePackageExitCodes, configFileSettings, defaultEnabled: true, description: "Use Package Exit Codes - Package scripts can provide exit codes. With this on, package exit codes will be what choco uses for exit when non-zero (this value can come from a dependency package). Chocolatey defines valid exit codes as 0, 1605, 1614, 1641, 3010. With this feature off, choco will exit with 0, 1, or -1 (matching previous behavior)."); + config.Features.UseEnhancedExitCodes = SetFeatureFlag(ApplicationParameters.Features.UseEnhancedExitCodes, configFileSettings, defaultEnabled: false, description: "Use Enhanced Exit Codes - Chocolatey is able to provide enhanced exit codes surrounding list, search, info, outdated and other commands that don't deal directly with package operations. To see enhanced exit codes and their meanings, please run `choco [cmdname] -?`. With this feature off, choco will exit with 0, 1, or -1 (matching previous behavior)."); + config.Features.ExitOnRebootDetected = SetFeatureFlag(ApplicationParameters.Features.ExitOnRebootDetected, configFileSettings, defaultEnabled: false, description: "Exit On Reboot Detected - Stop running install, upgrade, or uninstall when a reboot request is detected. Requires '{0}' feature to be turned on. Will exit with either {1} or {2}. When it exits with {1}, it means pending reboot discovered prior to running operation. When it exits with {2}, it means some work completed prior to reboot request being detected.".FormatWith(ApplicationParameters.Features.UsePackageExitCodes, ApplicationParameters.ExitCodes.ErrorFailNoActionReboot, ApplicationParameters.ExitCodes.ErrorInstallSuspend)); + config.Features.UseFipsCompliantChecksums = SetFeatureFlag(ApplicationParameters.Features.UseFipsCompliantChecksums, configFileSettings, defaultEnabled: false, description: "Use FIPS Compliant Checksums - Ensure checksumming done by choco uses FIPS compliant algorithms. Not recommended unless required by FIPS Mode. Enabling on an existing installation could have unintended consequences related to upgrades/uninstalls."); + config.Features.ShowNonElevatedWarnings = SetFeatureFlag(ApplicationParameters.Features.ShowNonElevatedWarnings, configFileSettings, defaultEnabled: true, description: "Show Non-Elevated Warnings - Display non-elevated warnings."); + config.Features.ShowDownloadProgress = SetFeatureFlag(ApplicationParameters.Features.ShowDownloadProgress, configFileSettings, defaultEnabled: true, description: "Show Download Progress - Show download progress percentages in the CLI."); + config.Features.StopOnFirstPackageFailure = SetFeatureFlag(ApplicationParameters.Features.StopOnFirstPackageFailure, configFileSettings, defaultEnabled: false, description: "Stop On First Package Failure - Stop running install, upgrade or uninstall on first package failure instead of continuing with others. As this will affect upgrade all, it is normally recommended to leave this off."); + config.Features.UseRememberedArgumentsForUpgrades = SetFeatureFlag(ApplicationParameters.Features.UseRememberedArgumentsForUpgrades, configFileSettings, defaultEnabled: false, description: "Use Remembered Arguments For Upgrades - When running upgrades, use arguments for upgrade that were used for installation ('remembered'). This is helpful when running upgrade for all packages. This is considered in preview and will be flipped to on by default in a future release."); + config.Features.IgnoreUnfoundPackagesOnUpgradeOutdated = SetFeatureFlag(ApplicationParameters.Features.IgnoreUnfoundPackagesOnUpgradeOutdated, configFileSettings, defaultEnabled: false, description: "Ignore Unfound Packages On Upgrade Outdated - When checking outdated or upgrades, if a package is not found against sources specified, don't report the package at all."); + config.Features.SkipPackageUpgradesWhenNotInstalled = SetFeatureFlag(ApplicationParameters.Features.SkipPackageUpgradesWhenNotInstalled, configFileSettings, defaultEnabled: false, description: "Skip Packages Not Installed During Upgrade - if a package is not installed, do not install it during the upgrade process."); + config.Features.RemovePackageInformationOnUninstall = SetFeatureFlag(ApplicationParameters.Features.RemovePackageInformationOnUninstall, configFileSettings, defaultEnabled: false, description: "Remove Stored Package Information On Uninstall - When a package is uninstalled, should the stored package information also be removed? "); + config.Features.LogWithoutColor = SetFeatureFlag(ApplicationParameters.Features.LogWithoutColor, configFileSettings, defaultEnabled: false, description: "Log without color - Do not show colorization in logging output."); + config.Features.LogValidationResultsOnWarnings = SetFeatureFlag(ApplicationParameters.Features.LogValidationResultsOnWarnings, configFileSettings, defaultEnabled: true, description: "Log validation results on warnings - Should the validation results be logged if there are warnings?"); + config.Features.UsePackageRepositoryOptimizations = SetFeatureFlag(ApplicationParameters.Features.UsePackageRepositoryOptimizations, configFileSettings, defaultEnabled: true, description: "Use Package Repository Optimizations - Turn on optimizations for reducing bandwidth with repository queries during package install/upgrade/outdated operations. Should generally be left enabled, unless a repository needs to support older methods of query. When disabled, this makes queries similar to the way they were done in earlier versions of Chocolatey."); + config.PromptForConfirmation = !SetFeatureFlag(ApplicationParameters.Features.AllowGlobalConfirmation, configFileSettings, defaultEnabled: false, description: "Prompt for confirmation in scripts or bypass."); + config.DisableCompatibilityChecks = SetFeatureFlag(ApplicationParameters.Features.DisableCompatibilityChecks, configFileSettings, defaultEnabled: false, description: "Disable Compatibility Checks - Should a warning we shown, before and after command execution, when a runtime compatibility check determines that there is an incompatibility between Chocolatey and Chocolatey Licensed Extension. Available in 1.1.0+"); } - private static bool set_feature_flag(string featureName, ConfigFileSettings configFileSettings, bool defaultEnabled, string description) + private static bool SetFeatureFlag(string featureName, ConfigFileSettings configFileSettings, bool defaultEnabled, string description) { - var feature = configFileSettings.Features.FirstOrDefault(f => f.Name.is_equal_to(featureName)); + var feature = configFileSettings.Features.FirstOrDefault(f => f.Name.IsEqualTo(featureName)); if (feature == null) { @@ -352,14 +355,14 @@ private static bool set_feature_flag(string featureName, ConfigFileSettings conf return feature != null ? feature.Enabled : defaultEnabled; } - private static void set_global_options(IList args, ChocolateyConfiguration config, Container container) + private static void SetGlobalOptions(IList args, ChocolateyConfiguration config, Container container) { - ConfigurationOptions.parse_arguments_and_update_configuration( + ConfigurationOptions.ParseArgumentsAndUpdateConfiguration( args, config, - (option_set) => + (optionSet) => { - option_set + optionSet .Add("d|debug", "Debug - Show debug messaging.", option => config.Debug = option != null) @@ -367,10 +370,10 @@ private static void set_global_options(IList args, ChocolateyConfigurati "Verbose - Show verbose messaging. Very verbose messaging, avoid using under normal circumstances.", option => config.Verbose = option != null) .Add("trace", - "Trace - Show trace messaging. Very, very verbose trace messaging. Avoid except when needing super low-level .NET Framework debugging. Available in 0.10.4+.", + "Trace - Show trace messaging. Very, very verbose trace messaging. Avoid except when needing super low-level .NET Framework debugging.", option => config.Trace = option != null) .Add("nocolor|no-color", - "No Color - Do not show colorization in logging output. This overrides the feature '{0}', set to '{1}'. Available in 0.10.9+.".format_with(ApplicationParameters.Features.LogWithoutColor, config.Features.LogWithoutColor), + "No Color - Do not show colorization in logging output. This overrides the feature '{0}', set to '{1}'.".FormatWith(ApplicationParameters.Features.LogWithoutColor, config.Features.LogWithoutColor), option => config.Features.LogWithoutColor = option != null) .Add("acceptlicense|accept-license", "AcceptLicense - Accept license dialogs automatically. Reserved for future use.", @@ -392,20 +395,20 @@ private static void set_global_options(IList args, ChocolateyConfigurati "LimitOutput - Limit the output to essential information", option => config.RegularOutput = option == null) .Add("timeout=|execution-timeout=", - "CommandExecutionTimeout (in seconds) - The time to allow a command to finish before timing out. Overrides the default execution timeout in the configuration of {0} seconds. '0' for infinite starting in 0.10.4.".format_with(config.CommandExecutionTimeoutSeconds.to_string()), + "CommandExecutionTimeout (in seconds) - The time to allow a command to finish before timing out. Overrides the default execution timeout in the configuration of {0} seconds. Supply '0' to disable the timeout.".FormatWith(config.CommandExecutionTimeoutSeconds.ToStringSafe()), option => { int timeout = 0; - var timeoutString = option.remove_surrounding_quotes(); + var timeoutString = option.UnquoteSafe(); int.TryParse(timeoutString, out timeout); - if (timeout > 0 || timeoutString.is_equal_to("0")) + if (timeout > 0 || timeoutString.IsEqualTo("0")) { config.CommandExecutionTimeoutSeconds = timeout; } }) .Add("c=|cache=|cachelocation=|cache-location=", "CacheLocation - Location for download cache, defaults to %TEMP% or value in chocolatey.config file.", - option => config.CacheLocation = option.remove_surrounding_quotes()) + option => config.CacheLocation = option.UnquoteSafe()) .Add("allowunofficial|allow-unofficial|allowunofficialbuild|allow-unofficial-build", "AllowUnofficialBuild - When not using the official build you must set this flag for choco to continue.", option => config.AllowUnofficialBuild = option != null) @@ -413,29 +416,29 @@ private static void set_global_options(IList args, ChocolateyConfigurati "FailOnStandardError - Fail on standard error output (stderr), typically received when running external commands during install providers. This overrides the feature failOnStandardError.", option => config.Features.FailOnStandardError = option != null) .Add("use-system-powershell", - "UseSystemPowerShell - Execute PowerShell using an external process instead of the built-in PowerShell host. Should only be used when internal host is failing. Available in 0.9.10+.", + "UseSystemPowerShell - Execute PowerShell using an external process instead of the built-in PowerShell host. Should only be used when internal host is failing.", option => config.Features.UsePowerShellHost = option == null) .Add("no-progress", - "Do Not Show Progress - Do not show download progress percentages. Available in 0.10.4+.", + "Do Not Show Progress - Do not show download progress percentages.", option => config.Features.ShowDownloadProgress = option == null) .Add("proxy=", - "Proxy Location - Explicit proxy location. Overrides the default proxy location of '{0}'. Available for config settings in 0.9.9.9+, this CLI option available in 0.10.4+.".format_with(config.Proxy.Location), - option => config.Proxy.Location = option.remove_surrounding_quotes()) + "Proxy Location - Explicit proxy location. Overrides the default proxy location of '{0}'.".FormatWith(config.Proxy.Location), + option => config.Proxy.Location = option.UnquoteSafe()) .Add("proxy-user=", - "Proxy User Name - Explicit proxy user (optional). Requires explicit proxy (`--proxy` or config setting). Overrides the default proxy user of '{0}'. Available for config settings in 0.9.9.9+, this CLI option available in 0.10.4+.".format_with(config.Proxy.User), - option => config.Proxy.User = option.remove_surrounding_quotes()) + "Proxy User Name - Explicit proxy user (optional). Requires explicit proxy (`--proxy` or config setting). Overrides the default proxy user of '{0}'.".FormatWith(config.Proxy.User), + option => config.Proxy.User = option.UnquoteSafe()) .Add("proxy-password=", - "Proxy Password - Explicit proxy password (optional) to be used with username. Requires explicit proxy (`--proxy` or config setting) and user name. Overrides the default proxy password (encrypted in settings if set). Available for config settings in 0.9.9.9+, this CLI option available in 0.10.4+.", - option => config.Proxy.EncryptedPassword = NugetEncryptionUtility.EncryptString(option.remove_surrounding_quotes())) + "Proxy Password - Explicit proxy password (optional) to be used with username. Requires explicit proxy (`--proxy` or config setting) and user name. Overrides the default proxy password (encrypted in settings if set).", + option => config.Proxy.EncryptedPassword = NugetEncryptionUtility.EncryptString(option.UnquoteSafe())) .Add("proxy-bypass-list=", - "ProxyBypassList - Comma separated list of regex locations to bypass on proxy. Requires explicit proxy (`--proxy` or config setting). Overrides the default proxy bypass list of '{0}'. Available in 0.10.4+.".format_with(config.Proxy.BypassList), - option => config.Proxy.BypassList = option.remove_surrounding_quotes()) + "ProxyBypassList - Comma separated list of regex locations to bypass on proxy. Requires explicit proxy (`--proxy` or config setting). Overrides the default proxy bypass list of '{0}'.".FormatWith(config.Proxy.BypassList), + option => config.Proxy.BypassList = option.UnquoteSafe()) .Add("proxy-bypass-on-local", - "Proxy Bypass On Local - Bypass proxy for local connections. Requires explicit proxy (`--proxy` or config setting). Overrides the default proxy bypass on local setting of '{0}'. Available in 0.10.4+.".format_with(config.Proxy.BypassOnLocal), + "Proxy Bypass On Local - Bypass proxy for local connections. Requires explicit proxy (`--proxy` or config setting). Overrides the default proxy bypass on local setting of '{0}'.".FormatWith(config.Proxy.BypassOnLocal), option => config.Proxy.BypassOnLocal = option != null) .Add("log-file=", - "Log File to output to in addition to regular loggers. Available in 0.10.8+.", - option => config.AdditionalLogFileLocation = option.remove_surrounding_quotes()) + "Log File to output to in addition to regular loggers.", + option => config.AdditionalLogFileLocation = option.UnquoteSafe()) .Add("skipcompatibilitychecks|skip-compatibility-checks", "SkipCompatibilityChecks - Prevent warnings being shown before and after command execution when a runtime compatibility problem is found between the version of Chocolatey and the Chocolatey Licensed Extension. Available in 1.1.0+", option => config.DisableCompatibilityChecks = option != null) @@ -445,25 +448,76 @@ private static void set_global_options(IList args, ChocolateyConfigurati { if (!string.IsNullOrWhiteSpace(config.CommandName)) { - // save help for next menu + // This method is called twice each run, once when setting the command name and global options (here), and then to set all the + // command-specific options and actually execute the command. + // To ensure correct operation, we need to reset the help options to false in the first execution, to then have them + // parsed correctly in the second iteration. config.HelpRequested = false; + config.ShowOnlineHelp = false; config.UnsuccessfulParsing = false; } }, () => { }, () => { - ChocolateyHelpCommand.display_help_message(container); + ChocolateyHelpCommand.DisplayHelpMessage(container); }); } - private static void set_environment_options(ChocolateyConfiguration config) + private static void SetProxyOptions(ChocolateyConfiguration config, Container container) + { + // Evaluation order of Proxy settings: System Set -> Environment Variable Set -> Chocolatey Configuration File Set -> CLI Passed in Argument + var proxyAlreadySet = !string.IsNullOrWhiteSpace(config.Proxy.Location); + var onWindows = Platform.GetPlatform() == PlatformType.Windows; + + // Only Windows has a registry provider, if it's already set, or we're not on Windows we don't need to continue. + if (proxyAlreadySet || !onWindows) + { + return; + } + + // We don't yet have a Proxy Location, check if the system has one configured in the registry + var registryService = container.GetInstance(); + var internetSettingsRegKey = registryService.GetKey(RegistryHive.CurrentUser, "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Internet Settings"); + + if (!internetSettingsRegKey.GetValue("ProxyEnable").ToStringSafe().IsEqualTo("1")) + { + return; + } + + var proxySetting = internetSettingsRegKey.GetValue("ProxyServer").ToStringSafe(); + + if (string.IsNullOrWhiteSpace(proxySetting)) + { + return; + } + + if (proxySetting.IndexOf(';') != -1) + { + var allProxies = proxySetting.Split(';'); + proxySetting = allProxies.FirstOrDefault(s => s.TrimSafe().StartsWith("https=")); + + if (string.IsNullOrWhiteSpace(proxySetting)) + { + proxySetting = allProxies.FirstOrDefault(s => s.TrimSafe().StartsWith("http=")); + } + } + + if (proxySetting?.IndexOf('=') != -1 && !proxySetting.StartsWith("http")) + { + return; + } + + config.Proxy.Location = proxySetting.Split('=').LastOrDefault(); + } + + private static void SetEnvironmentOptions(ChocolateyConfiguration config) { - config.Information.PlatformType = Platform.get_platform(); - config.Information.PlatformVersion = Platform.get_version(); - config.Information.PlatformName = Platform.get_name(); - config.Information.ChocolateyVersion = VersionInformation.get_current_assembly_version(); - config.Information.ChocolateyProductVersion = VersionInformation.get_current_informational_version(); + config.Information.PlatformType = Platform.GetPlatform(); + config.Information.PlatformVersion = Platform.GetVersion(); + config.Information.PlatformName = Platform.GetName(); + config.Information.ChocolateyVersion = VersionInformation.GetCurrentAssemblyVersion(); + config.Information.ChocolateyProductVersion = VersionInformation.GetCurrentInformationalVersion(); config.Information.FullName = Assembly.GetExecutingAssembly().FullName; config.Information.Is64BitOperatingSystem = Environment.Is64BitOperatingSystem; config.Information.Is64BitProcess = Environment.Is64BitProcess; @@ -471,11 +525,11 @@ private static void set_environment_options(ChocolateyConfiguration config) config.Information.UserName = System.Environment.UserName; config.Information.UserDomainName = System.Environment.UserDomainName; config.Information.CurrentDirectory = Environment.CurrentDirectory; - config.Information.IsUserAdministrator = ProcessInformation.user_is_administrator(); - config.Information.IsUserSystemAccount = ProcessInformation.user_is_system(); - config.Information.IsUserRemoteDesktop = ProcessInformation.user_is_terminal_services(); - config.Information.IsUserRemote = ProcessInformation.user_is_remote(); - config.Information.IsProcessElevated = ProcessInformation.process_is_elevated(); + config.Information.IsUserAdministrator = ProcessInformation.UserIsAdministrator(); + config.Information.IsUserSystemAccount = ProcessInformation.UserIsSystem(); + config.Information.IsUserRemoteDesktop = ProcessInformation.UserIsTerminalServices(); + config.Information.IsUserRemote = ProcessInformation.UserIsRemote(); + config.Information.IsProcessElevated = ProcessInformation.IsElevated(); if (!string.IsNullOrWhiteSpace(Environment.GetEnvironmentVariable("https_proxy")) && string.IsNullOrWhiteSpace(config.Proxy.Location)) { @@ -493,10 +547,10 @@ private static void set_environment_options(ChocolateyConfiguration config) } } - private static void set_licensed_options(ChocolateyConfiguration config, ChocolateyLicense license, ConfigFileSettings configFileSettings) + private static void SetLicensedOptions(ChocolateyConfiguration config, ChocolateyLicense license, ConfigFileSettings configFileSettings) { - config.Information.IsLicensedVersion = license.is_licensed_version(); - config.Information.LicenseType = license.LicenseType.get_description_or_value(); + config.Information.IsLicensedVersion = license.IsLicensedVersion(); + config.Information.LicenseType = license.LicenseType.DescriptionOrValue(); if (license.AssemblyLoaded) { @@ -514,7 +568,7 @@ private static void set_licensed_options(ChocolateyConfiguration config, Chocola object componentClass = Activator.CreateInstance(licensedConfigBuilder); licensedConfigBuilder.InvokeMember( - SET_CONFIGURATION_METHOD, + SetConfigurationMethod, BindingFlags.InvokeMethod, null, componentClass, @@ -523,18 +577,18 @@ private static void set_licensed_options(ChocolateyConfiguration config, Chocola } catch (Exception ex) { - var isDebug = ApplicationParameters.is_debug_mode_cli_primitive(); + var isDebug = ApplicationParameters.IsDebugModeCliPrimitive(); if (config.Debug) isDebug = true; var message = isDebug ? ex.ToString() : ex.Message; if (isDebug && ex.InnerException != null) { - message += "{0}{1}".format_with(Environment.NewLine, ex.InnerException.ToString()); + message += "{0}{1}".FormatWith(Environment.NewLine, ex.InnerException.ToString()); } "chocolatey".Log().Error( ChocolateyLoggers.Important, - @"Error when setting configuration for '{0}':{1} {2}".format_with( + @"Error when setting configuration for '{0}':{1} {2}".FormatWith( licensedConfigBuilder.FullName, Environment.NewLine, message @@ -543,26 +597,26 @@ private static void set_licensed_options(ChocolateyConfiguration config, Chocola } } - private static void set_hash_provider(ChocolateyConfiguration config, Container container) + private static void SetHashProvider(ChocolateyConfiguration config, Container container) { if (!config.Features.UseFipsCompliantChecksums) { var hashprovider = container.GetInstance(); try { - hashprovider.set_hash_algorithm(CryptoHashProviderType.Md5); + hashprovider.SetHashAlgorithm(CryptoHashProviderType.Md5); } catch (Exception ex) { - if (!config.CommandName.is_equal_to("feature")) + if (!config.CommandName.IsEqualTo("feature")) { - if (ex.InnerException != null && ex.InnerException.Message.contains("FIPS")) + if (ex.InnerException != null && ex.InnerException.Message.ContainsSafe("FIPS")) { "chocolatey".Log().Warn(ChocolateyLoggers.Important, @" FIPS Mode detected - run 'choco feature enable -n {0}' - to use Chocolatey.".format_with(ApplicationParameters.Features.UseFipsCompliantChecksums)); + to use Chocolatey.".FormatWith(ApplicationParameters.Features.UseFipsCompliantChecksums)); - var errorMessage = "When FIPS Mode is enabled, Chocolatey requires {0} feature also be enabled.".format_with(ApplicationParameters.Features.UseFipsCompliantChecksums); + var errorMessage = "When FIPS Mode is enabled, Chocolatey requires {0} feature also be enabled.".FormatWith(ApplicationParameters.Features.UseFipsCompliantChecksums); if (string.IsNullOrWhiteSpace(config.CommandName)) { "chocolatey".Log().Error(errorMessage); @@ -577,5 +631,20 @@ FIPS Mode detected - run 'choco feature enable -n {0}' } } } + +#pragma warning disable IDE1006 + [Obsolete("This overload is deprecated and will be removed in v3.")] + [EditorBrowsable(EditorBrowsableState.Never)] + public static void initialize_with(Lazy environment) + => InitializeWith(environment); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public static bool is_compatibility_checks_disabled(IFileSystem filesystem, IXmlService xmlService) + => AreCompatibilityChecksDisabled(filesystem, xmlService); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public static void set_up_configuration(IList args, ChocolateyConfiguration config, Container container, ChocolateyLicense license, Action notifyWarnLoggingAction) + => SetupConfiguration(args, config, container, license, notifyWarnLoggingAction); +#pragma warning restore IDE1006 } } diff --git a/src/chocolatey/infrastructure.app/commands/ChocolateyApiKeyCommand.cs b/src/chocolatey/infrastructure.app/commands/ChocolateyApiKeyCommand.cs index 272b526bae..5840d1db41 100644 --- a/src/chocolatey/infrastructure.app/commands/ChocolateyApiKeyCommand.cs +++ b/src/chocolatey/infrastructure.app/commands/ChocolateyApiKeyCommand.cs @@ -39,21 +39,21 @@ public ChocolateyApiKeyCommand(IChocolateyConfigSettingsService configSettingsSe _configSettingsService = configSettingsService; } - public virtual void configure_argument_parser(OptionSet optionSet, ChocolateyConfiguration configuration) + public virtual void ConfigureArgumentParser(OptionSet optionSet, ChocolateyConfiguration configuration) { configuration.Sources = null; optionSet .Add("s=|source=", "Source [REQUIRED] - The source location for the key", - option => configuration.Sources = option.remove_surrounding_quotes()) + option => configuration.Sources = option.UnquoteSafe()) .Add("k=|key=|apikey=|api-key=", "ApiKey - The API key for the source. This is the authentication that identifies you and allows you to push to a source. With some sources this is either a key or it could be a user name and password specified as 'user:password'.", - option => configuration.ApiKeyCommand.Key = option.remove_surrounding_quotes()) + option => configuration.ApiKeyCommand.Key = option.UnquoteSafe()) ; } - public virtual void handle_additional_argument_parsing(IList unparsedArguments, ChocolateyConfiguration configuration) + public virtual void ParseAdditionalArguments(IList unparsedArguments, ChocolateyConfiguration configuration) { configuration.Input = string.Join(" ", unparsedArguments); @@ -71,7 +71,7 @@ public virtual void handle_additional_argument_parsing(IList unparsedArg if (!string.IsNullOrWhiteSpace(unparsedCommand)) { - this.Log().Warn("Unknown command {0}. Setting to list.".format_with(unparsedCommand)); + this.Log().Warn("Unknown command {0}. Setting to list.".FormatWith(unparsedCommand)); } else if (!string.IsNullOrWhiteSpace(configuration.ApiKeyCommand.Key)) { @@ -83,7 +83,7 @@ public virtual void handle_additional_argument_parsing(IList unparsedArg configuration.ApiKeyCommand.Command = command; } - public virtual void handle_validation(ChocolateyConfiguration configuration) + public virtual void Validate(ChocolateyConfiguration configuration) { switch (configuration.ApiKeyCommand.Command) { @@ -104,7 +104,7 @@ public virtual void handle_validation(ChocolateyConfiguration configuration) } } - public virtual void help_message(ChocolateyConfiguration configuration) + public virtual void HelpMessage(ChocolateyConfiguration configuration) { this.Log().Info(ChocolateyLoggers.Important, "ApiKey Command"); this.Log().Info(@" @@ -158,7 +158,7 @@ log in (or register, confirm and then log in) to choco apikey add -k -s {0} -".format_with(ApplicationParameters.ChocolateyCommunityFeedPushSource)); +".FormatWith(ApplicationParameters.ChocolateyCommunityFeedPushSource)); "chocolatey".Log().Info(ChocolateyLoggers.Important, "Exit Codes"); "chocolatey".Log().Info(@" @@ -176,45 +176,75 @@ file a ticket so we can document it at "chocolatey".Log().Info(ChocolateyLoggers.Important, "Options and Switches"); } - public virtual void noop(ChocolateyConfiguration configuration) + public virtual void DryRun(ChocolateyConfiguration configuration) { - _configSettingsService.noop(configuration); + _configSettingsService.DryRun(configuration); } - public virtual void run(ChocolateyConfiguration configuration) + public virtual void Run(ChocolateyConfiguration configuration) { switch (configuration.ApiKeyCommand.Command) { case ApiKeyCommandType.Remove: - _configSettingsService.remove_api_key(configuration); + _configSettingsService.RemoveApiKey(configuration); break; case ApiKeyCommandType.Add: - _configSettingsService.set_api_key(configuration); + _configSettingsService.SetApiKey(configuration); break; default: - _configSettingsService.get_api_key(configuration, (key) => + _configSettingsService.GetApiKey(configuration, (key) => { string authenticatedString = string.IsNullOrWhiteSpace(key.Key) ? string.Empty : "(Authenticated)"; if (configuration.RegularOutput) { - this.Log().Info(() => "{0} - {1}".format_with(key.Source, authenticatedString)); + this.Log().Info(() => "{0} - {1}".FormatWith(key.Source, authenticatedString)); } else { - this.Log().Info(() => "{0}|{1}".format_with(key.Source, authenticatedString)); + this.Log().Info(() => "{0}|{1}".FormatWith(key.Source, authenticatedString)); } }); break; } } - public virtual bool may_require_admin_access() + public virtual bool MayRequireAdminAccess() { - var config = Config.get_configuration_settings(); + var config = Config.GetConfigurationSettings(); if (config == null) return true; return !string.IsNullOrWhiteSpace(config.ApiKeyCommand.Key); } + +#pragma warning disable IDE1006 + [Obsolete("This overload is deprecated and will be removed in v3.")] + public virtual void configure_argument_parser(OptionSet optionSet, ChocolateyConfiguration configuration) + => ConfigureArgumentParser(optionSet, configuration); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public virtual void handle_additional_argument_parsing(IList unparsedArguments, ChocolateyConfiguration configuration) + => ParseAdditionalArguments(unparsedArguments, configuration); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public virtual void handle_validation(ChocolateyConfiguration configuration) + => Validate(configuration); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public virtual void help_message(ChocolateyConfiguration configuration) + => HelpMessage(configuration); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public virtual void noop(ChocolateyConfiguration configuration) + => DryRun(configuration); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public virtual void run(ChocolateyConfiguration configuration) + => Run(configuration); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public virtual bool may_require_admin_access() + => MayRequireAdminAccess(); +#pragma warning restore IDE1006 } } diff --git a/src/chocolatey/infrastructure.app/commands/ChocolateyCommandBase.cs b/src/chocolatey/infrastructure.app/commands/ChocolateyCommandBase.cs index 6a253e51ac..1f757dbef4 100644 --- a/src/chocolatey/infrastructure.app/commands/ChocolateyCommandBase.cs +++ b/src/chocolatey/infrastructure.app/commands/ChocolateyCommandBase.cs @@ -28,9 +28,9 @@ public abstract class ChocolateyCommandBase /// /// The list of unrecognised and unparsed options. /// The list of options which are known to be removed and should be warned for. - protected virtual void warn_for_removed_options(IEnumerable unparsedOptions, IEnumerable removedOptions) + protected virtual void WarnForRemovedOptions(IEnumerable unparsedOptions, IEnumerable removedOptions) { - if (!unparsedOptions.or_empty_list_if_null().Any() || !removedOptions.or_empty_list_if_null().Any()) + if (!unparsedOptions.OrEmpty().Any() || !removedOptions.OrEmpty().Any()) { return; } diff --git a/src/chocolatey/infrastructure.app/commands/ChocolateyConfigCommand.cs b/src/chocolatey/infrastructure.app/commands/ChocolateyConfigCommand.cs index 245341a622..e878133fb8 100644 --- a/src/chocolatey/infrastructure.app/commands/ChocolateyConfigCommand.cs +++ b/src/chocolatey/infrastructure.app/commands/ChocolateyConfigCommand.cs @@ -38,7 +38,7 @@ public ChocolateyConfigCommand(IChocolateyConfigSettingsService configSettingsSe _configSettingsService = configSettingsService; } - public virtual void configure_argument_parser(OptionSet optionSet, ChocolateyConfiguration configuration) + public virtual void ConfigureArgumentParser(OptionSet optionSet, ChocolateyConfiguration configuration) { configuration.Sources = string.Empty; @@ -46,29 +46,29 @@ public virtual void configure_argument_parser(OptionSet optionSet, ChocolateyCon .Add( "name=", "Name - the name of the config setting. Required with some actions. Defaults to empty.", - option => configuration.ConfigCommand.Name = option.remove_surrounding_quotes()) + option => configuration.ConfigCommand.Name = option.UnquoteSafe()) .Add( "value=", "Value - the value of the config setting. Required with some actions. Defaults to empty.", - option => configuration.ConfigCommand.ConfigValue = option.remove_surrounding_quotes()) + option => configuration.ConfigCommand.ConfigValue = option.UnquoteSafe()) ; } - public virtual void handle_additional_argument_parsing(IList unparsedArguments, ChocolateyConfiguration configuration) + public virtual void ParseAdditionalArguments(IList unparsedArguments, ChocolateyConfiguration configuration) { configuration.Input = string.Join(" ", unparsedArguments); - var command = ConfigCommandType.unknown; - string unparsedCommand = unparsedArguments.DefaultIfEmpty(string.Empty).FirstOrDefault().to_string().Replace("-", string.Empty); + var command = ConfigCommandType.Unknown; + string unparsedCommand = unparsedArguments.DefaultIfEmpty(string.Empty).FirstOrDefault().ToStringSafe().Replace("-", string.Empty); Enum.TryParse(unparsedCommand, true, out command); - if (command == ConfigCommandType.unknown) + if (command == ConfigCommandType.Unknown) { - if (!string.IsNullOrWhiteSpace(unparsedCommand)) this.Log().Warn("Unknown command {0}. Setting to list.".format_with(unparsedCommand)); - command = ConfigCommandType.list; + if (!string.IsNullOrWhiteSpace(unparsedCommand)) this.Log().Warn("Unknown command {0}. Setting to list.".FormatWith(unparsedCommand)); + command = ConfigCommandType.List; } configuration.ConfigCommand.Command = command; - if ((configuration.ConfigCommand.Command == ConfigCommandType.list + if ((configuration.ConfigCommand.Command == ConfigCommandType.List || !string.IsNullOrWhiteSpace(configuration.ConfigCommand.Name) ) && unparsedArguments.Count > 1) throw new ApplicationException("A single features command must be listed. Please see the help menu for those commands"); @@ -83,26 +83,22 @@ public virtual void handle_additional_argument_parsing(IList unparsedArg } } - public virtual void handle_validation(ChocolateyConfiguration configuration) + public virtual void Validate(ChocolateyConfiguration configuration) { - if (configuration.ConfigCommand.Command != ConfigCommandType.list && string.IsNullOrWhiteSpace(configuration.ConfigCommand.Name)) throw new ApplicationException("When specifying the subcommand '{0}', you must also specify --name by option or position.".format_with(configuration.ConfigCommand.Command.to_string())); - if (configuration.ConfigCommand.Command == ConfigCommandType.set && string.IsNullOrWhiteSpace(configuration.ConfigCommand.ConfigValue)) throw new ApplicationException("When specifying the subcommand '{0}', you must also specify --value by option or position.".format_with(configuration.ConfigCommand.Command.to_string())); + if (configuration.ConfigCommand.Command != ConfigCommandType.List && string.IsNullOrWhiteSpace(configuration.ConfigCommand.Name)) throw new ApplicationException("When specifying the subcommand '{0}', you must also specify --name by option or position.".FormatWith(configuration.ConfigCommand.Command.ToStringSafe().ToLower())); + if (configuration.ConfigCommand.Command == ConfigCommandType.Set && string.IsNullOrWhiteSpace(configuration.ConfigCommand.ConfigValue)) throw new ApplicationException("When specifying the subcommand '{0}', you must also specify --value by option or position.".FormatWith(configuration.ConfigCommand.Command.ToStringSafe().ToLower())); } - public virtual void help_message(ChocolateyConfiguration configuration) + public virtual void HelpMessage(ChocolateyConfiguration configuration) { this.Log().Info(ChocolateyLoggers.Important, "Config Command"); this.Log().Info(@" Chocolatey will allow you to interact with the configuration file settings. - -NOTE: Available in 0.9.9.9+. "); "chocolatey".Log().Info(ChocolateyLoggers.Important, "Usage"); "chocolatey".Log().Info(@" choco config [list]|get|set|unset [] - -NOTE: `Unset` subcommand available in 0.9.10+. "); "chocolatey".Log().Info(ChocolateyLoggers.Important, "Examples"); @@ -144,36 +140,66 @@ file a ticket so we can document it at "chocolatey".Log().Info(ChocolateyLoggers.Important, "Options and Switches"); } - public virtual void noop(ChocolateyConfiguration configuration) + public virtual void DryRun(ChocolateyConfiguration configuration) { - _configSettingsService.noop(configuration); + _configSettingsService.DryRun(configuration); } - public virtual void run(ChocolateyConfiguration configuration) + public virtual void Run(ChocolateyConfiguration configuration) { switch (configuration.ConfigCommand.Command) { - case ConfigCommandType.list: - _configSettingsService.config_list(configuration); + case ConfigCommandType.List: + _configSettingsService.ListConfig(configuration); break; - case ConfigCommandType.get: - _configSettingsService.config_get(configuration); + case ConfigCommandType.Get: + _configSettingsService.GetConfig(configuration); break; - case ConfigCommandType.set: - _configSettingsService.config_set(configuration); + case ConfigCommandType.Set: + _configSettingsService.SetConfig(configuration); break; - case ConfigCommandType.unset: - _configSettingsService.config_unset(configuration); + case ConfigCommandType.Unset: + _configSettingsService.UnsetConfig(configuration); break; } } - public virtual bool may_require_admin_access() + public virtual bool MayRequireAdminAccess() { - var config = Config.get_configuration_settings(); + var config = Config.GetConfigurationSettings(); if (config == null) return true; - return config.ConfigCommand.Command != ConfigCommandType.list; + return config.ConfigCommand.Command != ConfigCommandType.List; } + +#pragma warning disable IDE1006 + [Obsolete("This overload is deprecated and will be removed in v3.")] + public virtual void configure_argument_parser(OptionSet optionSet, ChocolateyConfiguration configuration) + => ConfigureArgumentParser(optionSet, configuration); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public virtual void handle_additional_argument_parsing(IList unparsedArguments, ChocolateyConfiguration configuration) + => ParseAdditionalArguments(unparsedArguments, configuration); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public virtual void handle_validation(ChocolateyConfiguration configuration) + => Validate(configuration); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public virtual void help_message(ChocolateyConfiguration configuration) + => HelpMessage(configuration); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public virtual void noop(ChocolateyConfiguration configuration) + => DryRun(configuration); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public virtual void run(ChocolateyConfiguration configuration) + => Run(configuration); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public virtual bool may_require_admin_access() + => MayRequireAdminAccess(); +#pragma warning restore IDE1006 } } diff --git a/src/chocolatey/infrastructure.app/commands/ChocolateyExportCommand.cs b/src/chocolatey/infrastructure.app/commands/ChocolateyExportCommand.cs index dd2d57ec45..ce8fd569a5 100644 --- a/src/chocolatey/infrastructure.app/commands/ChocolateyExportCommand.cs +++ b/src/chocolatey/infrastructure.app/commands/ChocolateyExportCommand.cs @@ -43,19 +43,19 @@ public ChocolateyExportCommand(INugetService nugetService, IFileSystem fileSyste _fileSystem = fileSystem; } - public void configure_argument_parser(OptionSet optionSet, ChocolateyConfiguration configuration) + public void ConfigureArgumentParser(OptionSet optionSet, ChocolateyConfiguration configuration) { optionSet .Add("o=|output-file-path=", "Output File Path - the path to where the list of currently installed packages should be saved. Defaults to packages.config.", - option => configuration.ExportCommand.OutputFilePath = option.remove_surrounding_quotes()) + option => configuration.ExportCommand.OutputFilePath = option.UnquoteSafe()) .Add("include-version-numbers|include-version", "Include Version Numbers - controls whether or not version numbers for each package appear in generated file. Defaults to false.", option => configuration.ExportCommand.IncludeVersionNumbers = option != null) ; } - public void handle_additional_argument_parsing(IList unparsedArguments, ChocolateyConfiguration configuration) + public void ParseAdditionalArguments(IList unparsedArguments, ChocolateyConfiguration configuration) { configuration.Input = string.Join(" ", unparsedArguments); @@ -71,12 +71,12 @@ public void handle_additional_argument_parsing(IList unparsedArguments, } } - public void handle_validation(ChocolateyConfiguration configuration) + public void Validate(ChocolateyConfiguration configuration) { // Currently, no additional validation is required. } - public void help_message(ChocolateyConfiguration configuration) + public void HelpMessage(ChocolateyConfiguration configuration) { this.Log().Info(ChocolateyLoggers.Important, "Export Command"); this.Log().Info(@" @@ -85,8 +85,6 @@ Export all currently installed packages to a file. This is especially helpful when re-building a machine that was created using Chocolatey. Export all packages to a file, and then re-install those packages onto new machine using `choco install packages.config`. - -NOTE: Available with 0.11.0+. "); "chocolatey".Log().Info(ChocolateyLoggers.Important, "Usage"); "chocolatey".Log().Info(@" @@ -126,22 +124,22 @@ file a ticket so we can document it at "chocolatey".Log().Info(ChocolateyLoggers.Important, "Options and Switches"); } - public bool may_require_admin_access() + public bool MayRequireAdminAccess() { return false; } - public void noop(ChocolateyConfiguration configuration) + public void DryRun(ChocolateyConfiguration configuration) { - this.Log().Info("Export would have been with options: {0} Output File Path={1}{0} Include Version Numbers:{2}".format_with(Environment.NewLine, configuration.ExportCommand.OutputFilePath, configuration.ExportCommand.IncludeVersionNumbers)); + this.Log().Info("Export would have been with options: {0} Output File Path={1}{0} Include Version Numbers:{2}".FormatWith(Environment.NewLine, configuration.ExportCommand.OutputFilePath, configuration.ExportCommand.IncludeVersionNumbers)); } - public void run(ChocolateyConfiguration configuration) + public void Run(ChocolateyConfiguration configuration) { - var packageResults = _nugetService.get_all_installed_packages(configuration); + var packageResults = _nugetService.GetInstalledPackages(configuration); var settings = new XmlWriterSettings { Indent = true, Encoding = new UTF8Encoding(false) }; - FaultTolerance.try_catch_with_logging_exception( + FaultTolerance.TryCatchWithLoggingException( () => { using (var stringWriter = new StringWriter()) @@ -168,13 +166,13 @@ public void run(ChocolateyConfiguration configuration) xw.Flush(); } - var fullOutputFilePath = _fileSystem.get_full_path(configuration.ExportCommand.OutputFilePath); - var fileExists = _fileSystem.file_exists(fullOutputFilePath); + var fullOutputFilePath = _fileSystem.GetFullPath(configuration.ExportCommand.OutputFilePath); + var fileExists = _fileSystem.FileExists(fullOutputFilePath); // If the file doesn't already exist, just write the new one out directly if (!fileExists) { - _fileSystem.write_file( + _fileSystem.WriteFile( fullOutputFilePath, stringWriter.GetStringBuilder().ToString(), new UTF8Encoding(false)); @@ -185,16 +183,46 @@ public void run(ChocolateyConfiguration configuration) // Otherwise, create an update file, and resiliently move it into place. var tempUpdateFile = fullOutputFilePath + "." + Process.GetCurrentProcess().Id + ".update"; - _fileSystem.write_file(tempUpdateFile, + _fileSystem.WriteFile(tempUpdateFile, stringWriter.GetStringBuilder().ToString(), new UTF8Encoding(false)); - _fileSystem.replace_file(tempUpdateFile, fullOutputFilePath, fullOutputFilePath + ".backup"); + _fileSystem.ReplaceFile(tempUpdateFile, fullOutputFilePath, fullOutputFilePath + ".backup"); } }, errorMessage: "Error exporting currently installed packages", throwError: true ); } + +#pragma warning disable IDE1006 + [Obsolete("This overload is deprecated and will be removed in v3.")] + public virtual void configure_argument_parser(OptionSet optionSet, ChocolateyConfiguration configuration) + => ConfigureArgumentParser(optionSet, configuration); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public virtual void handle_additional_argument_parsing(IList unparsedArguments, ChocolateyConfiguration configuration) + => ParseAdditionalArguments(unparsedArguments, configuration); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public virtual void handle_validation(ChocolateyConfiguration configuration) + => Validate(configuration); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public virtual void help_message(ChocolateyConfiguration configuration) + => HelpMessage(configuration); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public virtual void noop(ChocolateyConfiguration configuration) + => DryRun(configuration); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public virtual void run(ChocolateyConfiguration configuration) + => Run(configuration); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public virtual bool may_require_admin_access() + => MayRequireAdminAccess(); +#pragma warning restore IDE1006 } } diff --git a/src/chocolatey/infrastructure.app/commands/ChocolateyFeatureCommand.cs b/src/chocolatey/infrastructure.app/commands/ChocolateyFeatureCommand.cs index d568b5cffb..968e161661 100644 --- a/src/chocolatey/infrastructure.app/commands/ChocolateyFeatureCommand.cs +++ b/src/chocolatey/infrastructure.app/commands/ChocolateyFeatureCommand.cs @@ -39,47 +39,55 @@ public ChocolateyFeatureCommand(IChocolateyConfigSettingsService configSettingsS _configSettingsService = configSettingsService; } - public virtual void configure_argument_parser(OptionSet optionSet, ChocolateyConfiguration configuration) + public virtual void ConfigureArgumentParser(OptionSet optionSet, ChocolateyConfiguration configuration) { configuration.Sources = string.Empty; optionSet .Add("n=|name=", "Name - the name of the source. Required with actions other than list. Defaults to empty.", - option => configuration.FeatureCommand.Name = option.remove_surrounding_quotes()) + option => configuration.FeatureCommand.Name = option.UnquoteSafe()) ; } - public virtual void handle_additional_argument_parsing(IList unparsedArguments, ChocolateyConfiguration configuration) + public virtual void ParseAdditionalArguments(IList unparsedArguments, ChocolateyConfiguration configuration) { configuration.Input = string.Join(" ", unparsedArguments); - if (unparsedArguments.Count > 1) - { - throw new ApplicationException("A single features command must be listed. Please see the help menu for those commands"); - } - - var command = FeatureCommandType.unknown; + var command = FeatureCommandType.Unknown; string unparsedCommand = unparsedArguments.DefaultIfEmpty(string.Empty).FirstOrDefault(); Enum.TryParse(unparsedCommand, true, out command); - if (command == FeatureCommandType.unknown) + if (command == FeatureCommandType.Unknown) { - if (!string.IsNullOrWhiteSpace(unparsedCommand)) this.Log().Warn("Unknown command {0}. Setting to list.".format_with(unparsedCommand)); - command = FeatureCommandType.list; + if (!string.IsNullOrWhiteSpace(unparsedCommand)) this.Log().Warn("Unknown command {0}. Setting to list.".FormatWith(unparsedCommand)); + command = FeatureCommandType.List; } configuration.FeatureCommand.Command = command; + + if ((configuration.FeatureCommand.Command == FeatureCommandType.List + || !string.IsNullOrWhiteSpace(configuration.FeatureCommand.Name) + ) + && unparsedArguments.Count > 1) + { + throw new ApplicationException("A single features command must be listed. Please see the help menu for those commands"); + } + + if (string.IsNullOrWhiteSpace(configuration.FeatureCommand.Name) && unparsedArguments.Count >= 2) + { + configuration.FeatureCommand.Name = unparsedArguments[1]; + } } - public virtual void handle_validation(ChocolateyConfiguration configuration) + public virtual void Validate(ChocolateyConfiguration configuration) { - if (configuration.FeatureCommand.Command != FeatureCommandType.list && string.IsNullOrWhiteSpace(configuration.FeatureCommand.Name)) + if (configuration.FeatureCommand.Command != FeatureCommandType.List && string.IsNullOrWhiteSpace(configuration.FeatureCommand.Name)) { - throw new ApplicationException("When specifying the subcommand '{0}', you must also specify --name.".format_with(configuration.FeatureCommand.Command.to_string())); + throw new ApplicationException("When specifying the subcommand '{0}', you must also specify --name.".FormatWith(configuration.FeatureCommand.Command.ToStringSafe().ToLower())); } } - public virtual void help_message(ChocolateyConfiguration configuration) + public virtual void HelpMessage(ChocolateyConfiguration configuration) { this.Log().Info(ChocolateyLoggers.Important, "Feature Command"); this.Log().Info(@" @@ -95,8 +103,10 @@ choco feature [list]|disable|enable [] "chocolatey".Log().Info(@" choco feature choco feature list - choco feature disable -n=bob - choco feature enable -n=bob + choco feature get checksumFiles + choco feature get --name=checksumFiles + choco feature disable --name=checksumFiles + choco feature enable --name=checksumFiles NOTE: See scripting in the command reference (`choco -?`) for how to write proper scripts and integrations. @@ -120,33 +130,66 @@ file a ticket so we can document it at "chocolatey".Log().Info(ChocolateyLoggers.Important, "Options and Switches"); } - public virtual void noop(ChocolateyConfiguration configuration) + public virtual void DryRun(ChocolateyConfiguration configuration) { - _configSettingsService.noop(configuration); + _configSettingsService.DryRun(configuration); } - public virtual void run(ChocolateyConfiguration configuration) + public virtual void Run(ChocolateyConfiguration configuration) { switch (configuration.FeatureCommand.Command) { - case FeatureCommandType.list: - _configSettingsService.feature_list(configuration); + case FeatureCommandType.List: + _configSettingsService.ListFeatures(configuration); break; - case FeatureCommandType.disable: - _configSettingsService.feature_disable(configuration); + case FeatureCommandType.Get: + _configSettingsService.GetFeature(configuration); break; - case FeatureCommandType.enable: - _configSettingsService.feature_enable(configuration); + case FeatureCommandType.Disable: + _configSettingsService.DisableFeature(configuration); + break; + case FeatureCommandType.Enable: + _configSettingsService.EnableFeature(configuration); break; } } - public virtual bool may_require_admin_access() + public virtual bool MayRequireAdminAccess() { - var config = Config.get_configuration_settings(); + var config = Config.GetConfigurationSettings(); if (config == null) return true; - return config.FeatureCommand.Command != FeatureCommandType.list; + return config.FeatureCommand.Command != FeatureCommandType.List; } + +#pragma warning disable IDE1006 + [Obsolete("This overload is deprecated and will be removed in v3.")] + public virtual void configure_argument_parser(OptionSet optionSet, ChocolateyConfiguration configuration) + => ConfigureArgumentParser(optionSet, configuration); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public virtual void handle_additional_argument_parsing(IList unparsedArguments, ChocolateyConfiguration configuration) + => ParseAdditionalArguments(unparsedArguments, configuration); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public virtual void handle_validation(ChocolateyConfiguration configuration) + => Validate(configuration); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public virtual void help_message(ChocolateyConfiguration configuration) + => HelpMessage(configuration); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public virtual void noop(ChocolateyConfiguration configuration) + => DryRun(configuration); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public virtual void run(ChocolateyConfiguration configuration) + => Run(configuration); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public virtual bool may_require_admin_access() + => MayRequireAdminAccess(); +#pragma warning restore IDE1006 } } diff --git a/src/chocolatey/infrastructure.app/commands/ChocolateyHelpCommand.cs b/src/chocolatey/infrastructure.app/commands/ChocolateyHelpCommand.cs index 18acf87e88..411688db78 100644 --- a/src/chocolatey/infrastructure.app/commands/ChocolateyHelpCommand.cs +++ b/src/chocolatey/infrastructure.app/commands/ChocolateyHelpCommand.cs @@ -37,40 +37,40 @@ public ChocolateyHelpCommand(Container container) _container = container; } - public virtual void configure_argument_parser(OptionSet optionSet, ChocolateyConfiguration configuration) + public virtual void ConfigureArgumentParser(OptionSet optionSet, ChocolateyConfiguration configuration) { } - public virtual void handle_additional_argument_parsing(IList unparsedArguments, ChocolateyConfiguration configuration) + public virtual void ParseAdditionalArguments(IList unparsedArguments, ChocolateyConfiguration configuration) { configuration.Input = string.Join(" ", unparsedArguments); } - public virtual void handle_validation(ChocolateyConfiguration configuration) + public virtual void Validate(ChocolateyConfiguration configuration) { } - public virtual void help_message(ChocolateyConfiguration configuration) + public virtual void HelpMessage(ChocolateyConfiguration configuration) { - display_help_message(_container); + DisplayHelpMessage(_container); } - public virtual void noop(ChocolateyConfiguration configuration) + public virtual void DryRun(ChocolateyConfiguration configuration) { - display_help_message(_container); + DisplayHelpMessage(_container); } - public virtual void run(ChocolateyConfiguration configuration) + public virtual void Run(ChocolateyConfiguration configuration) { - display_help_message(_container); + DisplayHelpMessage(_container); } - public virtual bool may_require_admin_access() + public virtual bool MayRequireAdminAccess() { return false; } - public static void display_help_message(Container container = null) + public static void DisplayHelpMessage(Container container = null) { var commandsLog = new StringBuilder(); if (null == container) @@ -84,7 +84,7 @@ public static void display_help_message(Container container = null) IEnumerable commands = container.GetAllInstances(); - foreach (var command in commands.or_empty_list_if_null().SelectMany(c => + foreach (var command in commands.OrEmpty().SelectMany(c => { return c.GetType().GetCustomAttributes(typeof(CommandForAttribute), false).Cast(); }).OrderBy(c => c.CommandName)) @@ -99,7 +99,7 @@ public static void display_help_message(Container container = null) "chocolatey".Log().Info(@" -v, --version - Version - Prints out the Chocolatey version. Available in 0.9.9+. + Version - Prints out the Chocolatey version. "); "chocolatey".Log().Info(ChocolateyLoggers.Important, "Commands"); @@ -108,7 +108,7 @@ public static void display_help_message(Container container = null) Please run chocolatey with `choco command -help` for specific help on each command. -".format_with(commandsLog.ToString())); +".FormatWith(commandsLog.ToString())); "chocolatey".Log().Info(ChocolateyLoggers.Important, @"How To Pass Options / Switches"); "chocolatey".Log().Info(@" You can pass options and switches in the following ways: @@ -258,5 +258,35 @@ everywhere they are used and with newer versions of Chocolatey. "); "chocolatey".Log().Info(ChocolateyLoggers.Important, "Default Options and Switches"); } + +#pragma warning disable IDE1006 + [Obsolete("This overload is deprecated and will be removed in v3.")] + public virtual void configure_argument_parser(OptionSet optionSet, ChocolateyConfiguration configuration) + => ConfigureArgumentParser(optionSet, configuration); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public virtual void handle_additional_argument_parsing(IList unparsedArguments, ChocolateyConfiguration configuration) + => ParseAdditionalArguments(unparsedArguments, configuration); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public virtual void handle_validation(ChocolateyConfiguration configuration) + => Validate(configuration); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public virtual void help_message(ChocolateyConfiguration configuration) + => HelpMessage(configuration); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public virtual void noop(ChocolateyConfiguration configuration) + => DryRun(configuration); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public virtual void run(ChocolateyConfiguration configuration) + => Run(configuration); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public virtual bool may_require_admin_access() + => MayRequireAdminAccess(); +#pragma warning restore IDE1006 } } diff --git a/src/chocolatey/infrastructure.app/commands/ChocolateyInfoCommand.cs b/src/chocolatey/infrastructure.app/commands/ChocolateyInfoCommand.cs index 3b31de47ab..cc32c98d74 100644 --- a/src/chocolatey/infrastructure.app/commands/ChocolateyInfoCommand.cs +++ b/src/chocolatey/infrastructure.app/commands/ChocolateyInfoCommand.cs @@ -16,6 +16,7 @@ namespace chocolatey.infrastructure.app.commands { + using System; using System.Collections.Generic; using attributes; using commandline; @@ -31,20 +32,20 @@ public ChocolateyInfoCommand(IChocolateyPackageService packageService) { } - public override void configure_argument_parser(OptionSet optionSet, ChocolateyConfiguration configuration) + public override void ConfigureArgumentParser(OptionSet optionSet, ChocolateyConfiguration configuration) { optionSet .Add( "s=|source=", "Source - Source location for install. Can use special 'windowsfeatures', 'ruby', 'cygwin', or 'python' sources. Defaults to configured sources.", - option => configuration.Sources = option.remove_surrounding_quotes()) + option => configuration.Sources = option.UnquoteSafe()) .Add( "l|lo|localonly|local-only", "LocalOnly - Only search against local machine items.", option => configuration.ListCommand.LocalOnly = option != null) .Add("version=", "Version - Specific version of a package to return.", - option => configuration.Version = option.remove_surrounding_quotes()) + option => configuration.Version = option.UnquoteSafe()) .Add( "pre|prerelease", "Prerelease - Include Prereleases? Defaults to false.", @@ -52,20 +53,20 @@ public override void configure_argument_parser(OptionSet optionSet, ChocolateyCo .Add( "u=|user=", "User - used with authenticated feeds. Defaults to empty.", - option => configuration.SourceCommand.Username = option.remove_surrounding_quotes()) + option => configuration.SourceCommand.Username = option.UnquoteSafe()) .Add( "p=|password=", "Password - the user's password to the source. Defaults to empty.", - option => configuration.SourceCommand.Password = option.remove_surrounding_quotes()) + option => configuration.SourceCommand.Password = option.UnquoteSafe()) .Add("cert=", - "Client certificate - PFX pathname for an x509 authenticated feeds. Defaults to empty. Available in 0.9.10+.", - option => configuration.SourceCommand.Certificate = option.remove_surrounding_quotes()) + "Client certificate - PFX pathname for an x509 authenticated feeds. Defaults to empty.", + option => configuration.SourceCommand.Certificate = option.UnquoteSafe()) .Add("cp=|certpassword=", - "Certificate Password - the client certificate's password to the source. Defaults to empty. Available in 0.9.10+.", - option => configuration.SourceCommand.CertificatePassword = option.remove_surrounding_quotes()) + "Certificate Password - the client certificate's password to the source. Defaults to empty.", + option => configuration.SourceCommand.CertificatePassword = option.UnquoteSafe()) .Add("disable-repository-optimizations|disable-package-repository-optimizations", - "Disable Package Repository Optimizations - Do not use optimizations for reducing bandwidth with repository queries during package install/upgrade/outdated operations. Should not generally be used, unless a repository needs to support older methods of query. When used, this makes queries similar to the way they were done in Chocolatey v0.10.11 and before. Overrides the default feature '{0}' set to '{1}'. Available in 0.10.14+.".format_with - (ApplicationParameters.Features.UsePackageRepositoryOptimizations, configuration.Features.UsePackageRepositoryOptimizations.to_string()), + "Disable Package Repository Optimizations - Do not use optimizations for reducing bandwidth with repository queries during package install/upgrade/outdated operations. Should not generally be used, unless a repository needs to support older methods of query. When used, this makes queries similar to the way they were done in earlier versions of Chocolatey. Overrides the default feature '{0}' set to '{1}'.".FormatWith + (ApplicationParameters.Features.UsePackageRepositoryOptimizations, configuration.Features.UsePackageRepositoryOptimizations.ToStringSafe()), option => { if (option != null) @@ -76,14 +77,32 @@ public override void configure_argument_parser(OptionSet optionSet, ChocolateyCo ; } - public override void handle_additional_argument_parsing(IList unparsedArguments, ChocolateyConfiguration configuration) + public override void ParseAdditionalArguments(IList unparsedArguments, ChocolateyConfiguration configuration) { configuration.Input = string.Join(" ", unparsedArguments); configuration.Verbose = true; configuration.ListCommand.Exact = true; } - public override void help_message(ChocolateyConfiguration configuration) + public override void Validate(ChocolateyConfiguration configuration) + { + base.Validate(configuration); + + if (string.IsNullOrWhiteSpace(configuration.Input)) + { + throw new ApplicationException("A single package name is required to run the choco info command."); + } + + // Validate only a single package has been passed to info + // TODO: Provide ability to get info on a list of packages. See https://github.com/chocolatey/choco/issues/2905 + var input = configuration.Input.Split(' '); + if (input.Length > 1) + { + throw new ApplicationException("Only a single package name can be passed to the choco info command."); + } + } + + public override void HelpMessage(ChocolateyConfiguration configuration) { this.Log().Info(ChocolateyLoggers.Important, "Info Command"); this.Log().Info(@" @@ -91,8 +110,6 @@ public override void help_message(ChocolateyConfiguration configuration) detailed information about that package. This is a synonym for `choco search --exact --detailed`. -NOTE: New as of 0.9.10.0. - "); "chocolatey".Log().Info(ChocolateyLoggers.Important, "Usage"); @@ -123,15 +140,15 @@ Exit codes that normally result from running this command. - -1 or 1: an error has occurred - 2: no results (enhanced) -NOTE: Starting in v0.10.12, if you have the feature '{0}' - turned on, then choco will provide enhanced exit codes that allow +NOTE: If you have the feature '{0}' turned on, + then choco will provide enhanced exit codes that allow better integration and scripting. If you find other exit codes that we have not yet documented, please file a ticket so we can document it at https://github.com/chocolatey/choco/issues/new/choose. -".format_with(ApplicationParameters.Features.UseEnhancedExitCodes)); +".FormatWith(ApplicationParameters.Features.UseEnhancedExitCodes)); "chocolatey".Log().Info(ChocolateyLoggers.Important, "Options and Switches"); } } diff --git a/src/chocolatey/infrastructure.app/commands/ChocolateyInstallCommand.cs b/src/chocolatey/infrastructure.app/commands/ChocolateyInstallCommand.cs index 011e96c3a6..23f10109cb 100644 --- a/src/chocolatey/infrastructure.app/commands/ChocolateyInstallCommand.cs +++ b/src/chocolatey/infrastructure.app/commands/ChocolateyInstallCommand.cs @@ -48,15 +48,15 @@ public ChocolateyInstallCommand(IChocolateyPackageService packageService) _packageService = packageService; } - public virtual void configure_argument_parser(OptionSet optionSet, ChocolateyConfiguration configuration) + public virtual void ConfigureArgumentParser(OptionSet optionSet, ChocolateyConfiguration configuration) { optionSet .Add("s=|source=", "Source - The source to find the package(s) to install. Special sources include: ruby, cygwin, windowsfeatures, and python. To specify more than one source, pass it with a semi-colon separating the values (e.g. \"'source1;source2'\"). Defaults to default feeds.", - option => configuration.Sources = option.remove_surrounding_quotes()) + option => configuration.Sources = option.UnquoteSafe()) .Add("version=", "Version - A specific version to install. Defaults to unspecified.", - option => configuration.Version = option.remove_surrounding_quotes()) + option => configuration.Version = option.UnquoteSafe()) .Add("pre|prerelease", "Prerelease - Include Prereleases? Defaults to false.", option => configuration.Prerelease = option != null) @@ -65,7 +65,7 @@ public virtual void configure_argument_parser(OptionSet optionSet, ChocolateyCon option => configuration.ForceX86 = option != null) .Add("ia=|installargs=|install-args=|installarguments=|install-arguments=", "InstallArguments - Install Arguments to pass to the native installer in the package. Defaults to unspecified.", - option => configuration.InstallArguments = option.remove_surrounding_quotes()) + option => configuration.InstallArguments = option.UnquoteSafe()) .Add("o|override|overrideargs|overridearguments|override-arguments", "OverrideArguments - Should install arguments be used exclusively without appending to current package passed arguments? Defaults to false.", option => configuration.OverrideArguments = option != null) @@ -74,7 +74,7 @@ public virtual void configure_argument_parser(OptionSet optionSet, ChocolateyCon option => configuration.NotSilent = option != null) .Add("params=|parameters=|pkgparameters=|packageparameters=|package-parameters=", "PackageParameters - Parameters to pass to the package. Defaults to unspecified.", - option => configuration.PackageParameters = option.remove_surrounding_quotes()) + option => configuration.PackageParameters = option.UnquoteSafe()) .Add("argsglobal|args-global|installargsglobal|install-args-global|applyargstodependencies|apply-args-to-dependencies|apply-install-arguments-to-dependencies", "Apply Install Arguments To Dependencies - Should install arguments be applied to dependent packages? Defaults to false.", option => configuration.ApplyInstallArgumentsToDependencies = option != null) @@ -95,36 +95,36 @@ public virtual void configure_argument_parser(OptionSet optionSet, ChocolateyCon option => configuration.SkipPackageInstallProvider = option != null) .Add("u=|user=", "User - used with authenticated feeds. Defaults to empty.", - option => configuration.SourceCommand.Username = option.remove_surrounding_quotes()) + option => configuration.SourceCommand.Username = option.UnquoteSafe()) .Add("p=|password=", "Password - the user's password to the source. Defaults to empty.", - option => configuration.SourceCommand.Password = option.remove_surrounding_quotes()) + option => configuration.SourceCommand.Password = option.UnquoteSafe()) .Add("cert=", - "Client certificate - PFX pathname for an x509 authenticated feeds. Defaults to empty. Available in 0.9.10+.", - option => configuration.SourceCommand.Certificate = option.remove_surrounding_quotes()) + "Client certificate - PFX pathname for an x509 authenticated feeds. Defaults to empty.", + option => configuration.SourceCommand.Certificate = option.UnquoteSafe()) .Add("cp=|certpassword=", - "Certificate Password - the client certificate's password to the source. Defaults to empty. Available in 0.9.10+.", - option => configuration.SourceCommand.CertificatePassword = option.remove_surrounding_quotes()) + "Certificate Password - the client certificate's password to the source. Defaults to empty.", + option => configuration.SourceCommand.CertificatePassword = option.UnquoteSafe()) .Add("ignorechecksum|ignore-checksum|ignorechecksums|ignore-checksums", - "IgnoreChecksums - Ignore checksums provided by the package. Overrides the default feature '{0}' set to '{1}'. Available in 0.9.9.9+.".format_with(ApplicationParameters.Features.ChecksumFiles, configuration.Features.ChecksumFiles.to_string()), + "IgnoreChecksums - Ignore checksums provided by the package. Overrides the default feature '{0}' set to '{1}'.".FormatWith(ApplicationParameters.Features.ChecksumFiles, configuration.Features.ChecksumFiles.ToStringSafe()), option => { if (option != null) configuration.Features.ChecksumFiles = false; }) .Add("allowemptychecksum|allowemptychecksums|allow-empty-checksums", - "Allow Empty Checksums - Allow packages to have empty/missing checksums for downloaded resources from non-secure locations (HTTP, FTP). Use this switch is not recommended if using sources that download resources from the internet. Overrides the default feature '{0}' set to '{1}'. Available in 0.10.0+.".format_with(ApplicationParameters.Features.AllowEmptyChecksums, configuration.Features.AllowEmptyChecksums.to_string()), + "Allow Empty Checksums - Allow packages to have empty/missing checksums for downloaded resources from non-secure locations (HTTP, FTP). Use this switch is not recommended if using sources that download resources from the internet. Overrides the default feature '{0}' set to '{1}'.".FormatWith(ApplicationParameters.Features.AllowEmptyChecksums, configuration.Features.AllowEmptyChecksums.ToStringSafe()), option => { if (option != null) configuration.Features.AllowEmptyChecksums = true; }) .Add("allowemptychecksumsecure|allowemptychecksumssecure|allow-empty-checksums-secure", - "Allow Empty Checksums Secure - Allow packages to have empty checksums for downloaded resources from secure locations (HTTPS). Overrides the default feature '{0}' set to '{1}'. Available in 0.10.0+.".format_with(ApplicationParameters.Features.AllowEmptyChecksumsSecure, configuration.Features.AllowEmptyChecksumsSecure.to_string()), + "Allow Empty Checksums Secure - Allow packages to have empty checksums for downloaded resources from secure locations (HTTPS). Overrides the default feature '{0}' set to '{1}'.".FormatWith(ApplicationParameters.Features.AllowEmptyChecksumsSecure, configuration.Features.AllowEmptyChecksumsSecure.ToStringSafe()), option => { if (option != null) configuration.Features.AllowEmptyChecksumsSecure = true; }) .Add("requirechecksum|requirechecksums|require-checksums", - "Require Checksums - Requires packages to have checksums for downloaded resources (both non-secure and secure). Overrides the default feature '{0}' set to '{1}' and '{2}' set to '{3}'. Available in 0.10.0+.".format_with(ApplicationParameters.Features.AllowEmptyChecksums, configuration.Features.AllowEmptyChecksums.to_string(), ApplicationParameters.Features.AllowEmptyChecksumsSecure, configuration.Features.AllowEmptyChecksumsSecure.to_string()), + "Require Checksums - Requires packages to have checksums for downloaded resources (both non-secure and secure). Overrides the default feature '{0}' set to '{1}' and '{2}' set to '{3}'.".FormatWith(ApplicationParameters.Features.AllowEmptyChecksums, configuration.Features.AllowEmptyChecksums.ToStringSafe(), ApplicationParameters.Features.AllowEmptyChecksumsSecure, configuration.Features.AllowEmptyChecksumsSecure.ToStringSafe()), option => { if (option != null) @@ -135,19 +135,19 @@ public virtual void configure_argument_parser(OptionSet optionSet, ChocolateyCon } }) .Add("checksum=|downloadchecksum=|download-checksum=", - "Download Checksum - a user provided checksum for downloaded resources for the package. Overrides the package checksum (if it has one). Defaults to empty. Available in 0.10.0+.", - option => configuration.DownloadChecksum = option.remove_surrounding_quotes()) + "Download Checksum - a user provided checksum for downloaded resources for the package. Overrides the package checksum (if it has one). Defaults to empty.", + option => configuration.DownloadChecksum = option.UnquoteSafe()) .Add("checksum64=|checksumx64=|downloadchecksumx64=|download-checksum-x64=", - "Download Checksum 64bit - a user provided checksum for 64bit downloaded resources for the package. Overrides the package 64-bit checksum (if it has one). Defaults to same as Download Checksum. Available in 0.10.0+.", - option => configuration.DownloadChecksum64 = option.remove_surrounding_quotes()) + "Download Checksum 64bit - a user provided checksum for 64bit downloaded resources for the package. Overrides the package 64-bit checksum (if it has one). Defaults to same as Download Checksum.", + option => configuration.DownloadChecksum64 = option.UnquoteSafe()) .Add("checksumtype=|checksum-type=|downloadchecksumtype=|download-checksum-type=", - "Download Checksum Type - a user provided checksum type. Overrides the package checksum type (if it has one). Used in conjunction with Download Checksum. Available values are 'md5', 'sha1', 'sha256' or 'sha512'. Defaults to 'md5'. Available in 0.10.0+.", - option => configuration.DownloadChecksumType = option.remove_surrounding_quotes()) + "Download Checksum Type - a user provided checksum type. Overrides the package checksum type (if it has one). Used in conjunction with Download Checksum. Available values are 'md5', 'sha1', 'sha256' or 'sha512'. Defaults to 'md5'.", + option => configuration.DownloadChecksumType = option.UnquoteSafe()) .Add("checksumtype64=|checksumtypex64=|checksum-type-x64=|downloadchecksumtypex64=|download-checksum-type-x64=", - "Download Checksum Type 64bit - a user provided checksum for 64bit downloaded resources for the package. Overrides the package 64-bit checksum (if it has one). Used in conjunction with Download Checksum 64bit. Available values are 'md5', 'sha1', 'sha256' or 'sha512'. Defaults to same as Download Checksum Type. Available in 0.10.0+.", - option => configuration.DownloadChecksumType64 = option.remove_surrounding_quotes()) + "Download Checksum Type 64bit - a user provided checksum for 64bit downloaded resources for the package. Overrides the package 64-bit checksum (if it has one). Used in conjunction with Download Checksum 64bit. Available values are 'md5', 'sha1', 'sha256' or 'sha512'. Defaults to same as Download Checksum Type.", + option => configuration.DownloadChecksumType64 = option.UnquoteSafe()) .Add("ignorepackagecodes|ignorepackageexitcodes|ignore-package-codes|ignore-package-exit-codes", - "IgnorePackageExitCodes - Exit with a 0 for success and 1 for non-success, no matter what package scripts provide for exit codes. Overrides the default feature '{0}' set to '{1}'. Available in 0.9.10+.".format_with(ApplicationParameters.Features.UsePackageExitCodes, configuration.Features.UsePackageExitCodes.to_string()), + "IgnorePackageExitCodes - Exit with a 0 for success and 1 for non-success, no matter what package scripts provide for exit codes. Overrides the default feature '{0}' set to '{1}'.".FormatWith(ApplicationParameters.Features.UsePackageExitCodes, configuration.Features.UsePackageExitCodes.ToStringSafe()), option => { if (option != null) @@ -156,21 +156,21 @@ public virtual void configure_argument_parser(OptionSet optionSet, ChocolateyCon } }) .Add("usepackagecodes|usepackageexitcodes|use-package-codes|use-package-exit-codes", - "UsePackageExitCodes - Package scripts can provide exit codes. Use those for choco's exit code when non-zero (this value can come from a dependency package). Chocolatey defines valid exit codes as 0, 1605, 1614, 1641, 3010. Overrides the default feature '{0}' set to '{1}'. Available in 0.9.10+.".format_with(ApplicationParameters.Features.UsePackageExitCodes, configuration.Features.UsePackageExitCodes.to_string()), + "UsePackageExitCodes - Package scripts can provide exit codes. Use those for choco's exit code when non-zero (this value can come from a dependency package). Chocolatey defines valid exit codes as 0, 1605, 1614, 1641, 3010. Overrides the default feature '{0}' set to '{1}'.".FormatWith(ApplicationParameters.Features.UsePackageExitCodes, configuration.Features.UsePackageExitCodes.ToStringSafe()), option => configuration.Features.UsePackageExitCodes = option != null ) .Add("stoponfirstfailure|stop-on-first-failure|stop-on-first-package-failure", - "Stop On First Package Failure - stop running install, upgrade or uninstall on first package failure instead of continuing with others. Overrides the default feature '{0}' set to '{1}'. Available in 0.10.4+.".format_with(ApplicationParameters.Features.StopOnFirstPackageFailure, configuration.Features.StopOnFirstPackageFailure.to_string()), + "Stop On First Package Failure - stop running install, upgrade or uninstall on first package failure instead of continuing with others. Overrides the default feature '{0}' set to '{1}'.".FormatWith(ApplicationParameters.Features.StopOnFirstPackageFailure, configuration.Features.StopOnFirstPackageFailure.ToStringSafe()), option => configuration.Features.StopOnFirstPackageFailure = option != null ) .Add("exitwhenrebootdetected|exit-when-reboot-detected", - "Exit When Reboot Detected - Stop running install, upgrade, or uninstall when a reboot request is detected. Requires '{0}' feature to be turned on. Will exit with either {1} or {2}. Overrides the default feature '{3}' set to '{4}'. Available in 0.10.12+.".format_with - (ApplicationParameters.Features.UsePackageExitCodes, ApplicationParameters.ExitCodes.ErrorFailNoActionReboot, ApplicationParameters.ExitCodes.ErrorInstallSuspend, ApplicationParameters.Features.ExitOnRebootDetected, configuration.Features.ExitOnRebootDetected.to_string()), + "Exit When Reboot Detected - Stop running install, upgrade, or uninstall when a reboot request is detected. Requires '{0}' feature to be turned on. Will exit with either {1} or {2}. Overrides the default feature '{3}' set to '{4}'.".FormatWith + (ApplicationParameters.Features.UsePackageExitCodes, ApplicationParameters.ExitCodes.ErrorFailNoActionReboot, ApplicationParameters.ExitCodes.ErrorInstallSuspend, ApplicationParameters.Features.ExitOnRebootDetected, configuration.Features.ExitOnRebootDetected.ToStringSafe()), option => configuration.Features.ExitOnRebootDetected = option != null ) .Add("ignoredetectedreboot|ignore-detected-reboot", - "Ignore Detected Reboot - Ignore any detected reboots if found. Overrides the default feature '{0}' set to '{1}'. Available in 0.10.12+.".format_with - (ApplicationParameters.Features.ExitOnRebootDetected, configuration.Features.ExitOnRebootDetected.to_string()), + "Ignore Detected Reboot - Ignore any detected reboots if found. Overrides the default feature '{0}' set to '{1}'.".FormatWith + (ApplicationParameters.Features.ExitOnRebootDetected, configuration.Features.ExitOnRebootDetected.ToStringSafe()), option => { if (option != null) @@ -179,8 +179,8 @@ public virtual void configure_argument_parser(OptionSet optionSet, ChocolateyCon } }) .Add("disable-repository-optimizations|disable-package-repository-optimizations", - "Disable Package Repository Optimizations - Do not use optimizations for reducing bandwidth with repository queries during package install/upgrade/outdated operations. Should not generally be used, unless a repository needs to support older methods of query. When used, this makes queries similar to the way they were done in Chocolatey v0.10.11 and before. Overrides the default feature '{0}' set to '{1}'. Available in 0.10.14+.".format_with - (ApplicationParameters.Features.UsePackageRepositoryOptimizations, configuration.Features.UsePackageRepositoryOptimizations.to_string()), + "Disable Package Repository Optimizations - Do not use optimizations for reducing bandwidth with repository queries during package install/upgrade/outdated operations. Should not generally be used, unless a repository needs to support older methods of query. When used, this makes queries similar to the way they were done in earlier versions of Chocolatey. Overrides the default feature '{0}' set to '{1}'.".FormatWith + (ApplicationParameters.Features.UsePackageRepositoryOptimizations, configuration.Features.UsePackageRepositoryOptimizations.ToStringSafe()), option => { if (option != null) @@ -201,18 +201,18 @@ public virtual void configure_argument_parser(OptionSet optionSet, ChocolateyCon //todo: #770 package name can be a url / installertype } - public virtual void handle_additional_argument_parsing(IList unparsedArguments, ChocolateyConfiguration configuration) + public virtual void ParseAdditionalArguments(IList unparsedArguments, ChocolateyConfiguration configuration) { configuration.Input = string.Join(" ", unparsedArguments); - configuration.PackageNames = string.Join(ApplicationParameters.PackageNamesSeparator.to_string(), unparsedArguments.Where(arg => !arg.StartsWith("-"))); + configuration.PackageNames = string.Join(ApplicationParameters.PackageNamesSeparator.ToStringSafe(), unparsedArguments.Where(arg => !arg.StartsWith("-"))); if (configuration.RegularOutput) { - warn_for_removed_options(unparsedArguments.Where(arg => arg.StartsWith("-")), _removedOptions); + WarnForRemovedOptions(unparsedArguments.Where(arg => arg.StartsWith("-")), _removedOptions); } } - public virtual void handle_validation(ChocolateyConfiguration configuration) + public virtual void Validate(ChocolateyConfiguration configuration) { if (string.IsNullOrWhiteSpace(configuration.PackageNames)) { @@ -235,12 +235,12 @@ public virtual void handle_validation(ChocolateyConfiguration configuration) var unparsedOptionsAndPackages = configuration.Input.Split(new[] { " " }, StringSplitOptions.RemoveEmptyEntries); if (!configuration.Information.IsLicensedVersion) { - foreach (var argument in unparsedOptionsAndPackages.or_empty_list_if_null()) + foreach (var argument in unparsedOptionsAndPackages.OrEmpty()) { - var arg = argument.to_lower(); + var arg = argument.ToLowerSafe(); if (arg.StartsWith("-dir") || arg.StartsWith("--dir") || arg.StartsWith("-install") || arg.StartsWith("--install")) { - throw new ApplicationException("It appears you are attempting to use options that may be only available in licensed versions of Chocolatey ('{0}'). There may be ways in the open source edition to achieve what you are looking to do. Please remove the argument and consult the documentation.".format_with(arg)); + throw new ApplicationException("It appears you are attempting to use options that may be only available in licensed versions of Chocolatey ('{0}'). There may be ways in the open source edition to achieve what you are looking to do. Please remove the argument and consult the documentation.".FormatWith(arg)); } } } @@ -248,23 +248,18 @@ public virtual void handle_validation(ChocolateyConfiguration configuration) if (!string.IsNullOrWhiteSpace(configuration.SourceCommand.Username) && string.IsNullOrWhiteSpace(configuration.SourceCommand.Password)) { - this.Log().Debug(ChocolateyLoggers.LogFileOnly, "Username '{0}' provided. Asking for password.".format_with(configuration.SourceCommand.Username)); - System.Console.Write("User name '{0}' provided. Password: ".format_with(configuration.SourceCommand.Username)); - configuration.SourceCommand.Password = InteractivePrompt.get_password(configuration.PromptForConfirmation); + this.Log().Debug(ChocolateyLoggers.LogFileOnly, "Username '{0}' provided. Asking for password.".FormatWith(configuration.SourceCommand.Username)); + System.Console.Write("User name '{0}' provided. Password: ".FormatWith(configuration.SourceCommand.Username)); + configuration.SourceCommand.Password = InteractivePrompt.GetPassword(configuration.PromptForConfirmation); } } - public virtual void help_message(ChocolateyConfiguration configuration) + public virtual void HelpMessage(ChocolateyConfiguration configuration) { this.Log().Info(ChocolateyLoggers.Important, "Install Command"); this.Log().Info(@" Installs a package or a list of packages (sometimes specified as a packages.config). - -NOTE: 100% compatible with older chocolatey client (0.9.8.32 and below) - with options and switches. Add `-y` for previous behavior with no - prompt. In most cases you can still pass options and switches with one - dash (`-`). For more details, see the command reference (`choco -?`). "); "chocolatey".Log().Info(ChocolateyLoggers.Important, "Usage"); @@ -331,7 +326,6 @@ Exit codes that normally result from running this command. In addition to normal exit codes, packages are allowed to exit with their own codes when the feature '{0}' is turned on. Uninstall command has additional valid exit codes. - Available in v0.9.10+. Reboot Exit Codes: - 350: pending reboot detected, no action has occurred @@ -340,8 +334,7 @@ Available in v0.9.10+. In addition to the above exit codes, you may also see reboot exit codes when the feature '{1}' is turned on. It typically requires the feature '{0}' to also be turned on to work properly. - Available in v0.10.12+. -".format_with(ApplicationParameters.Features.UsePackageExitCodes, ApplicationParameters.Features.ExitOnRebootDetected)); +".FormatWith(ApplicationParameters.Features.UsePackageExitCodes, ApplicationParameters.Features.ExitOnRebootDetected)); "chocolatey".Log().Info(ChocolateyLoggers.Important, "See It In Action"); "chocolatey".Log().Info(@" @@ -376,7 +369,6 @@ Chocolatey Professional showing private download cache and virus scan "); "chocolatey".Log().Info(ChocolateyLoggers.Important, "Alternative Sources"); "chocolatey".Log().Info(@" -Available in 0.9.10+. Ruby This specifies the source is Ruby Gems and that we are installing a @@ -424,20 +416,49 @@ pass specific options. "); } - public virtual void noop(ChocolateyConfiguration configuration) + public virtual void DryRun(ChocolateyConfiguration configuration) { - _packageService.install_noop(configuration); + _packageService.InstallDryRun(configuration); } - public virtual void run(ChocolateyConfiguration configuration) + public virtual void Run(ChocolateyConfiguration configuration) { - _packageService.ensure_source_app_installed(configuration); - _packageService.install_run(configuration); + _packageService.Install(configuration); } - public virtual bool may_require_admin_access() + public virtual bool MayRequireAdminAccess() { return true; } + +#pragma warning disable IDE1006 + [Obsolete("This overload is deprecated and will be removed in v3.")] + public virtual void configure_argument_parser(OptionSet optionSet, ChocolateyConfiguration configuration) + => ConfigureArgumentParser(optionSet, configuration); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public virtual void handle_additional_argument_parsing(IList unparsedArguments, ChocolateyConfiguration configuration) + => ParseAdditionalArguments(unparsedArguments, configuration); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public virtual void handle_validation(ChocolateyConfiguration configuration) + => Validate(configuration); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public virtual void help_message(ChocolateyConfiguration configuration) + => HelpMessage(configuration); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public virtual void noop(ChocolateyConfiguration configuration) + => DryRun(configuration); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public virtual void run(ChocolateyConfiguration configuration) + => Run(configuration); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public virtual bool may_require_admin_access() + => MayRequireAdminAccess(); +#pragma warning restore IDE1006 } } diff --git a/src/chocolatey/infrastructure.app/commands/ChocolateyListCommand.cs b/src/chocolatey/infrastructure.app/commands/ChocolateyListCommand.cs index 8c41bbbddd..e730243774 100644 --- a/src/chocolatey/infrastructure.app/commands/ChocolateyListCommand.cs +++ b/src/chocolatey/infrastructure.app/commands/ChocolateyListCommand.cs @@ -20,6 +20,7 @@ namespace chocolatey.infrastructure.app.commands using System.Linq; using chocolatey.infrastructure.app.attributes; using chocolatey.infrastructure.app.configuration; + using chocolatey.infrastructure.app.domain; using chocolatey.infrastructure.app.services; using chocolatey.infrastructure.commandline; using chocolatey.infrastructure.commands; @@ -36,26 +37,59 @@ public class ChocolateyListCommand : IListCommand { "-l", "-lo", + "--lo", + "-local", "--local", + "-localonly", "--localonly", + "-local-only", "--local-only", "-a", + "-all", "--all", + "-allversions", "--allversions", + "-all-versions", "--all-versions", + "-order-by-popularity", "--order-by-popularity" }; + /// + /// These options have been chosen since these are the examples that were listed on docs.chocolatey.org + /// - choco list -li + /// - choco list -lai + /// + [Obsolete("Remove unsupported argument in V3!")] + private readonly string[] _unsupportedIncludeRegistryProgramsArguments = new[] + { + "-li", + "-il", + "-lai", + "-lia", + "-ali", + "-ail", + "-ial", + "-ila" + }; + public ChocolateyListCommand(IChocolateyPackageService packageService) { _packageService = packageService ?? throw new ArgumentNullException(nameof(packageService)); } - public virtual void configure_argument_parser(OptionSet optionSet, ChocolateyConfiguration configuration) + public virtual void ConfigureArgumentParser(OptionSet optionSet, ChocolateyConfiguration configuration) { optionSet + .Add("s=|source=", + "Source - Name of alternative source to use, for example 'windowsfeatures', 'ruby', 'cygwin', or 'python'.", + option => + { + configuration.Sources = option.UnquoteSafe(); + configuration.ListCommand.ExplicitSource = true; + }) .Add("idonly|id-only", - "Id Only - Only return Package Ids in the list results. Available in 0.10.6+.", + "Id Only - Only return Package Ids in the list results.", option => configuration.ListCommand.IdOnly = option != null) .Add("pre|prerelease", "Prerelease - Include Prereleases? Defaults to false.", @@ -65,9 +99,9 @@ public virtual void configure_argument_parser(OptionSet optionSet, ChocolateyCon option => configuration.ListCommand.IncludeRegistryPrograms = option != null) .Add("version=", "Version - Specific version of a package to return.", - option => configuration.Version = option.remove_surrounding_quotes()) + option => configuration.Version = option.UnquoteSafe()) .Add("page=", - "Page - the 'page' of results to return. Defaults to return all results. Available in 0.9.10+.", + "Page - the 'page' of results to return. Defaults to return all results.", option => { if (int.TryParse(option, out var page)) @@ -80,47 +114,59 @@ public virtual void configure_argument_parser(OptionSet optionSet, ChocolateyCon } }) .Add("page-size=", // Does it make sense to have paging on local packages? - "Page Size - the amount of package results to return per page. Defaults to 25. Available in 0.9.10+.", + "Page Size - the amount of package results to return per page. Defaults to 25.", option => { configuration.ListCommand.PageSize = int.Parse(option); configuration.ListCommand.ExplicitPageSize = true; }) .Add("e|exact", - "Exact - Only return packages with this exact name. Available in 0.9.10+.", + "Exact - Only return packages with this exact name.", option => configuration.ListCommand.Exact = option != null) .Add("by-id-only", - "ByIdOnly - Only return packages where the id contains the search filter. Available in 0.9.10+.", + "ByIdOnly - Only return packages where the id contains the search filter.", option => configuration.ListCommand.ByIdOnly = option != null) .Add("by-tag-only|by-tags-only", - "ByTagOnly - Only return packages where the search filter matches on the tags. Available in 0.10.6+.", + "ByTagOnly - Only return packages where the search filter matches on the tags.", option => configuration.ListCommand.ByTagOnly = option != null) .Add("id-starts-with", - "IdStartsWith - Only return packages where the id starts with the search filter. Available in 0.9.10+.", + "IdStartsWith - Only return packages where the id starts with the search filter.", option => configuration.ListCommand.IdStartsWith = option != null) .Add("detail|detailed", - "Detailed - Alias for verbose. Available in 0.9.10+.", + "Detailed - Alias for verbose.", option => configuration.Verbose = option != null); } - public virtual int count(ChocolateyConfiguration config) + public virtual int Count(ChocolateyConfiguration config) { config.ListCommand.LocalOnly = true; config.QuietOutput = true; - return _packageService.count_run(config); + return _packageService.Count(config); } - public virtual void handle_additional_argument_parsing(IList unparsedArguments, ChocolateyConfiguration configuration) + public virtual void ParseAdditionalArguments(IList unparsedArguments, ChocolateyConfiguration configuration) { var argumentsWithoutLocalOnly = new List(unparsedArguments.Count); foreach (var argument in unparsedArguments) { - if (_unsupportedArguments.Contains(argument, StringComparer.OrdinalIgnoreCase)) + bool isUnsupportedArgument = _unsupportedArguments.Contains(argument, StringComparer.OrdinalIgnoreCase); + bool isUnsupportedRegistryProgramsArgument = _unsupportedIncludeRegistryProgramsArguments.Contains(argument, StringComparer.OrdinalIgnoreCase); + + if (isUnsupportedArgument || isUnsupportedRegistryProgramsArgument) { - this.Log().Warn(ChocolateyLoggers.Important, @" -UNSUPPORTED ARGUMENT: Ignoring the argument {0}. This argument is unsupported for locally installed packages, and will be treated as a package name in Chocolatey CLI v3!", argument); + if (configuration.RegularOutput) + { + throw new ApplicationException("Invalid argument {0}. This argument has been removed from the list command and cannot be used.".FormatWith(argument)); + } + + if (isUnsupportedRegistryProgramsArgument) + { + configuration.ListCommand.IncludeRegistryPrograms = true; + } + + this.Log().Warn(ChocolateyLoggers.LogFileOnly, "Ignoring the argument {0}. This argument is unsupported for locally installed packages.", argument); } else { @@ -131,12 +177,12 @@ public virtual void handle_additional_argument_parsing(IList unparsedArg configuration.Input = string.Join(" ", argumentsWithoutLocalOnly); } - public virtual void handle_validation(ChocolateyConfiguration configuration) + public virtual void Validate(ChocolateyConfiguration configuration) { // There is nothing to validate. } - public virtual void help_message(ChocolateyConfiguration configuration) + public virtual void HelpMessage(ChocolateyConfiguration configuration) { this.Log().Info(ChocolateyLoggers.Important, "List Command"); this.Log().Info(string.Empty); @@ -144,17 +190,17 @@ public virtual void help_message(ChocolateyConfiguration configuration) this.Log().Info(ChocolateyLoggers.Important, "Usage"); this.Log().Info(@" choco {0} [] -".format_with(configuration.CommandName)); +".FormatWith(configuration.CommandName)); this.Log().Info(ChocolateyLoggers.Important, "Examples"); this.Log().Info(@" - choco {0} --local-only - choco {0} --local-only --include-programs + choco list -i + choco list --include-programs NOTE: See scripting in the command reference (`choco -?`) for how to write proper scripts and integrations. -".format_with(configuration.CommandName)); +"); this.Log().Info(ChocolateyLoggers.Important, "Exit Codes"); this.Log().Info(@" @@ -169,45 +215,52 @@ Exit codes that normally result from running this command. - -1 or 1: an error has occurred - 2: no results (enhanced) -NOTE: Starting in v0.10.12, if you have the feature '{0}' - turned on, then choco will provide enhanced exit codes that allow +NOTE: If you have the feature '{0}' turned on, + then choco will provide enhanced exit codes that allow better integration and scripting. If you find other exit codes that we have not yet documented, please file a ticket so we can document it at https://github.com/chocolatey/choco/issues/new/choose. -".format_with(ApplicationParameters.Features.UseEnhancedExitCodes)); +".FormatWith(ApplicationParameters.Features.UseEnhancedExitCodes)); this.Log().Info(ChocolateyLoggers.Important, "Options and Switches"); } - public virtual IEnumerable list(ChocolateyConfiguration config) + public virtual IEnumerable List(ChocolateyConfiguration config) { config.ListCommand.LocalOnly = true; config.QuietOutput = true; - return _packageService.list_run(config); + return _packageService.List(config); } - public virtual bool may_require_admin_access() + public virtual bool MayRequireAdminAccess() { return false; } - public virtual void noop(ChocolateyConfiguration configuration) + public virtual void DryRun(ChocolateyConfiguration configuration) { configuration.ListCommand.LocalOnly = true; - _packageService.list_noop(configuration); + _packageService.ListDryRun(configuration); } - public virtual void run(ChocolateyConfiguration config) + public virtual void Run(ChocolateyConfiguration config) { + // Would have liked to have done this in the Validate method, but can't, since the SourceType + // hasn't yet been set, since the sources have not yet been parsed. + if (config.ListCommand.ExplicitSource && config.SourceType == SourceTypes.Normal) + { + throw new ApplicationException("When using the '--source' option with the 'choco list' command, only a named alternative source can be provided."); + } + config.ListCommand.LocalOnly = true; // note: you must leave the .ToList() here or else the method won't be evaluated! - var packageResults = _packageService.list_run(config).ToList(); + var packageResults = _packageService.List(config).ToList(); // if there are no results, exit with a 2 if enhanced exit codes is enabled. if (config.Features.UseEnhancedExitCodes && packageResults.Count == 0 && Environment.ExitCode == 0) @@ -215,5 +268,43 @@ public virtual void run(ChocolateyConfiguration config) Environment.ExitCode = 2; } } + +#pragma warning disable IDE1006 + [Obsolete("This overload is deprecated and will be removed in v3.")] + public virtual void configure_argument_parser(OptionSet optionSet, ChocolateyConfiguration configuration) + => ConfigureArgumentParser(optionSet, configuration); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public virtual void handle_additional_argument_parsing(IList unparsedArguments, ChocolateyConfiguration configuration) + => ParseAdditionalArguments(unparsedArguments, configuration); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public virtual void handle_validation(ChocolateyConfiguration configuration) + => Validate(configuration); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public virtual void help_message(ChocolateyConfiguration configuration) + => HelpMessage(configuration); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public virtual void noop(ChocolateyConfiguration configuration) + => DryRun(configuration); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public virtual void run(ChocolateyConfiguration configuration) + => Run(configuration); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public virtual bool may_require_admin_access() + => MayRequireAdminAccess(); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public virtual int count(ChocolateyConfiguration config) + => Count(config); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public virtual IEnumerable list(ChocolateyConfiguration config) + => List(config); +#pragma warning restore IDE1006 } } diff --git a/src/chocolatey/infrastructure.app/commands/ChocolateyNewCommand.cs b/src/chocolatey/infrastructure.app/commands/ChocolateyNewCommand.cs index a34feb86fc..859f51affe 100644 --- a/src/chocolatey/infrastructure.app/commands/ChocolateyNewCommand.cs +++ b/src/chocolatey/infrastructure.app/commands/ChocolateyNewCommand.cs @@ -37,44 +37,44 @@ public ChocolateyNewCommand(ITemplateService templateService) _templateService = templateService; } - public virtual void configure_argument_parser(OptionSet optionSet, ChocolateyConfiguration configuration) + public virtual void ConfigureArgumentParser(OptionSet optionSet, ChocolateyConfiguration configuration) { optionSet .Add("a|auto|automaticpackage", "AutomaticPackage - Generate automatic package instead of normal. Defaults to false", option => configuration.NewCommand.AutomaticPackage = option != null) .Add("t=|template=|template-name=", - "TemplateName - Use a named template in {0}\\templates\\templatename instead of built-in template. Available in 0.9.9.9+. Manage templates as packages in 0.9.10+.".format_with(ApplicationParameters.InstallLocation), - option => configuration.NewCommand.TemplateName = option.remove_surrounding_quotes()) + "TemplateName - Use a named template in {0}\\templates\\templatename instead of built-in template.".FormatWith(ApplicationParameters.InstallLocation), + option => configuration.NewCommand.TemplateName = option.UnquoteSafe()) .Add("name=", "Name [Required]- the name of the package. Can be passed as first parameter without \"--name=\".", option => { - configuration.NewCommand.Name = option.remove_surrounding_quotes(); - configuration.NewCommand.TemplateProperties.Add(TemplateValues.NamePropertyName, option.remove_surrounding_quotes()); + configuration.NewCommand.Name = option.UnquoteSafe(); + configuration.NewCommand.TemplateProperties.Add(TemplateValues.NamePropertyName, option.UnquoteSafe()); }) .Add("version=", "Version - the version of the package. Can also be passed as the property PackageVersion=somevalue", - option => configuration.NewCommand.TemplateProperties.Add(TemplateValues.VersionPropertyName, option.remove_surrounding_quotes())) + option => configuration.NewCommand.TemplateProperties.Add(TemplateValues.VersionPropertyName, option.UnquoteSafe())) .Add("maintainer=", "Maintainer - the name of the maintainer. Can also be passed as the property MaintainerName=somevalue", - option => configuration.NewCommand.TemplateProperties.Add(TemplateValues.MaintainerPropertyName, option.remove_surrounding_quotes())) + option => configuration.NewCommand.TemplateProperties.Add(TemplateValues.MaintainerPropertyName, option.UnquoteSafe())) .Add("out=|outdir=|outputdirectory=|output-directory=", - "OutputDirectory - Specifies the directory for the created Chocolatey package file. If not specified, uses the current directory. Available in 0.9.10+.", - option => configuration.OutputDirectory = option.remove_surrounding_quotes()) + "OutputDirectory - Specifies the directory for the created Chocolatey package file. If not specified, uses the current directory.", + option => configuration.OutputDirectory = option.UnquoteSafe()) .Add("built-in|built-in-template|originaltemplate|original-template|use-original-template|use-built-in-template", - "BuiltInTemplate - Use the original built-in template instead of any override. Available in 0.9.10+.", + "BuiltInTemplate - Use the original built-in template instead of any override.", option => configuration.NewCommand.UseOriginalTemplate = option != null) ; } - public virtual void handle_additional_argument_parsing(IList unparsedArguments, ChocolateyConfiguration configuration) + public virtual void ParseAdditionalArguments(IList unparsedArguments, ChocolateyConfiguration configuration) { configuration.Input = string.Join(" ", unparsedArguments); if (string.IsNullOrWhiteSpace(configuration.NewCommand.Name)) { - configuration.NewCommand.Name = unparsedArguments.DefaultIfEmpty(string.Empty).FirstOrDefault(arg => !arg.StartsWith("-") && !arg.contains("=")); + configuration.NewCommand.Name = unparsedArguments.DefaultIfEmpty(string.Empty).FirstOrDefault(arg => !arg.StartsWith("-") && !arg.ContainsSafe("=")); var property = unparsedArguments.DefaultIfEmpty(string.Empty).FirstOrDefault().Split(new[] {'='}, StringSplitOptions.RemoveEmptyEntries); if (property.Length == 1) { @@ -82,17 +82,17 @@ public virtual void handle_additional_argument_parsing(IList unparsedArg } } - foreach (var unparsedArgument in unparsedArguments.or_empty_list_if_null()) + foreach (var unparsedArgument in unparsedArguments.OrEmpty()) { var property = unparsedArgument.Split(new[] { '=' }, 2, StringSplitOptions.RemoveEmptyEntries); if (property.Length == 2) { - var propName = property[0].trim_safe(); - var propValue = property[1].trim_safe().remove_surrounding_quotes(); + var propName = property[0].TrimSafe(); + var propValue = property[1].TrimSafe().UnquoteSafe(); if (configuration.NewCommand.TemplateProperties.ContainsKey(propName)) { - this.Log().Warn(() => "A value for '{0}' has already been added with the value '{1}'. Ignoring {0}='{2}'.".format_with(propName, configuration.NewCommand.TemplateProperties[propName], propValue)); + this.Log().Warn(() => "A value for '{0}' has already been added with the value '{1}'. Ignoring {0}='{2}'.".FormatWith(propName, configuration.NewCommand.TemplateProperties[propName], propValue)); } else { @@ -102,7 +102,7 @@ public virtual void handle_additional_argument_parsing(IList unparsedArg } } - public virtual void handle_validation(ChocolateyConfiguration configuration) + public virtual void Validate(ChocolateyConfiguration configuration) { if (string.IsNullOrWhiteSpace(configuration.NewCommand.Name)) { @@ -116,7 +116,7 @@ public virtual void handle_validation(ChocolateyConfiguration configuration) } } - public virtual void help_message(ChocolateyConfiguration configuration) + public virtual void HelpMessage(ChocolateyConfiguration configuration) { this.Log().Info(ChocolateyLoggers.Important, "New Command"); this.Log().Info(@" @@ -136,7 +136,7 @@ public virtual void help_message(ChocolateyConfiguration configuration) url64 silentargs -NOTE: Starting in 0.9.10, you can pass arbitrary property value pairs +NOTE: You can pass arbitrary property value pairs through to templates. This really unlocks your ability to create packages automatically! @@ -178,19 +178,49 @@ file a ticket so we can document it at "chocolatey".Log().Info(ChocolateyLoggers.Important, "Options and Switches"); } - public virtual void noop(ChocolateyConfiguration configuration) + public virtual void DryRun(ChocolateyConfiguration configuration) { - _templateService.generate_noop(configuration); + _templateService.GenerateDryRun(configuration); } - public virtual void run(ChocolateyConfiguration configuration) + public virtual void Run(ChocolateyConfiguration configuration) { - _templateService.generate(configuration); + _templateService.Generate(configuration); } - public virtual bool may_require_admin_access() + public virtual bool MayRequireAdminAccess() { return false; } + +#pragma warning disable IDE1006 + [Obsolete("This overload is deprecated and will be removed in v3.")] + public virtual void configure_argument_parser(OptionSet optionSet, ChocolateyConfiguration configuration) + => ConfigureArgumentParser(optionSet, configuration); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public virtual void handle_additional_argument_parsing(IList unparsedArguments, ChocolateyConfiguration configuration) + => ParseAdditionalArguments(unparsedArguments, configuration); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public virtual void handle_validation(ChocolateyConfiguration configuration) + => Validate(configuration); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public virtual void help_message(ChocolateyConfiguration configuration) + => HelpMessage(configuration); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public virtual void noop(ChocolateyConfiguration configuration) + => DryRun(configuration); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public virtual void run(ChocolateyConfiguration configuration) + => Run(configuration); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public virtual bool may_require_admin_access() + => MayRequireAdminAccess(); +#pragma warning restore IDE1006 } } diff --git a/src/chocolatey/infrastructure.app/commands/ChocolateyOutdatedCommand.cs b/src/chocolatey/infrastructure.app/commands/ChocolateyOutdatedCommand.cs index 6b125f7c7a..af63ffed56 100644 --- a/src/chocolatey/infrastructure.app/commands/ChocolateyOutdatedCommand.cs +++ b/src/chocolatey/infrastructure.app/commands/ChocolateyOutdatedCommand.cs @@ -16,6 +16,7 @@ namespace chocolatey.infrastructure.app.commands { + using System; using System.Collections.Generic; using attributes; using commandline; @@ -34,36 +35,36 @@ public ChocolateyOutdatedCommand(IChocolateyPackageService packageService) _packageService = packageService; } - public virtual void configure_argument_parser(OptionSet optionSet, ChocolateyConfiguration configuration) + public virtual void ConfigureArgumentParser(OptionSet optionSet, ChocolateyConfiguration configuration) { optionSet .Add("s=|source=", "Source - The source to find the package(s) to install. Special sources include: ruby, cygwin, windowsfeatures, and python. To specify more than one source, pass it with a semi-colon separating the values (e.g. \"'source1;source2'\"). Defaults to default feeds.", - option => configuration.Sources = option.remove_surrounding_quotes()) + option => configuration.Sources = option.UnquoteSafe()) .Add("u=|user=", "User - used with authenticated feeds. Defaults to empty.", - option => configuration.SourceCommand.Username = option.remove_surrounding_quotes()) + option => configuration.SourceCommand.Username = option.UnquoteSafe()) .Add("p=|password=", "Password - the user's password to the source. Defaults to empty.", - option => configuration.SourceCommand.Password = option.remove_surrounding_quotes()) + option => configuration.SourceCommand.Password = option.UnquoteSafe()) .Add("cert=", - "Client certificate - PFX pathname for an x509 authenticated feeds. Defaults to empty. Available in 0.9.10+.", - option => configuration.SourceCommand.Certificate = option.remove_surrounding_quotes()) + "Client certificate - PFX pathname for an x509 authenticated feeds. Defaults to empty.", + option => configuration.SourceCommand.Certificate = option.UnquoteSafe()) .Add("cp=|certpassword=", - "Certificate Password - the client certificate's password to the source. Defaults to empty. Available in 0.9.10+.", - option => configuration.SourceCommand.CertificatePassword = option.remove_surrounding_quotes()) + "Certificate Password - the client certificate's password to the source. Defaults to empty.", + option => configuration.SourceCommand.CertificatePassword = option.UnquoteSafe()) .Add("pre|prerelease", - "Prerelease - Include Prereleases? Defaults to false. Available in 0.10.14+.", + "Prerelease - Include Prereleases? Defaults to false.", option => configuration.Prerelease = option != null) .Add("ignore-pinned", - "Ignore Pinned - Ignore pinned packages. Defaults to false. Available in 0.10.6+.", + "Ignore Pinned - Ignore pinned packages. Defaults to false.", option => configuration.OutdatedCommand.IgnorePinned = option != null) .Add("ignore-unfound", - "Ignore Unfound Packages - Ignore packages that are not found on the sources used (or the defaults). Overrides the default feature '{0}' set to '{1}'. Available in 0.10.9+.".format_with(ApplicationParameters.Features.IgnoreUnfoundPackagesOnUpgradeOutdated, configuration.Features.IgnoreUnfoundPackagesOnUpgradeOutdated.to_string()), + "Ignore Unfound Packages - Ignore packages that are not found on the sources used (or the defaults). Overrides the default feature '{0}' set to '{1}'.".FormatWith(ApplicationParameters.Features.IgnoreUnfoundPackagesOnUpgradeOutdated, configuration.Features.IgnoreUnfoundPackagesOnUpgradeOutdated.ToStringSafe()), option => configuration.Features.IgnoreUnfoundPackagesOnUpgradeOutdated = option != null) .Add("disable-repository-optimizations|disable-package-repository-optimizations", - "Disable Package Repository Optimizations - Do not use optimizations for reducing bandwidth with repository queries during package install/upgrade/outdated operations. Should not generally be used, unless a repository needs to support older methods of query. When disabled, this makes queries similar to the way they were done in Chocolatey v0.10.11 and before. Overrides the default feature '{0}' set to '{1}'. Available in 0.10.14+.".format_with - (ApplicationParameters.Features.UsePackageRepositoryOptimizations, configuration.Features.UsePackageRepositoryOptimizations.to_string()), + "Disable Package Repository Optimizations - Do not use optimizations for reducing bandwidth with repository queries during package install/upgrade/outdated operations. Should not generally be used, unless a repository needs to support older methods of query. When disabled, this makes queries similar to the way they were done in earlier versions of Chocolatey. Overrides the default feature '{0}' set to '{1}'.".FormatWith + (ApplicationParameters.Features.UsePackageRepositoryOptimizations, configuration.Features.UsePackageRepositoryOptimizations.ToStringSafe()), option => { if (option != null) @@ -74,30 +75,28 @@ public virtual void configure_argument_parser(OptionSet optionSet, ChocolateyCon ; } - public virtual void handle_additional_argument_parsing(IList unparsedArguments, ChocolateyConfiguration configuration) + public virtual void ParseAdditionalArguments(IList unparsedArguments, ChocolateyConfiguration configuration) { configuration.Input = string.Join(" ", unparsedArguments); - configuration.PackageNames = string.Join(ApplicationParameters.PackageNamesSeparator.to_string(), unparsedArguments); + configuration.PackageNames = string.Join(ApplicationParameters.PackageNamesSeparator.ToStringSafe(), unparsedArguments); } - public virtual void handle_validation(ChocolateyConfiguration configuration) + public virtual void Validate(ChocolateyConfiguration configuration) { if (!string.IsNullOrWhiteSpace(configuration.SourceCommand.Username) && string.IsNullOrWhiteSpace(configuration.SourceCommand.Password)) { - this.Log().Debug(ChocolateyLoggers.LogFileOnly, "Username '{0}' provided. Asking for password.".format_with(configuration.SourceCommand.Username)); - System.Console.Write("User name '{0}' provided. Password: ".format_with(configuration.SourceCommand.Username)); - configuration.SourceCommand.Password = InteractivePrompt.get_password(configuration.PromptForConfirmation); + this.Log().Debug(ChocolateyLoggers.LogFileOnly, "Username '{0}' provided. Asking for password.".FormatWith(configuration.SourceCommand.Username)); + System.Console.Write("User name '{0}' provided. Password: ".FormatWith(configuration.SourceCommand.Username)); + configuration.SourceCommand.Password = InteractivePrompt.GetPassword(configuration.PromptForConfirmation); } } - public virtual void help_message(ChocolateyConfiguration configuration) + public virtual void HelpMessage(ChocolateyConfiguration configuration) { this.Log().Info(ChocolateyLoggers.Important, "Outdated Command"); this.Log().Info(@" Returns a list of outdated packages. -NOTE: Available with 0.9.9.6+. - "); "chocolatey".Log().Info(ChocolateyLoggers.Important, "Usage"); @@ -133,15 +132,15 @@ Exit codes that normally result from running this command. - -1 or 1: an error has occurred - 2: outdated packages have been found -NOTE: Starting in v0.10.12, if you have the feature '{0}' - turned on, then choco will provide enhanced exit codes that allow +NOTE: If you have the feature '{0}' turned on, + then choco will provide enhanced exit codes that allow better integration and scripting. If you find other exit codes that we have not yet documented, please file a ticket so we can document it at https://github.com/chocolatey/choco/issues/new/choose. -".format_with(ApplicationParameters.Features.UseEnhancedExitCodes)); +".FormatWith(ApplicationParameters.Features.UseEnhancedExitCodes)); "chocolatey".Log().Info(ChocolateyLoggers.Important, "See It In Action"); "chocolatey".Log().Info(@" @@ -152,19 +151,49 @@ file a ticket so we can document it at "chocolatey".Log().Info(ChocolateyLoggers.Important, "Options and Switches"); } - public virtual void noop(ChocolateyConfiguration configuration) + public virtual void DryRun(ChocolateyConfiguration configuration) { - _packageService.outdated_noop(configuration); + _packageService.OutdatedDryRun(configuration); } - public virtual void run(ChocolateyConfiguration configuration) + public virtual void Run(ChocolateyConfiguration configuration) { - _packageService.outdated_run(configuration); + _packageService.Outdated(configuration); } - public virtual bool may_require_admin_access() + public virtual bool MayRequireAdminAccess() { return false; } + +#pragma warning disable IDE1006 + [Obsolete("This overload is deprecated and will be removed in v3.")] + public virtual void configure_argument_parser(OptionSet optionSet, ChocolateyConfiguration configuration) + => ConfigureArgumentParser(optionSet, configuration); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public virtual void handle_additional_argument_parsing(IList unparsedArguments, ChocolateyConfiguration configuration) + => ParseAdditionalArguments(unparsedArguments, configuration); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public virtual void handle_validation(ChocolateyConfiguration configuration) + => Validate(configuration); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public virtual void help_message(ChocolateyConfiguration configuration) + => HelpMessage(configuration); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public virtual void noop(ChocolateyConfiguration configuration) + => DryRun(configuration); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public virtual void run(ChocolateyConfiguration configuration) + => Run(configuration); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public virtual bool may_require_admin_access() + => MayRequireAdminAccess(); +#pragma warning restore IDE1006 } } diff --git a/src/chocolatey/infrastructure.app/commands/ChocolateyPackCommand.cs b/src/chocolatey/infrastructure.app/commands/ChocolateyPackCommand.cs index a90c4e59bb..1236b00f91 100644 --- a/src/chocolatey/infrastructure.app/commands/ChocolateyPackCommand.cs +++ b/src/chocolatey/infrastructure.app/commands/ChocolateyPackCommand.cs @@ -36,34 +36,34 @@ public ChocolateyPackCommand(IChocolateyPackageService packageService) _packageService = packageService; } - public virtual void configure_argument_parser(OptionSet optionSet, ChocolateyConfiguration configuration) + public virtual void ConfigureArgumentParser(OptionSet optionSet, ChocolateyConfiguration configuration) { optionSet .Add("version=", "Version - The version you would like to insert into the package.", - option => configuration.Version = option.remove_surrounding_quotes()) + option => configuration.Version = option.UnquoteSafe()) .Add("out=|outdir=|outputdirectory=|output-directory=", "OutputDirectory - Specifies the directory for the created Chocolatey package file. If not specified, uses the current directory.", - option => configuration.OutputDirectory = option.remove_surrounding_quotes()) + option => configuration.OutputDirectory = option.UnquoteSafe()) ; } - public virtual void handle_additional_argument_parsing(IList unparsedArguments, ChocolateyConfiguration configuration) + public virtual void ParseAdditionalArguments(IList unparsedArguments, ChocolateyConfiguration configuration) { // First non-switch argument that is not a name=value pair will be treated as the nuspec file to pack. - configuration.Input = unparsedArguments.DefaultIfEmpty(string.Empty).FirstOrDefault(arg => !arg.StartsWith("-") && !arg.contains("=")); + configuration.Input = unparsedArguments.DefaultIfEmpty(string.Empty).FirstOrDefault(arg => !arg.StartsWith("-") && !arg.ContainsSafe("=")); - foreach (var unparsedArgument in unparsedArguments.or_empty_list_if_null()) + foreach (var unparsedArgument in unparsedArguments.OrEmpty()) { var property = unparsedArgument.Split(new[] { '=' }, 2, StringSplitOptions.RemoveEmptyEntries); if (property.Length == 2) { - var propName = property[0].trim_safe(); - var propValue = property[1].trim_safe().remove_surrounding_quotes(); + var propName = property[0].TrimSafe(); + var propValue = property[1].TrimSafe().UnquoteSafe(); if (configuration.PackCommand.Properties.ContainsKey(propName)) { - this.Log().Warn(() => "A value for '{0}' has already been added with the value '{1}'. Ignoring {0}='{2}'.".format_with(propName, configuration.PackCommand.Properties[propName], propValue)); + this.Log().Warn(() => "A value for '{0}' has already been added with the value '{1}'. Ignoring {0}='{2}'.".FormatWith(propName, configuration.PackCommand.Properties[propName], propValue)); } else { @@ -73,21 +73,16 @@ public virtual void handle_additional_argument_parsing(IList unparsedArg } } - public virtual void handle_validation(ChocolateyConfiguration configuration) + public virtual void Validate(ChocolateyConfiguration configuration) { } - public virtual void help_message(ChocolateyConfiguration configuration) + public virtual void HelpMessage(ChocolateyConfiguration configuration) { this.Log().Info(ChocolateyLoggers.Important, "Pack Command"); this.Log().Info(@" Chocolatey will attempt to package a nuspec into a compiled nupkg. -NOTE: 100% compatible with older chocolatey client (0.9.8.32 and below) - with options and switches. In most cases you can still pass options - and switches with one dash (`-`). For more details, see - the command reference (`choco -?`). - NOTE: You can pass arbitrary property value pairs through to nuspecs. These will replace variables formatted as `$property$` with the value passed. "); @@ -126,19 +121,49 @@ file a ticket so we can document it at "chocolatey".Log().Info(ChocolateyLoggers.Important, "Options and Switches"); } - public virtual void noop(ChocolateyConfiguration configuration) + public virtual void DryRun(ChocolateyConfiguration configuration) { - _packageService.pack_noop(configuration); + _packageService.PackDryRun(configuration); } - public virtual void run(ChocolateyConfiguration configuration) + public virtual void Run(ChocolateyConfiguration configuration) { - _packageService.pack_run(configuration); + _packageService.Pack(configuration); } - public virtual bool may_require_admin_access() + public virtual bool MayRequireAdminAccess() { return false; } + +#pragma warning disable IDE1006 + [Obsolete("This overload is deprecated and will be removed in v3.")] + public virtual void configure_argument_parser(OptionSet optionSet, ChocolateyConfiguration configuration) + => ConfigureArgumentParser(optionSet, configuration); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public virtual void handle_additional_argument_parsing(IList unparsedArguments, ChocolateyConfiguration configuration) + => ParseAdditionalArguments(unparsedArguments, configuration); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public virtual void handle_validation(ChocolateyConfiguration configuration) + => Validate(configuration); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public virtual void help_message(ChocolateyConfiguration configuration) + => HelpMessage(configuration); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public virtual void noop(ChocolateyConfiguration configuration) + => DryRun(configuration); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public virtual void run(ChocolateyConfiguration configuration) + => Run(configuration); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public virtual bool may_require_admin_access() + => MayRequireAdminAccess(); +#pragma warning restore IDE1006 } } diff --git a/src/chocolatey/infrastructure.app/commands/ChocolateyPinCommand.cs b/src/chocolatey/infrastructure.app/commands/ChocolateyPinCommand.cs index 6b085d51ff..38bf19321a 100644 --- a/src/chocolatey/infrastructure.app/commands/ChocolateyPinCommand.cs +++ b/src/chocolatey/infrastructure.app/commands/ChocolateyPinCommand.cs @@ -38,7 +38,7 @@ public class ChocolateyPinCommand : ICommand private readonly IChocolateyPackageInformationService _packageInfoService; private readonly ILogger _nugetLogger; private readonly INugetService _nugetService; - private const string NO_CHANGE_MESSAGE = "Nothing to change. Pin already set or removed."; + private const string NoChangeMessage = "Nothing to change. Pin already set or removed."; public ChocolateyPinCommand(IChocolateyPackageInformationService packageInfoService, ILogger nugetLogger, INugetService nugetService) { @@ -47,19 +47,19 @@ public ChocolateyPinCommand(IChocolateyPackageInformationService packageInfoServ _nugetService = nugetService; } - public virtual void configure_argument_parser(OptionSet optionSet, ChocolateyConfiguration configuration) + public virtual void ConfigureArgumentParser(OptionSet optionSet, ChocolateyConfiguration configuration) { optionSet .Add("n=|name=", "Name - the name of the package. Required with some actions. Defaults to empty.", - option => configuration.PinCommand.Name = option.remove_surrounding_quotes()) + option => configuration.PinCommand.Name = option.UnquoteSafe()) .Add("version=", "Version - Used when multiple versions of a package are installed. Defaults to empty.", - option => configuration.Version = option.remove_surrounding_quotes()) + option => configuration.Version = option.UnquoteSafe()) ; } - public virtual void handle_additional_argument_parsing(IList unparsedArguments, ChocolateyConfiguration configuration) + public virtual void ParseAdditionalArguments(IList unparsedArguments, ChocolateyConfiguration configuration) { // don't set configuration.Input or it will be passed to list @@ -68,14 +68,14 @@ public virtual void handle_additional_argument_parsing(IList unparsedArg throw new ApplicationException("A single pin command must be listed. Please see the help menu for those commands"); } - var command = PinCommandType.unknown; + var command = PinCommandType.Unknown; string unparsedCommand = unparsedArguments.DefaultIfEmpty(string.Empty).FirstOrDefault(); Enum.TryParse(unparsedCommand, true, out command); - if (command == PinCommandType.unknown) + if (command == PinCommandType.Unknown) { - if (!string.IsNullOrWhiteSpace(unparsedCommand)) this.Log().Warn("Unknown command {0}. Setting to list.".format_with(unparsedCommand)); - command = PinCommandType.list; + if (!string.IsNullOrWhiteSpace(unparsedCommand)) this.Log().Warn("Unknown command {0}. Setting to list.".FormatWith(unparsedCommand)); + command = PinCommandType.List; } configuration.PinCommand.Command = command; @@ -85,15 +85,15 @@ public virtual void handle_additional_argument_parsing(IList unparsedArg configuration.Prerelease = true; } - public virtual void handle_validation(ChocolateyConfiguration configuration) + public virtual void Validate(ChocolateyConfiguration configuration) { - if (configuration.PinCommand.Command != PinCommandType.list && string.IsNullOrWhiteSpace(configuration.PinCommand.Name)) + if (configuration.PinCommand.Command != PinCommandType.List && string.IsNullOrWhiteSpace(configuration.PinCommand.Name)) { - throw new ApplicationException("When specifying the subcommand '{0}', you must also specify --name.".format_with(configuration.PinCommand.Command.to_string())); + throw new ApplicationException("When specifying the subcommand '{0}', you must also specify --name.".FormatWith(configuration.PinCommand.Command.ToStringSafe().ToLower())); } } - public virtual void help_message(ChocolateyConfiguration configuration) + public virtual void HelpMessage(ChocolateyConfiguration configuration) { this.Log().Info(ChocolateyLoggers.Important, "Pin Command"); this.Log().Info(@" @@ -140,90 +140,120 @@ file a ticket so we can document it at "chocolatey".Log().Info(ChocolateyLoggers.Important, "Options and Switches"); } - public virtual void noop(ChocolateyConfiguration configuration) + public virtual void DryRun(ChocolateyConfiguration configuration) { - this.Log().Info("Pin would have called {0} with other options:{1} Name={2}{1} Version={3}".format_with(configuration.PinCommand.Command.to_string(), Environment.NewLine, configuration.PinCommand.Name, configuration.Version)); + this.Log().Info("Pin would have called {0} with other options:{1} Name={2}{1} Version={3}".FormatWith(configuration.PinCommand.Command.ToStringSafe(), Environment.NewLine, configuration.PinCommand.Name, configuration.Version)); } - public virtual void run(ChocolateyConfiguration configuration) + public virtual void Run(ChocolateyConfiguration configuration) { switch (configuration.PinCommand.Command) { - case PinCommandType.list: - list_pins(configuration); + case PinCommandType.List: + ListPins(configuration); break; - case PinCommandType.add: - case PinCommandType.remove: - set_pin(configuration); + case PinCommandType.Add: + case PinCommandType.Remove: + SetPin(configuration); break; } } - public virtual void list_pins(ChocolateyConfiguration config) + public virtual void ListPins(ChocolateyConfiguration config) { var input = config.Input; config.Input = string.Empty; var quiet = config.QuietOutput; config.QuietOutput = true; - var packages = _nugetService.list_run(config).ToList(); + var packages = _nugetService.List(config).ToList(); config.QuietOutput = quiet; config.Input = input; - foreach (var pkg in packages.or_empty_list_if_null()) + foreach (var pkg in packages.OrEmpty()) { - var pkgInfo = _packageInfoService.get_package_information(pkg.PackageMetadata); + var pkgInfo = _packageInfoService.Get(pkg.PackageMetadata); if (pkgInfo != null && pkgInfo.IsPinned) { - this.Log().Info(() => "{0}|{1}".format_with(pkgInfo.Package.Id, pkgInfo.Package.Version)); + this.Log().Info(() => "{0}|{1}".FormatWith(pkgInfo.Package.Id, pkgInfo.Package.Version)); } } } - public virtual void set_pin(ChocolateyConfiguration config) + public virtual void SetPin(ChocolateyConfiguration config) { - var addingAPin = config.PinCommand.Command == PinCommandType.add; - this.Log().Info("Trying to {0} a pin for {1}".format_with(config.PinCommand.Command.to_string(), config.PinCommand.Name)); + var addingAPin = config.PinCommand.Command == PinCommandType.Add; + this.Log().Info("Trying to {0} a pin for {1}".FormatWith(config.PinCommand.Command.ToStringSafe(), config.PinCommand.Name)); var versionUnspecified = string.IsNullOrWhiteSpace(config.Version); NuGetVersion semanticVersion = versionUnspecified ? null : NuGetVersion.Parse(config.Version); var input = config.Input; config.Input = config.PinCommand.Name; - config.Version = semanticVersion.to_full_string(); + config.Version = semanticVersion.ToFullStringChecked(); config.ListCommand.ByIdOnly = true; var quiet = config.QuietOutput; config.QuietOutput = true; - var installedPackage = _nugetService.list_run(config).FirstOrDefault(); + var installedPackage = _nugetService.List(config).FirstOrDefault(); config.QuietOutput = quiet; config.Input = input; if (installedPackage == null) { - throw new ApplicationException("Unable to find package named '{0}'{1} to pin. Please check to ensure it is installed.".format_with(config.PinCommand.Name, versionUnspecified ? "" : " (version '{0}')".format_with(config.Version))); + throw new ApplicationException("Unable to find package named '{0}'{1} to pin. Please check to ensure it is installed.".FormatWith(config.PinCommand.Name, versionUnspecified ? "" : " (version '{0}')".FormatWith(config.Version))); } - var pkgInfo = _packageInfoService.get_package_information(installedPackage.PackageMetadata); + var pkgInfo = _packageInfoService.Get(installedPackage.PackageMetadata); bool changeMessage = pkgInfo.IsPinned != addingAPin; pkgInfo.IsPinned = addingAPin; - _packageInfoService.save_package_information(pkgInfo); + _packageInfoService.Save(pkgInfo); if (changeMessage) { - this.Log().Warn("Successfully {0} a pin for {1} v{2}.".format_with(addingAPin ? "added" : "removed", pkgInfo.Package.Id, pkgInfo.Package.Version.to_full_string())); + this.Log().Warn("Successfully {0} a pin for {1} v{2}.".FormatWith(addingAPin ? "added" : "removed", pkgInfo.Package.Id, pkgInfo.Package.Version.ToFullStringChecked())); } else { - this.Log().Warn(NO_CHANGE_MESSAGE); + this.Log().Warn(NoChangeMessage); } } - public virtual bool may_require_admin_access() + public virtual bool MayRequireAdminAccess() { - var config = Config.get_configuration_settings(); + var config = Config.GetConfigurationSettings(); if (config == null) return true; - return config.PinCommand.Command != PinCommandType.list; + return config.PinCommand.Command != PinCommandType.List; } + +#pragma warning disable IDE1006 + [Obsolete("This overload is deprecated and will be removed in v3.")] + public virtual void configure_argument_parser(OptionSet optionSet, ChocolateyConfiguration configuration) + => ConfigureArgumentParser(optionSet, configuration); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public virtual void handle_additional_argument_parsing(IList unparsedArguments, ChocolateyConfiguration configuration) + => ParseAdditionalArguments(unparsedArguments, configuration); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public virtual void handle_validation(ChocolateyConfiguration configuration) + => Validate(configuration); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public virtual void help_message(ChocolateyConfiguration configuration) + => HelpMessage(configuration); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public virtual void noop(ChocolateyConfiguration configuration) + => DryRun(configuration); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public virtual void run(ChocolateyConfiguration configuration) + => Run(configuration); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public virtual bool may_require_admin_access() + => MayRequireAdminAccess(); +#pragma warning restore IDE1006 } } diff --git a/src/chocolatey/infrastructure.app/commands/ChocolateyPushCommand.cs b/src/chocolatey/infrastructure.app/commands/ChocolateyPushCommand.cs index 22cab401a5..94c426baab 100644 --- a/src/chocolatey/infrastructure.app/commands/ChocolateyPushCommand.cs +++ b/src/chocolatey/infrastructure.app/commands/ChocolateyPushCommand.cs @@ -38,17 +38,17 @@ public ChocolateyPushCommand(IChocolateyPackageService packageService, IChocolat _configSettingsService = configSettingsService; } - public virtual void configure_argument_parser(OptionSet optionSet, ChocolateyConfiguration configuration) + public virtual void ConfigureArgumentParser(OptionSet optionSet, ChocolateyConfiguration configuration) { configuration.Sources = null; optionSet .Add("s=|source=", - "Source - The source we are pushing the package to. Use {0} to push to community feed.".format_with(ApplicationParameters.ChocolateyCommunityFeedPushSource), - option => configuration.Sources = option.remove_surrounding_quotes()) + "Source - The source we are pushing the package to. Use {0} to push to community feed.".FormatWith(ApplicationParameters.ChocolateyCommunityFeedPushSource), + option => configuration.Sources = option.UnquoteSafe()) .Add("k=|key=|apikey=|api-key=", "ApiKey - The API key for the source. If not specified (and not local file source), does a lookup. If not specified and one is not found for an https source, push will fail.", - option => configuration.PushCommand.Key = option.remove_surrounding_quotes()) + option => configuration.PushCommand.Key = option.UnquoteSafe()) //.Add("b|disablebuffering|disable-buffering", // "DisableBuffering - Disable buffering when pushing to an HTTP(S) server to decrease memory usage. Note that when this option is enabled, integrated windows authentication might not work.", // option => configuration.PushCommand.DisableBuffering = option) @@ -56,10 +56,13 @@ public virtual void configure_argument_parser(OptionSet optionSet, ChocolateyCon //todo: #2569 push command - allow disable buffering? } - public virtual void handle_additional_argument_parsing(IList unparsedArguments, ChocolateyConfiguration configuration) + public virtual void ParseAdditionalArguments(IList unparsedArguments, ChocolateyConfiguration configuration) { configuration.Input = string.Join(" ", unparsedArguments); // path to .nupkg - assume relative + } + public virtual void Validate(ChocolateyConfiguration configuration) + { if (string.IsNullOrWhiteSpace(configuration.Sources)) { if (!string.IsNullOrWhiteSpace(configuration.PushCommand.DefaultSource)) @@ -68,52 +71,30 @@ public virtual void handle_additional_argument_parsing(IList unparsedArg } else { - throw new ApplicationException("Default push source configuration is not set. Please pass a source to push to, such as --source={0}".format_with(ApplicationParameters.ChocolateyCommunityFeedPushSource)); + throw new ApplicationException("Default push source configuration is not set. Please pass a source to push to, such as --source={0}".FormatWith(ApplicationParameters.ChocolateyCommunityFeedPushSource)); } } - if (!string.IsNullOrWhiteSpace(configuration.Sources)) - { - IEnumerable sources = configuration.Sources.Split(new[] { ";", "," }, StringSplitOptions.RemoveEmptyEntries); + IEnumerable sources = configuration.Sources.Split(new[] { ";", "," }, StringSplitOptions.RemoveEmptyEntries); - if (sources.Count() > 1) - { - throw new ApplicationException("Multiple sources are not support by push command."); - } - - var machineSource = configuration.MachineSources.FirstOrDefault(m => m.Name.is_equal_to(configuration.Sources)); - if (machineSource != null) - { - "chocolatey".Log().Debug("Switching source name {0} to actual source value '{1}'.".format_with(configuration.Sources, machineSource.Key.to_string())); - - configuration.Sources = machineSource.Key; - } - - var remoteSource = new Uri(configuration.Sources); - if (string.IsNullOrWhiteSpace(configuration.PushCommand.Key) && !remoteSource.IsUnc && !remoteSource.IsFile) - { - // perform a lookup - configuration.PushCommand.Key = _configSettingsService.get_api_key(configuration, null); - } - } - } - - public virtual void handle_validation(ChocolateyConfiguration configuration) - { - if (string.IsNullOrWhiteSpace(configuration.Sources)) + if (sources.Count() > 1) { - throw new ApplicationException("Source is required. Please pass a source to push to, such as --source={0}".format_with(ApplicationParameters.ChocolateyCommunityFeedPushSource)); + throw new ApplicationException("Multiple sources are not supported by push command."); } var remoteSource = new Uri(configuration.Sources); - if (string.IsNullOrWhiteSpace(configuration.PushCommand.Key) && !remoteSource.IsUnc && !remoteSource.IsFile) { - throw new ApplicationException("An API key was not found for '{0}'. You must either set an API key with the apikey command or specify one with --api-key.".format_with(configuration.Sources)); + // perform a lookup + configuration.PushCommand.Key = _configSettingsService.GetApiKey(configuration, null); + if (string.IsNullOrWhiteSpace(configuration.PushCommand.Key)) + { + throw new ApplicationException("An API key was not found for '{0}'. You must either set an API key with the apikey command or specify one with --api-key.".FormatWith(configuration.Sources)); + } } // security advisory - if (!configuration.Force || configuration.Sources.to_lower().Contains("chocolatey.org")) + if (!configuration.Force || configuration.Sources.ToLowerSafe().Contains("chocolatey.org")) { if (remoteSource.Scheme == "http" && remoteSource.Host != "localhost") { @@ -126,28 +107,23 @@ hackers. Please update your source to a more secure source and try again. accessing an internal feed. If you are however doing this against an internet feed, then the choco gods think you are crazy. ;-) -NOTE: For chocolatey.org, you must update the source to be secure.".format_with(configuration.Sources); +NOTE: For chocolatey.org, you must update the source to be secure.".FormatWith(configuration.Sources); throw new ApplicationException(errorMessage); } } } - public virtual void help_message(ChocolateyConfiguration configuration) + public virtual void HelpMessage(ChocolateyConfiguration configuration) { this.Log().Info(ChocolateyLoggers.Important, "Push Command"); this.Log().Info(@" Chocolatey will attempt to push a compiled nupkg to a package feed. -NOTE: 100% compatible with older chocolatey client (0.9.8.32 and below) - with options and switches. In most cases you can still pass options and - switches with one dash (`-`). For more details, see - the command reference (`choco -?`). - A feed can be a local folder, a file share, the community feed ({0}), or a custom/private feed. For web feeds, it has a requirement that it implements the proper OData endpoints required for NuGet packages. -".format_with(ApplicationParameters.ChocolateyCommunityFeedPushSource)); +".FormatWith(ApplicationParameters.ChocolateyCommunityFeedPushSource)); "chocolatey".Log().Info(ChocolateyLoggers.Important, "Usage"); "chocolatey".Log().Info(@" @@ -166,7 +142,7 @@ choco push --source ""'{0}'"" --execution-timeout 500 NOTE: See scripting in the command reference (`choco -?`) for how to write proper scripts and integrations. -".format_with(ApplicationParameters.ChocolateyCommunityFeedPushSource)); +".FormatWith(ApplicationParameters.ChocolateyCommunityFeedPushSource)); "chocolatey".Log().Info(ChocolateyLoggers.Important, "Troubleshooting"); "chocolatey".Log().Info(() => @" @@ -184,7 +160,7 @@ exists with a different user (API key). The package could be unlisted. You can verify by going to {0}packages/packageName. Please contact the administrators of {0} if you see this and you don't see a good reason for it. -".format_with(ApplicationParameters.ChocolateyCommunityGalleryUrl)); +".FormatWith(ApplicationParameters.ChocolateyCommunityGalleryUrl)); "chocolatey".Log().Info(ChocolateyLoggers.Important, "Exit Codes"); "chocolatey".Log().Info(@" @@ -203,19 +179,49 @@ file a ticket so we can document it at "chocolatey".Log().Info(ChocolateyLoggers.Important, "Options and Switches"); } - public virtual void noop(ChocolateyConfiguration configuration) + public virtual void DryRun(ChocolateyConfiguration configuration) { - _packageService.push_noop(configuration); + _packageService.PushDryRun(configuration); } - public virtual void run(ChocolateyConfiguration configuration) + public virtual void Run(ChocolateyConfiguration configuration) { - _packageService.push_run(configuration); + _packageService.Push(configuration); } - public virtual bool may_require_admin_access() + public virtual bool MayRequireAdminAccess() { return false; } + +#pragma warning disable IDE1006 + [Obsolete("This overload is deprecated and will be removed in v3.")] + public virtual void configure_argument_parser(OptionSet optionSet, ChocolateyConfiguration configuration) + => ConfigureArgumentParser(optionSet, configuration); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public virtual void handle_additional_argument_parsing(IList unparsedArguments, ChocolateyConfiguration configuration) + => ParseAdditionalArguments(unparsedArguments, configuration); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public virtual void handle_validation(ChocolateyConfiguration configuration) + => Validate(configuration); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public virtual void help_message(ChocolateyConfiguration configuration) + => HelpMessage(configuration); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public virtual void noop(ChocolateyConfiguration configuration) + => DryRun(configuration); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public virtual void run(ChocolateyConfiguration configuration) + => Run(configuration); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public virtual bool may_require_admin_access() + => MayRequireAdminAccess(); +#pragma warning restore IDE1006 } } diff --git a/src/chocolatey/infrastructure.app/commands/ChocolateySearchCommand.cs b/src/chocolatey/infrastructure.app/commands/ChocolateySearchCommand.cs index caa6cd8d61..417bd41ef0 100644 --- a/src/chocolatey/infrastructure.app/commands/ChocolateySearchCommand.cs +++ b/src/chocolatey/infrastructure.app/commands/ChocolateySearchCommand.cs @@ -38,14 +38,14 @@ public ChocolateySearchCommand(IChocolateyPackageService packageService) _packageService = packageService; } - public virtual void configure_argument_parser(OptionSet optionSet, ChocolateyConfiguration configuration) + public virtual void ConfigureArgumentParser(OptionSet optionSet, ChocolateyConfiguration configuration) { optionSet .Add("s=|source=", "Source - Source location for install. Can use special 'windowsfeatures', 'ruby', 'cygwin', or 'python' sources. Defaults to sources.", - option => configuration.Sources = option.remove_surrounding_quotes()) + option => configuration.Sources = option.UnquoteSafe()) .Add("idonly|id-only", - "Id Only - Only return Package Ids in the list results. Available in 0.10.6+.", + "Id Only - Only return Package Ids in the list results.", option => configuration.ListCommand.IdOnly = option != null) .Add("pre|prerelease", "Prerelease - Include Prereleases? Defaults to false.", @@ -58,21 +58,21 @@ public virtual void configure_argument_parser(OptionSet optionSet, ChocolateyCon option => configuration.AllVersions = option != null) .Add("version=", "Version - Specific version of a package to return.", - option => configuration.Version = option.remove_surrounding_quotes()) + option => configuration.Version = option.UnquoteSafe()) .Add("u=|user=", "User - used with authenticated feeds. Defaults to empty.", - option => configuration.SourceCommand.Username = option.remove_surrounding_quotes()) + option => configuration.SourceCommand.Username = option.UnquoteSafe()) .Add("p=|password=", "Password - the user's password to the source. Defaults to empty.", - option => configuration.SourceCommand.Password = option.remove_surrounding_quotes()) + option => configuration.SourceCommand.Password = option.UnquoteSafe()) .Add("cert=", - "Client certificate - PFX pathname for an x509 authenticated feeds. Defaults to empty. Available in 0.9.10+.", - option => configuration.SourceCommand.Certificate = option.remove_surrounding_quotes()) + "Client certificate - PFX pathname for an x509 authenticated feeds. Defaults to empty.", + option => configuration.SourceCommand.Certificate = option.UnquoteSafe()) .Add("cp=|certpassword=", - "Certificate Password - the client certificate's password to the source. Defaults to empty. Available in 0.9.10+.", - option => configuration.SourceCommand.CertificatePassword = option.remove_surrounding_quotes()) + "Certificate Password - the client certificate's password to the source. Defaults to empty.", + option => configuration.SourceCommand.CertificatePassword = option.UnquoteSafe()) .Add("page=", - "Page - the 'page' of results to return. Defaults to return all results. Available in 0.9.10+.", + "Page - the 'page' of results to return. Defaults to return all results.", option => { int page; @@ -86,42 +86,42 @@ public virtual void configure_argument_parser(OptionSet optionSet, ChocolateyCon } }) .Add("page-size=", - "Page Size - the amount of package results to return per page. Defaults to 25. Available in 0.9.10+.", + "Page Size - the amount of packages to return in each page of results. NOTE: this value is per source. Defaults to 25 for each source that is included in query.", option => { configuration.ListCommand.PageSize = int.Parse(option); configuration.ListCommand.ExplicitPageSize = true; }) .Add("e|exact", - "Exact - Only return packages with this exact name. Available in 0.9.10+.", + "Exact - Only return packages with this exact name.", option => configuration.ListCommand.Exact = option != null) .Add("by-id-only", - "ByIdOnly - Only return packages where the id contains the search filter. Available in 0.9.10+.", + "ByIdOnly - Only return packages where the id contains the search filter.", option => configuration.ListCommand.ByIdOnly = option != null) .Add("by-tag-only|by-tags-only", - "ByTagOnly - Only return packages where the search filter matches on the tags. Available in 0.10.6+.", + "ByTagOnly - Only return packages where the search filter matches on the tags.", option => configuration.ListCommand.ByTagOnly = option != null) .Add("id-starts-with", - "IdStartsWith - Only return packages where the id starts with the search filter. Available in 0.9.10+.", + "IdStartsWith - Only return packages where the id starts with the search filter.", option => configuration.ListCommand.IdStartsWith = option != null) .Add("order-by-popularity", - "OrderByPopularity - Sort by package results by popularity. Available in 0.9.10+.", + "OrderByPopularity - Sort by package results by popularity.", option => configuration.ListCommand.OrderByPopularity = option != null) .Add("approved-only", - "ApprovedOnly - Only return approved packages - this option will filter out results not from the community repository. Available in 0.9.10+.", + "ApprovedOnly - Only return approved packages - this option will filter out results not from the community repository.", option => configuration.ListCommand.ApprovedOnly = option != null) .Add("download-cache|download-cache-only", - "DownloadCacheAvailable - Only return packages that have a download cache available - this option will filter out results not from the community repository. Available in 0.9.10+.", + "DownloadCacheAvailable - Only return packages that have a download cache available - this option will filter out results not from the community repository.", option => configuration.ListCommand.DownloadCacheAvailable = option != null) .Add("not-broken", - "NotBroken - Only return packages that are not failing testing - this option only filters out failing results from the community feed. It will not filter against other sources. Available in 0.9.10+.", + "NotBroken - Only return packages that are not failing testing - this option only filters out failing results from the community feed. It will not filter against other sources.", option => configuration.ListCommand.NotBroken = option != null) .Add("detail|detailed", - "Detailed - Alias for verbose. Available in 0.9.10+.", + "Detailed - Alias for verbose.", option => configuration.Verbose = option != null) .Add("disable-repository-optimizations|disable-package-repository-optimizations", - "Disable Package Repository Optimizations - Do not use optimizations for reducing bandwidth with repository queries during package install/upgrade/outdated operations. Should not generally be used, unless a repository needs to support older methods of query. When disabled, this makes queries similar to the way they were done in Chocolatey v0.10.11 and before. Overrides the default feature '{0}' set to '{1}'. Available in 0.10.14+.".format_with - (ApplicationParameters.Features.UsePackageRepositoryOptimizations, configuration.Features.UsePackageRepositoryOptimizations.to_string()), + "Disable Package Repository Optimizations - Do not use optimizations for reducing bandwidth with repository queries during package install/upgrade/outdated operations. Should not generally be used, unless a repository needs to support older methods of query. When disabled, this makes queries similar to the way they were done in earlier versions of Chocolatey. Overrides the default feature '{0}' set to '{1}'.".FormatWith + (ApplicationParameters.Features.UsePackageRepositoryOptimizations, configuration.Features.UsePackageRepositoryOptimizations.ToStringSafe()), option => { if (option != null) @@ -132,37 +132,32 @@ public virtual void configure_argument_parser(OptionSet optionSet, ChocolateyCon ; } - public virtual void handle_additional_argument_parsing(IList unparsedArguments, ChocolateyConfiguration configuration) + public virtual void ParseAdditionalArguments(IList unparsedArguments, ChocolateyConfiguration configuration) { configuration.Input = string.Join(" ", unparsedArguments); } - public virtual void handle_validation(ChocolateyConfiguration configuration) + public virtual void Validate(ChocolateyConfiguration configuration) { if (!string.IsNullOrWhiteSpace(configuration.SourceCommand.Username) && string.IsNullOrWhiteSpace(configuration.SourceCommand.Password)) { - this.Log().Debug(ChocolateyLoggers.LogFileOnly, "Username '{0}' provided. Asking for password.".format_with(configuration.SourceCommand.Username)); - System.Console.Write("User name '{0}' provided. Password: ".format_with(configuration.SourceCommand.Username)); - configuration.SourceCommand.Password = InteractivePrompt.get_password(configuration.PromptForConfirmation); + this.Log().Debug(ChocolateyLoggers.LogFileOnly, "Username '{0}' provided. Asking for password.".FormatWith(configuration.SourceCommand.Username)); + System.Console.Write("User name '{0}' provided. Password: ".FormatWith(configuration.SourceCommand.Username)); + configuration.SourceCommand.Password = InteractivePrompt.GetPassword(configuration.PromptForConfirmation); } if (configuration.ListCommand.PageSize < 1 || configuration.ListCommand.PageSize > 100) { - var message = "The page size has been specified to be {0:N0} packages. The page size cannot be lower than 1 package, and no larger than 100 packages.".format_with(configuration.ListCommand.PageSize); + var message = "The page size has been specified to be {0:N0} packages. The page size cannot be lower than 1 package, and no larger than 100 packages.".FormatWith(configuration.ListCommand.PageSize); throw new ApplicationException(message); } } - public virtual void help_message(ChocolateyConfiguration configuration) + public virtual void HelpMessage(ChocolateyConfiguration configuration) { this.Log().Info(ChocolateyLoggers.Important, "Search Command"); this.Log().Info(@" Chocolatey will perform a search for a package local or remote. - -NOTE: 100% compatible with older Chocolatey client (0.9.8.x and below) - with options and switches. In most cases you can still pass options - and switches with one dash (`-`). For more details, see - the command reference (`choco -?`). "); "chocolatey".Log().Info(ChocolateyLoggers.Important, "Usage"); @@ -199,36 +194,35 @@ Exit codes that normally result from running this command. - -1 or 1: an error has occurred - 2: no results (enhanced) -NOTE: Starting in v0.10.12, if you have the feature '{0}' - turned on, then choco will provide enhanced exit codes that allow +NOTE: If you have the feature '{0}' turned on, + then choco will provide enhanced exit codes that allow better integration and scripting. If you find other exit codes that we have not yet documented, please file a ticket so we can document it at https://github.com/chocolatey/choco/issues/new/choose. -".format_with(ApplicationParameters.Features.UseEnhancedExitCodes)); +".FormatWith(ApplicationParameters.Features.UseEnhancedExitCodes)); "chocolatey".Log().Info(ChocolateyLoggers.Important, "See It In Action"); "chocolatey".Log().Info(@" choco {0}: https://raw.githubusercontent.com/wiki/chocolatey/choco/images/gifs/choco_search.gif -".format_with(configuration.CommandName)); +".FormatWith(configuration.CommandName)); "chocolatey".Log().Info(ChocolateyLoggers.Important, "Alternative Sources"); "chocolatey".Log().Info(ChocolateyLoggers.Important, "Options and Switches"); } - public virtual void noop(ChocolateyConfiguration configuration) + public virtual void DryRun(ChocolateyConfiguration configuration) { - _packageService.list_noop(configuration); + _packageService.ListDryRun(configuration); } - public virtual void run(ChocolateyConfiguration configuration) + public virtual void Run(ChocolateyConfiguration configuration) { - _packageService.ensure_source_app_installed(configuration); // note: you must leave the .ToList() here or else the method won't be evaluated! - var packageResults = _packageService.list_run(configuration).ToList(); + var packageResults = _packageService.List(configuration).ToList(); // if there are no results, exit with a 2. if (configuration.Features.UseEnhancedExitCodes && packageResults.Count == 0 && Environment.ExitCode == 0) @@ -237,22 +231,60 @@ public virtual void run(ChocolateyConfiguration configuration) } } - public virtual IEnumerable list(ChocolateyConfiguration configuration) + public virtual IEnumerable List(ChocolateyConfiguration configuration) { configuration.QuietOutput = true; // here it's up to the caller to enumerate the results - return _packageService.list_run(configuration); + return _packageService.List(configuration); } - public virtual int count(ChocolateyConfiguration config) + public virtual int Count(ChocolateyConfiguration config) { config.QuietOutput = true; - return _packageService.count_run(config); + return _packageService.Count(config); } - public virtual bool may_require_admin_access() + public virtual bool MayRequireAdminAccess() { return false; } + +#pragma warning disable IDE1006 + [Obsolete("This overload is deprecated and will be removed in v3.")] + public virtual void configure_argument_parser(OptionSet optionSet, ChocolateyConfiguration configuration) + => ConfigureArgumentParser(optionSet, configuration); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public virtual void handle_additional_argument_parsing(IList unparsedArguments, ChocolateyConfiguration configuration) + => ParseAdditionalArguments(unparsedArguments, configuration); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public virtual void handle_validation(ChocolateyConfiguration configuration) + => Validate(configuration); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public virtual void help_message(ChocolateyConfiguration configuration) + => HelpMessage(configuration); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public virtual void noop(ChocolateyConfiguration configuration) + => DryRun(configuration); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public virtual void run(ChocolateyConfiguration configuration) + => Run(configuration); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public virtual bool may_require_admin_access() + => MayRequireAdminAccess(); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public virtual int count(ChocolateyConfiguration config) + => Count(config); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public virtual IEnumerable list(ChocolateyConfiguration config) + => List(config); +#pragma warning restore IDE1006 } } diff --git a/src/chocolatey/infrastructure.app/commands/ChocolateySourceCommand.cs b/src/chocolatey/infrastructure.app/commands/ChocolateySourceCommand.cs index a3e0b817a0..bf78c4ca26 100644 --- a/src/chocolatey/infrastructure.app/commands/ChocolateySourceCommand.cs +++ b/src/chocolatey/infrastructure.app/commands/ChocolateySourceCommand.cs @@ -20,6 +20,7 @@ namespace chocolatey.infrastructure.app.commands using System.Collections.Generic; using System.Linq; using attributes; + using chocolatey.infrastructure.results; using commandline; using configuration; using domain; @@ -39,45 +40,45 @@ public ChocolateySourceCommand(IChocolateyConfigSettingsService configSettingsSe _configSettingsService = configSettingsService; } - public virtual void configure_argument_parser(OptionSet optionSet, ChocolateyConfiguration configuration) + public virtual void ConfigureArgumentParser(OptionSet optionSet, ChocolateyConfiguration configuration) { configuration.Sources = string.Empty; optionSet .Add("n=|name=", "Name - the name of the source. Required with actions other than list. Defaults to empty.", - option => configuration.SourceCommand.Name = option.remove_surrounding_quotes()) + option => configuration.SourceCommand.Name = option.UnquoteSafe()) .Add("s=|source=", "Source - The source. This can be a folder/file share or an http location. If it is a url, it will be a location you can go to in a browser and it returns OData with something that says Packages in the browser, similar to what you see when you go to https://community.chocolatey.org/api/v2/. Required with add action. Defaults to empty.", - option => configuration.Sources = option.remove_surrounding_quotes()) + option => configuration.Sources = option.UnquoteSafe()) .Add("u=|user=", "User - used with authenticated feeds. Defaults to empty.", - option => configuration.SourceCommand.Username = option.remove_surrounding_quotes()) + option => configuration.SourceCommand.Username = option.UnquoteSafe()) .Add("p=|password=", "Password - the user's password to the source. Encrypted in chocolatey.config file.", - option => configuration.SourceCommand.Password = option.remove_surrounding_quotes()) + option => configuration.SourceCommand.Password = option.UnquoteSafe()) .Add("cert=", - "Client certificate - PFX pathname for an x509 authenticated feeds. Defaults to empty. Available in 0.9.10+.", - option => configuration.SourceCommand.Certificate = option.remove_surrounding_quotes()) + "Client certificate - PFX pathname for an x509 authenticated feeds. Defaults to empty.", + option => configuration.SourceCommand.Certificate = option.UnquoteSafe()) .Add("cp=|certpassword=", - "Certificate Password - the client certificate's password to the source. Defaults to empty. Available in 0.9.10+.", - option => configuration.SourceCommand.CertificatePassword = option.remove_surrounding_quotes()) + "Certificate Password - the client certificate's password to the source. Defaults to empty.", + option => configuration.SourceCommand.CertificatePassword = option.UnquoteSafe()) .Add("priority=", - "Priority - The priority order of this source as compared to other sources, lower is better. Defaults to 0 (no priority). All priorities above 0 will be evaluated first, then zero-based values will be evaluated in config file order. Available in 0.9.9.9+.", - option => configuration.SourceCommand.Priority = int.Parse(option.remove_surrounding_quotes())) + "Priority - The priority order of this source as compared to other sources, lower is better. Defaults to 0 (no priority). All priorities above 0 will be evaluated first, then zero-based values will be evaluated in config file order.", + option => configuration.SourceCommand.Priority = int.Parse(option.UnquoteSafe())) .Add("bypassproxy|bypass-proxy", - "Bypass Proxy - Should this source explicitly bypass any explicitly or system configured proxies? Defaults to false. Available in 0.10.4+.", + "Bypass Proxy - Should this source explicitly bypass any explicitly or system configured proxies? Defaults to false.", option => configuration.SourceCommand.BypassProxy = option != null) .Add("allowselfservice|allow-self-service", - "Allow Self-Service - Should this source be allowed to be used with self-service? Requires business edition (v1.10.0+) with feature 'useBackgroundServiceWithSelfServiceSourcesOnly' turned on. Defaults to false. Available in 0.10.4+.", + "Allow Self-Service - Should this source be allowed to be used with self-service? Requires business edition (v1.10.0+) with feature 'useBackgroundServiceWithSelfServiceSourcesOnly' turned on. Defaults to false.", option => configuration.SourceCommand.AllowSelfService = option != null) .Add("adminonly|admin-only", - "Visible to Administrators Only - Should this source be visible to non-administrators? Requires business edition (v1.12.2+). Defaults to false. Available in 0.10.8+.", + "Visible to Administrators Only - Should this source be visible to non-administrators? Requires business edition (v1.12.2+). Defaults to false.", option => configuration.SourceCommand.VisibleToAdminsOnly = option != null) ; } - public virtual void handle_additional_argument_parsing(IList unparsedArguments, ChocolateyConfiguration configuration) + public virtual void ParseAdditionalArguments(IList unparsedArguments, ChocolateyConfiguration configuration) { configuration.Input = string.Join(" ", unparsedArguments); @@ -86,49 +87,43 @@ public virtual void handle_additional_argument_parsing(IList unparsedArg throw new ApplicationException("A single sources command must be listed. Please see the help menu for those commands"); } - var command = SourceCommandType.unknown; + var command = SourceCommandType.Unknown; string unparsedCommand = unparsedArguments.DefaultIfEmpty(string.Empty).FirstOrDefault(); Enum.TryParse(unparsedCommand, true, out command); - if (command == SourceCommandType.unknown) + if (command == SourceCommandType.Unknown) { - if (!string.IsNullOrWhiteSpace(unparsedCommand)) this.Log().Warn("Unknown command {0}. Setting to list.".format_with(unparsedCommand)); - command = SourceCommandType.list; + if (!string.IsNullOrWhiteSpace(unparsedCommand)) this.Log().Warn("Unknown command {0}. Setting to list.".FormatWith(unparsedCommand)); + command = SourceCommandType.List; } configuration.SourceCommand.Command = command; } - public virtual void handle_validation(ChocolateyConfiguration configuration) + public virtual void Validate(ChocolateyConfiguration configuration) { - if (configuration.SourceCommand.Command != SourceCommandType.list && string.IsNullOrWhiteSpace(configuration.SourceCommand.Name)) + if (configuration.SourceCommand.Command != SourceCommandType.List && string.IsNullOrWhiteSpace(configuration.SourceCommand.Name)) { - throw new ApplicationException("When specifying the subcommand '{0}', you must also specify --name.".format_with(configuration.SourceCommand.Command.to_string())); + throw new ApplicationException("When specifying the subcommand '{0}', you must also specify --name.".FormatWith(configuration.SourceCommand.Command.ToStringSafe().ToLower())); } - if (configuration.SourceCommand.Command == SourceCommandType.add && string.IsNullOrWhiteSpace(configuration.Sources)) + if (configuration.SourceCommand.Command == SourceCommandType.Add && string.IsNullOrWhiteSpace(configuration.Sources)) { - throw new ApplicationException("When specifying the subcommand 'add', you must also specify --source.".format_with(configuration.SourceCommand.Command.to_string())); + throw new ApplicationException("When specifying the subcommand 'add', you must also specify --source."); } if (!string.IsNullOrWhiteSpace(configuration.SourceCommand.Username) && string.IsNullOrWhiteSpace(configuration.SourceCommand.Password)) { - this.Log().Debug(ChocolateyLoggers.LogFileOnly, "Username '{0}' provided. Asking for password.".format_with(configuration.SourceCommand.Username)); - System.Console.Write("User name '{0}' provided. Password: ".format_with(configuration.SourceCommand.Username)); - configuration.SourceCommand.Password = InteractivePrompt.get_password(configuration.PromptForConfirmation); + this.Log().Debug(ChocolateyLoggers.LogFileOnly, "Username '{0}' provided. Asking for password.".FormatWith(configuration.SourceCommand.Username)); + System.Console.Write("User name '{0}' provided. Password: ".FormatWith(configuration.SourceCommand.Username)); + configuration.SourceCommand.Password = InteractivePrompt.GetPassword(configuration.PromptForConfirmation); } } - public virtual void help_message(ChocolateyConfiguration configuration) + public virtual void HelpMessage(ChocolateyConfiguration configuration) { this.Log().Info(ChocolateyLoggers.Important, "Source Command"); this.Log().Info(@" Chocolatey will allow you to interact with sources. - -NOTE: Mostly compatible with older chocolatey client (0.9.8.x and - below) with options and switches. When enabling, disabling or removing - a source, use `-name` in front of the option now. In most cases you - can still pass options and switches with one dash (`-`). For more - details, see the command reference (`choco -?`). "); "chocolatey".Log().Info(ChocolateyLoggers.Important, "Usage"); @@ -175,49 +170,87 @@ file a ticket so we can document it at "chocolatey".Log().Info(ChocolateyLoggers.Important, "Options and Switches"); } - public virtual void noop(ChocolateyConfiguration configuration) + public virtual void DryRun(ChocolateyConfiguration configuration) { - _configSettingsService.noop(configuration); + _configSettingsService.DryRun(configuration); } - public virtual void run(ChocolateyConfiguration configuration) + public virtual void Run(ChocolateyConfiguration configuration) { switch (configuration.SourceCommand.Command) { - case SourceCommandType.list: - _configSettingsService.source_list(configuration); + case SourceCommandType.List: + _configSettingsService.ListSources(configuration); break; - case SourceCommandType.add: - _configSettingsService.source_add(configuration); + case SourceCommandType.Add: + _configSettingsService.AddSource(configuration); break; - case SourceCommandType.remove: - _configSettingsService.source_remove(configuration); + case SourceCommandType.Remove: + _configSettingsService.RemoveSource(configuration); break; - case SourceCommandType.disable: - _configSettingsService.source_disable(configuration); + case SourceCommandType.Disable: + _configSettingsService.DisableSource(configuration); break; - case SourceCommandType.enable: - _configSettingsService.source_enable(configuration); + case SourceCommandType.Enable: + _configSettingsService.EnableSource(configuration); break; } } - public virtual IEnumerable list(ChocolateyConfiguration configuration) + public virtual IEnumerable List(ChocolateyConfiguration configuration) { - return _configSettingsService.source_list(configuration); + return _configSettingsService.ListSources(configuration); } - public virtual int count(ChocolateyConfiguration config) + public virtual int Count(ChocolateyConfiguration config) { - return list(config).Count(); + return List(config).Count(); } - public virtual bool may_require_admin_access() + public virtual bool MayRequireAdminAccess() { - var config = Config.get_configuration_settings(); + var config = Config.GetConfigurationSettings(); if (config == null) return true; - return config.SourceCommand.Command != SourceCommandType.list; + return config.SourceCommand.Command != SourceCommandType.List; } + +#pragma warning disable IDE1006 + [Obsolete("This overload is deprecated and will be removed in v3.")] + public virtual void configure_argument_parser(OptionSet optionSet, ChocolateyConfiguration configuration) + => ConfigureArgumentParser(optionSet, configuration); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public virtual void handle_additional_argument_parsing(IList unparsedArguments, ChocolateyConfiguration configuration) + => ParseAdditionalArguments(unparsedArguments, configuration); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public virtual void handle_validation(ChocolateyConfiguration configuration) + => Validate(configuration); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public virtual void help_message(ChocolateyConfiguration configuration) + => HelpMessage(configuration); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public virtual void noop(ChocolateyConfiguration configuration) + => DryRun(configuration); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public virtual void run(ChocolateyConfiguration configuration) + => Run(configuration); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public virtual bool may_require_admin_access() + => MayRequireAdminAccess(); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public virtual int count(ChocolateyConfiguration config) + => Count(config); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public virtual IEnumerable list(ChocolateyConfiguration config) + => List(config); +#pragma warning restore IDE1006 } } diff --git a/src/chocolatey/infrastructure.app/commands/ChocolateyTemplateCommand.cs b/src/chocolatey/infrastructure.app/commands/ChocolateyTemplateCommand.cs index 0aa3db98a0..ee8fa0aac1 100644 --- a/src/chocolatey/infrastructure.app/commands/ChocolateyTemplateCommand.cs +++ b/src/chocolatey/infrastructure.app/commands/ChocolateyTemplateCommand.cs @@ -20,6 +20,7 @@ namespace chocolatey.infrastructure.app.commands using System.Collections.Generic; using System.Linq; using attributes; + using chocolatey.infrastructure.results; using commandline; using configuration; using domain; @@ -39,16 +40,16 @@ public ChocolateyTemplateCommand(ITemplateService templateService) _templateService = templateService; } - public void configure_argument_parser(OptionSet optionSet, ChocolateyConfiguration configuration) + public void ConfigureArgumentParser(OptionSet optionSet, ChocolateyConfiguration configuration) { optionSet .Add("n=|name=", "The name of the template to get information about.", - option => configuration.TemplateCommand.Name = option.remove_surrounding_quotes().ToLower()); + option => configuration.TemplateCommand.Name = option.UnquoteSafe().ToLower()); // todo: #2570 Allow for templates from an external path? Requires #1477 } - public virtual void handle_additional_argument_parsing(IList unparsedArguments, ChocolateyConfiguration configuration) + public virtual void ParseAdditionalArguments(IList unparsedArguments, ChocolateyConfiguration configuration) { // don't set configuration.Input or it will be passed to list @@ -57,38 +58,35 @@ public virtual void handle_additional_argument_parsing(IList unparsedArg throw new ApplicationException("A single template command must be listed. Please see the help menu for those commands"); } - var command = TemplateCommandType.unknown; + var command = TemplateCommandType.Unknown; string unparsedCommand = unparsedArguments.DefaultIfEmpty(string.Empty).FirstOrDefault(); Enum.TryParse(unparsedCommand, true, out command); - if (command == TemplateCommandType.unknown) + if (command == TemplateCommandType.Unknown) { - if (!string.IsNullOrWhiteSpace(unparsedCommand)) this.Log().Warn("Unknown command {0}. Setting to list.".format_with(unparsedCommand)); - command = TemplateCommandType.list; + if (!string.IsNullOrWhiteSpace(unparsedCommand)) this.Log().Warn("Unknown command {0}. Setting to list.".FormatWith(unparsedCommand)); + command = TemplateCommandType.List; } configuration.TemplateCommand.Command = command; } - public virtual void handle_validation(ChocolateyConfiguration configuration) + public virtual void Validate(ChocolateyConfiguration configuration) { - if (configuration.TemplateCommand.Command != TemplateCommandType.list && string.IsNullOrWhiteSpace(configuration.TemplateCommand.Name)) + if (configuration.TemplateCommand.Command != TemplateCommandType.List && string.IsNullOrWhiteSpace(configuration.TemplateCommand.Name)) { - throw new ApplicationException("When specifying the subcommand '{0}', you must also specify --name.".format_with(configuration.TemplateCommand.Command.to_string())); + throw new ApplicationException("When specifying the subcommand '{0}', you must also specify --name.".FormatWith(configuration.TemplateCommand.Command.ToStringSafe().ToLower())); } } - public virtual void help_message(ChocolateyConfiguration configuration) + public virtual void HelpMessage(ChocolateyConfiguration configuration) { "chocolatey".Log().Info(ChocolateyLoggers.Important, "Template Command"); "chocolatey".Log().Info(@" List information installed templates. Both manually installed templates and templates installed via - .template packages are displayed. - -NOTE: Available with 0.12.0+." -); + .template packages are displayed."); "chocolatey".Log().Info(ChocolateyLoggers.Important, "Usage"); "chocolatey".Log().Info(@" @@ -125,36 +123,66 @@ file a ticket so we can document it at "chocolatey".Log().Info(ChocolateyLoggers.Important, "Options and Switches"); } - public virtual void noop(ChocolateyConfiguration configuration) + public virtual void DryRun(ChocolateyConfiguration configuration) { switch (configuration.TemplateCommand.Command) { - case TemplateCommandType.list: - _templateService.list_noop(configuration); + case TemplateCommandType.List: + _templateService.ListDryRun(configuration); break; - case TemplateCommandType.info: - _templateService.list_noop(configuration); + case TemplateCommandType.Info: + _templateService.ListDryRun(configuration); break; } } - public virtual void run(ChocolateyConfiguration configuration) + public virtual void Run(ChocolateyConfiguration configuration) { switch (configuration.TemplateCommand.Command) { - case TemplateCommandType.list: - _templateService.list(configuration); + case TemplateCommandType.List: + _templateService.List(configuration); break; - case TemplateCommandType.info: + case TemplateCommandType.Info: configuration.Verbose = true; - _templateService.list(configuration); + _templateService.List(configuration); break; } } - public virtual bool may_require_admin_access() + public virtual bool MayRequireAdminAccess() { return false; } + +#pragma warning disable IDE1006 + [Obsolete("This overload is deprecated and will be removed in v3.")] + public virtual void configure_argument_parser(OptionSet optionSet, ChocolateyConfiguration configuration) + => ConfigureArgumentParser(optionSet, configuration); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public virtual void handle_additional_argument_parsing(IList unparsedArguments, ChocolateyConfiguration configuration) + => ParseAdditionalArguments(unparsedArguments, configuration); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public virtual void handle_validation(ChocolateyConfiguration configuration) + => Validate(configuration); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public virtual void help_message(ChocolateyConfiguration configuration) + => HelpMessage(configuration); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public virtual void noop(ChocolateyConfiguration configuration) + => DryRun(configuration); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public virtual void run(ChocolateyConfiguration configuration) + => Run(configuration); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public virtual bool may_require_admin_access() + => MayRequireAdminAccess(); +#pragma warning restore IDE1006 } } diff --git a/src/chocolatey/infrastructure.app/commands/ChocolateyUninstallCommand.cs b/src/chocolatey/infrastructure.app/commands/ChocolateyUninstallCommand.cs index 9938b7f282..44bb8c5c55 100644 --- a/src/chocolatey/infrastructure.app/commands/ChocolateyUninstallCommand.cs +++ b/src/chocolatey/infrastructure.app/commands/ChocolateyUninstallCommand.cs @@ -48,21 +48,21 @@ public ChocolateyUninstallCommand(IChocolateyPackageService packageService) _packageService = packageService; } - public virtual void configure_argument_parser(OptionSet optionSet, ChocolateyConfiguration configuration) + public virtual void ConfigureArgumentParser(OptionSet optionSet, ChocolateyConfiguration configuration) { optionSet .Add("s=|source=", "Source - The source to find the package(s) to install. Special sources include: ruby, cygwin, windowsfeatures, and python. Defaults to default feeds.", - option => configuration.Sources = option.remove_surrounding_quotes()) + option => configuration.Sources = option.UnquoteSafe()) .Add("version=", "Version - A specific version to uninstall. Defaults to unspecified.", - option => configuration.Version = option.remove_surrounding_quotes()) + option => configuration.Version = option.UnquoteSafe()) .Add("a|allversions|all-versions", "AllVersions - Uninstall all versions? Defaults to false.", option => configuration.AllVersions = option != null) .Add("ua=|uninstallargs=|uninstallarguments=|uninstall-arguments=", "UninstallArguments - Uninstall Arguments to pass to the native installer in the package. Defaults to unspecified.", - option => configuration.InstallArguments = option.remove_surrounding_quotes()) + option => configuration.InstallArguments = option.UnquoteSafe()) .Add("o|override|overrideargs|overridearguments|override-arguments", "OverrideArguments - Should uninstall arguments be used exclusively without appending to current package passed arguments? Defaults to false.", option => configuration.OverrideArguments = option != null) @@ -71,7 +71,7 @@ public virtual void configure_argument_parser(OptionSet optionSet, ChocolateyCon option => configuration.NotSilent = option != null) .Add("params=|parameters=|pkgparameters=|packageparameters=|package-parameters=", "PackageParameters - Parameters to pass to the package. Defaults to unspecified.", - option => configuration.PackageParameters = option.remove_surrounding_quotes()) + option => configuration.PackageParameters = option.UnquoteSafe()) .Add("argsglobal|args-global|installargsglobal|install-args-global|applyargstodependencies|apply-args-to-dependencies|apply-install-arguments-to-dependencies", "Apply Install Arguments To Dependencies - Should install arguments be applied to dependent packages? Defaults to false.", option => configuration.ApplyInstallArgumentsToDependencies = option != null) @@ -85,7 +85,7 @@ public virtual void configure_argument_parser(OptionSet optionSet, ChocolateyCon "Skip PowerShell - Do not run chocolateyUninstall.ps1. Defaults to false.", option => configuration.SkipPackageInstallProvider = option != null) .Add("ignorepackagecodes|ignorepackageexitcodes|ignore-package-codes|ignore-package-exit-codes", - "IgnorePackageExitCodes - Exit with a 0 for success and 1 for non-success, no matter what package scripts provide for exit codes. Overrides the default feature '{0}' set to '{1}'. Available in 0.9.10+.".format_with(ApplicationParameters.Features.UsePackageExitCodes, configuration.Features.UsePackageExitCodes.to_string()), + "IgnorePackageExitCodes - Exit with a 0 for success and 1 for non-success, no matter what package scripts provide for exit codes. Overrides the default feature '{0}' set to '{1}'.".FormatWith(ApplicationParameters.Features.UsePackageExitCodes, configuration.Features.UsePackageExitCodes.ToStringSafe()), option => { if (option != null) @@ -94,15 +94,15 @@ public virtual void configure_argument_parser(OptionSet optionSet, ChocolateyCon } }) .Add("usepackagecodes|usepackageexitcodes|use-package-codes|use-package-exit-codes", - "UsePackageExitCodes - Package scripts can provide exit codes. Use those for choco's exit code when non-zero (this value can come from a dependency package). Chocolatey defines valid exit codes as 0, 1605, 1614, 1641, 3010. Overrides the default feature '{0}' set to '{1}'. Available in 0.9.10+.".format_with(ApplicationParameters.Features.UsePackageExitCodes, configuration.Features.UsePackageExitCodes.to_string()), + "UsePackageExitCodes - Package scripts can provide exit codes. Use those for choco's exit code when non-zero (this value can come from a dependency package). Chocolatey defines valid exit codes as 0, 1605, 1614, 1641, 3010. Overrides the default feature '{0}' set to '{1}'.".FormatWith(ApplicationParameters.Features.UsePackageExitCodes, configuration.Features.UsePackageExitCodes.ToStringSafe()), option => configuration.Features.UsePackageExitCodes = option != null ) .Add("autouninstaller|use-autouninstaller", - "UseAutoUninstaller - Use auto uninstaller service when uninstalling. Overrides the default feature '{0}' set to '{1}'. Available in 0.9.10+.".format_with(ApplicationParameters.Features.AutoUninstaller, configuration.Features.AutoUninstaller.to_string()), + "UseAutoUninstaller - Use auto uninstaller service when uninstalling. Overrides the default feature '{0}' set to '{1}'.".FormatWith(ApplicationParameters.Features.AutoUninstaller, configuration.Features.AutoUninstaller.ToStringSafe()), option => configuration.Features.AutoUninstaller = option != null ) .Add("skipautouninstaller|skip-autouninstaller", - "SkipAutoUninstaller - Skip auto uninstaller service when uninstalling. Overrides the default feature '{0}' set to '{1}'. Available in 0.9.10+.".format_with(ApplicationParameters.Features.AutoUninstaller, configuration.Features.AutoUninstaller.to_string()), + "SkipAutoUninstaller - Skip auto uninstaller service when uninstalling. Overrides the default feature '{0}' set to '{1}'.".FormatWith(ApplicationParameters.Features.AutoUninstaller, configuration.Features.AutoUninstaller.ToStringSafe()), option => { if (option != null) @@ -111,11 +111,11 @@ public virtual void configure_argument_parser(OptionSet optionSet, ChocolateyCon } }) .Add("failonautouninstaller|fail-on-autouninstaller", - "FailOnAutoUninstaller - Fail the package uninstall if the auto uninstaller reports and error. Overrides the default feature '{0}' set to '{1}'. Available in 0.9.10+.".format_with(ApplicationParameters.Features.FailOnAutoUninstaller, configuration.Features.FailOnAutoUninstaller.to_string()), + "FailOnAutoUninstaller - Fail the package uninstall if the auto uninstaller reports and error. Overrides the default feature '{0}' set to '{1}'.".FormatWith(ApplicationParameters.Features.FailOnAutoUninstaller, configuration.Features.FailOnAutoUninstaller.ToStringSafe()), option => configuration.Features.FailOnAutoUninstaller = option != null ) .Add("ignoreautouninstallerfailure|ignore-autouninstaller-failure", - "Ignore Auto Uninstaller Failure - Do not fail the package if auto uninstaller reports an error. Overrides the default feature '{0}' set to '{1}'. Available in 0.9.10+.".format_with(ApplicationParameters.Features.FailOnAutoUninstaller, configuration.Features.FailOnAutoUninstaller.to_string()), + "Ignore Auto Uninstaller Failure - Do not fail the package if auto uninstaller reports an error. Overrides the default feature '{0}' set to '{1}'.".FormatWith(ApplicationParameters.Features.FailOnAutoUninstaller, configuration.Features.FailOnAutoUninstaller.ToStringSafe()), option => { if (option != null) @@ -124,17 +124,17 @@ public virtual void configure_argument_parser(OptionSet optionSet, ChocolateyCon } }) .Add("stoponfirstfailure|stop-on-first-failure|stop-on-first-package-failure", - "Stop On First Package Failure - stop running install, upgrade or uninstall on first package failure instead of continuing with others. Overrides the default feature '{0}' set to '{1}'. Available in 0.10.4+.".format_with(ApplicationParameters.Features.StopOnFirstPackageFailure, configuration.Features.StopOnFirstPackageFailure.to_string()), + "Stop On First Package Failure - stop running install, upgrade or uninstall on first package failure instead of continuing with others. Overrides the default feature '{0}' set to '{1}'.".FormatWith(ApplicationParameters.Features.StopOnFirstPackageFailure, configuration.Features.StopOnFirstPackageFailure.ToStringSafe()), option => configuration.Features.StopOnFirstPackageFailure = option != null ) .Add("exitwhenrebootdetected|exit-when-reboot-detected", - "Exit When Reboot Detected - Stop running install, upgrade, or uninstall when a reboot request is detected. Requires '{0}' feature to be turned on. Will exit with either {1} or {2}. Overrides the default feature '{3}' set to '{4}'. Available in 0.10.12+.".format_with - (ApplicationParameters.Features.UsePackageExitCodes, ApplicationParameters.ExitCodes.ErrorFailNoActionReboot, ApplicationParameters.ExitCodes.ErrorInstallSuspend, ApplicationParameters.Features.ExitOnRebootDetected, configuration.Features.ExitOnRebootDetected.to_string()), + "Exit When Reboot Detected - Stop running install, upgrade, or uninstall when a reboot request is detected. Requires '{0}' feature to be turned on. Will exit with either {1} or {2}. Overrides the default feature '{3}' set to '{4}'.".FormatWith + (ApplicationParameters.Features.UsePackageExitCodes, ApplicationParameters.ExitCodes.ErrorFailNoActionReboot, ApplicationParameters.ExitCodes.ErrorInstallSuspend, ApplicationParameters.Features.ExitOnRebootDetected, configuration.Features.ExitOnRebootDetected.ToStringSafe()), option => configuration.Features.ExitOnRebootDetected = option != null ) .Add("ignoredetectedreboot|ignore-detected-reboot", - "Ignore Detected Reboot - Ignore any detected reboots if found. Overrides the default feature '{0}' set to '{1}'. Available in 0.10.12+.".format_with - (ApplicationParameters.Features.ExitOnRebootDetected, configuration.Features.ExitOnRebootDetected.to_string()), + "Ignore Detected Reboot - Ignore any detected reboots if found. Overrides the default feature '{0}' set to '{1}'.".FormatWith + (ApplicationParameters.Features.ExitOnRebootDetected, configuration.Features.ExitOnRebootDetected.ToStringSafe()), option => { if (option != null) @@ -149,18 +149,18 @@ public virtual void configure_argument_parser(OptionSet optionSet, ChocolateyCon ; } - public virtual void handle_additional_argument_parsing(IList unparsedArguments, ChocolateyConfiguration configuration) + public virtual void ParseAdditionalArguments(IList unparsedArguments, ChocolateyConfiguration configuration) { configuration.Input = string.Join(" ", unparsedArguments); - configuration.PackageNames = string.Join(ApplicationParameters.PackageNamesSeparator.to_string(), unparsedArguments.Where(arg => !arg.StartsWith("-"))); + configuration.PackageNames = string.Join(ApplicationParameters.PackageNamesSeparator.ToStringSafe(), unparsedArguments.Where(arg => !arg.StartsWith("-"))); if (configuration.RegularOutput) { - warn_for_removed_options(unparsedArguments.Where(arg => arg.StartsWith("-")), _removedOptions); + WarnForRemovedOptions(unparsedArguments.Where(arg => arg.StartsWith("-")), _removedOptions); } } - public virtual void handle_validation(ChocolateyConfiguration configuration) + public virtual void Validate(ChocolateyConfiguration configuration) { if (string.IsNullOrWhiteSpace(configuration.PackageNames)) { @@ -168,18 +168,13 @@ public virtual void handle_validation(ChocolateyConfiguration configuration) } } - public virtual void help_message(ChocolateyConfiguration configuration) + public virtual void HelpMessage(ChocolateyConfiguration configuration) { this.Log().Info(ChocolateyLoggers.Important, "Uninstall Command"); this.Log().Info(@" Uninstalls a package or a list of packages. -NOTE: 100% compatible with older chocolatey client (0.9.8.32 and below) - with options and switches. Add `-y` for previous behavior with no - prompt. In most cases you can still pass options and switches with one - dash (`-`). For more details, see the command reference (`choco -?`). - -Choco 0.9.9+ automatically tracks registry changes for ""Programs and +Chocolatey automatically tracks registry changes for ""Programs and Features"" of the underlying software's native installers when installing packages. The ""Automatic Uninstaller"" (auto uninstaller) service is a feature that can use that information to automatically @@ -204,11 +199,6 @@ Chocolatey but does not remove the software from your system (unless `-n --skipautouninstaller` flags. This will remove the package from chocolatey without attempting to uninstall the program. -NOTE: Starting in 0.9.10+, the Automatic Uninstaller (AutoUninstaller) - is turned on by default. To turn it off, run the following command: - - choco feature disable -n autoUninstaller - NOTE: Chocolatey Pro / Business automatically synchronizes with Programs and Features, ensuring manually removed apps are automatically removed from Chocolatey's repository. @@ -265,7 +255,7 @@ Exit codes that normally result from running this command. In addition to normal exit codes, packages are allowed to exit with their own codes when the feature '{0}' is - turned on. Available in v0.9.10+. + turned on. Reboot Exit Codes: - 350: pending reboot detected, no action has occurred @@ -274,8 +264,7 @@ turned on. Available in v0.9.10+. In addition to the above exit codes, you may also see reboot exit codes when the feature '{1}' is turned on. It typically requires the feature '{0}' to also be turned on to work properly. - Available in v0.10.12+. -".format_with(ApplicationParameters.Features.UsePackageExitCodes, ApplicationParameters.Features.ExitOnRebootDetected)); +".FormatWith(ApplicationParameters.Features.UsePackageExitCodes, ApplicationParameters.Features.ExitOnRebootDetected)); "chocolatey".Log().Info(ChocolateyLoggers.Important, "Options and Switches"); "chocolatey".Log().Info(@" @@ -287,20 +276,49 @@ pass specific options. "); } - public virtual void noop(ChocolateyConfiguration configuration) + public virtual void DryRun(ChocolateyConfiguration configuration) { - _packageService.uninstall_noop(configuration); + _packageService.UninstallDryRun(configuration); } - public virtual void run(ChocolateyConfiguration configuration) + public virtual void Run(ChocolateyConfiguration configuration) { - _packageService.ensure_source_app_installed(configuration); - _packageService.uninstall_run(configuration); + _packageService.Uninstall(configuration); } - public virtual bool may_require_admin_access() + public virtual bool MayRequireAdminAccess() { return true; } + +#pragma warning disable IDE1006 + [Obsolete("This overload is deprecated and will be removed in v3.")] + public virtual void configure_argument_parser(OptionSet optionSet, ChocolateyConfiguration configuration) + => ConfigureArgumentParser(optionSet, configuration); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public virtual void handle_additional_argument_parsing(IList unparsedArguments, ChocolateyConfiguration configuration) + => ParseAdditionalArguments(unparsedArguments, configuration); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public virtual void handle_validation(ChocolateyConfiguration configuration) + => Validate(configuration); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public virtual void help_message(ChocolateyConfiguration configuration) + => HelpMessage(configuration); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public virtual void noop(ChocolateyConfiguration configuration) + => DryRun(configuration); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public virtual void run(ChocolateyConfiguration configuration) + => Run(configuration); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public virtual bool may_require_admin_access() + => MayRequireAdminAccess(); +#pragma warning restore IDE1006 } } diff --git a/src/chocolatey/infrastructure.app/commands/ChocolateyUnpackSelfCommand.cs b/src/chocolatey/infrastructure.app/commands/ChocolateyUnpackSelfCommand.cs index e68b368399..449396479d 100644 --- a/src/chocolatey/infrastructure.app/commands/ChocolateyUnpackSelfCommand.cs +++ b/src/chocolatey/infrastructure.app/commands/ChocolateyUnpackSelfCommand.cs @@ -37,18 +37,18 @@ public class ChocolateyUnpackSelfCommand : ICommand private readonly IFileSystem _fileSystem; #if !NoResources - private Lazy _assemblyInitializer = new Lazy(() => Assembly.GetAssembly(typeof (ChocolateyResourcesAssembly))); + private Lazy _assemblyInitializer = new Lazy(() => adapters.Assembly.GetAssembly(typeof (ChocolateyResourcesAssembly))); #else private Lazy _assemblyInitializer = new Lazy(); #endif [EditorBrowsable(EditorBrowsableState.Never)] - public void initialize_with(Lazy assembly_initializer) + public void InitializeWith(Lazy assembly_initializer) { _assemblyInitializer = assembly_initializer; } - private IAssembly assembly + private IAssembly Assembly { get { return _assemblyInitializer.Value; } } @@ -58,19 +58,19 @@ public ChocolateyUnpackSelfCommand(IFileSystem fileSystem) _fileSystem = fileSystem; } - public virtual void configure_argument_parser(OptionSet optionSet, ChocolateyConfiguration configuration) + public virtual void ConfigureArgumentParser(OptionSet optionSet, ChocolateyConfiguration configuration) { } - public virtual void handle_additional_argument_parsing(IList unparsedArguments, ChocolateyConfiguration configuration) + public virtual void ParseAdditionalArguments(IList unparsedArguments, ChocolateyConfiguration configuration) { } - public virtual void handle_validation(ChocolateyConfiguration configuration) + public virtual void Validate(ChocolateyConfiguration configuration) { } - public virtual void help_message(ChocolateyConfiguration configuration) + public virtual void HelpMessage(ChocolateyConfiguration configuration) { this.Log().Info(ChocolateyLoggers.Important, "UnpackSelf Command"); this.Log().Info(@" @@ -85,18 +85,18 @@ during normal operation. "chocolatey".Log().Info(ChocolateyLoggers.Important, "Options and Switches"); } - public virtual void noop(ChocolateyConfiguration configuration) + public virtual void DryRun(ChocolateyConfiguration configuration) { - this.Log().Info("This would have unpacked {0} for use relative where the executable is, based on resources embedded in {0}.".format_with(ApplicationParameters.Name)); + this.Log().Info("This would have unpacked {0} for use relative where the executable is, based on resources embedded in {0}.".FormatWith(ApplicationParameters.Name)); } - public virtual void run(ChocolateyConfiguration configuration) + public virtual void Run(ChocolateyConfiguration configuration) { - this.Log().Info("{0} is unpacking required files for use. Overwriting? {1}".format_with(ApplicationParameters.Name, configuration.Force)); + this.Log().Info("{0} is unpacking required files for use. Overwriting? {1}".FormatWith(ApplicationParameters.Name, configuration.Force)); // refactor - thank goodness this is temporary, cuz manifest resource streams are dumb // unpack the manifest file as well - AssemblyFileExtractor.extract_all_resources_to_relative_directory(_fileSystem, Assembly.GetAssembly(typeof(ChocolateyUnpackSelfCommand)), _fileSystem.get_directory_name(_fileSystem.get_current_assembly_path()), new List(), "chocolatey.console"); + AssemblyFileExtractor.ExtractAssemblyResourcesToRelativeDirectory(_fileSystem, adapters.Assembly.GetAssembly(typeof(ChocolateyUnpackSelfCommand)), _fileSystem.GetDirectoryName(_fileSystem.GetCurrentAssemblyPath()), new List(), "chocolatey.console"); IList folders = new List { @@ -106,19 +106,49 @@ public virtual void run(ChocolateyConfiguration configuration) "tools" }; - AssemblyFileExtractor.extract_all_resources_to_relative_directory( + AssemblyFileExtractor.ExtractAssemblyResourcesToRelativeDirectory( _fileSystem, - assembly, - _fileSystem.get_directory_name(_fileSystem.get_current_assembly_path()), + Assembly, + _fileSystem.GetDirectoryName(_fileSystem.GetCurrentAssemblyPath()), folders, ApplicationParameters.ChocolateyFileResources, overwriteExisting: configuration.Force, logOutput: true); } - public virtual bool may_require_admin_access() + public virtual bool MayRequireAdminAccess() { return true; } + +#pragma warning disable IDE1006 + [Obsolete("This overload is deprecated and will be removed in v3.")] + public virtual void configure_argument_parser(OptionSet optionSet, ChocolateyConfiguration configuration) + => ConfigureArgumentParser(optionSet, configuration); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public virtual void handle_additional_argument_parsing(IList unparsedArguments, ChocolateyConfiguration configuration) + => ParseAdditionalArguments(unparsedArguments, configuration); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public virtual void handle_validation(ChocolateyConfiguration configuration) + => Validate(configuration); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public virtual void help_message(ChocolateyConfiguration configuration) + => HelpMessage(configuration); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public virtual void noop(ChocolateyConfiguration configuration) + => DryRun(configuration); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public virtual void run(ChocolateyConfiguration configuration) + => Run(configuration); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public virtual bool may_require_admin_access() + => MayRequireAdminAccess(); +#pragma warning restore IDE1006 } } diff --git a/src/chocolatey/infrastructure.app/commands/ChocolateyUpgradeCommand.cs b/src/chocolatey/infrastructure.app/commands/ChocolateyUpgradeCommand.cs index 0296394cfa..ec42a2cb74 100644 --- a/src/chocolatey/infrastructure.app/commands/ChocolateyUpgradeCommand.cs +++ b/src/chocolatey/infrastructure.app/commands/ChocolateyUpgradeCommand.cs @@ -48,15 +48,15 @@ public ChocolateyUpgradeCommand(IChocolateyPackageService packageService) _packageService = packageService; } - public virtual void configure_argument_parser(OptionSet optionSet, ChocolateyConfiguration configuration) + public virtual void ConfigureArgumentParser(OptionSet optionSet, ChocolateyConfiguration configuration) { optionSet .Add("s=|source=", "Source - The source to find the package(s) to install. Special sources include: ruby, cygwin, windowsfeatures, and python. To specify more than one source, pass it with a semi-colon separating the values (e.g. \"'source1;source2'\"). Defaults to default feeds.", - option => configuration.Sources = option.remove_surrounding_quotes()) + option => configuration.Sources = option.UnquoteSafe()) .Add("version=", "Version - A specific version to install. Defaults to unspecified.", - option => configuration.Version = option.remove_surrounding_quotes()) + option => configuration.Version = option.UnquoteSafe()) .Add("pre|prerelease", "Prerelease - Include Prereleases? Defaults to false.", option => configuration.Prerelease = option != null) @@ -65,7 +65,7 @@ public virtual void configure_argument_parser(OptionSet optionSet, ChocolateyCon option => configuration.ForceX86 = option != null) .Add("ia=|installargs=|install-args=|installarguments=|install-arguments=", "InstallArguments - Install Arguments to pass to the native installer in the package. Defaults to unspecified.", - option => configuration.InstallArguments = option.remove_surrounding_quotes()) + option => configuration.InstallArguments = option.UnquoteSafe()) .Add("o|override|overrideargs|overridearguments|override-arguments", "OverrideArguments - Should install arguments be used exclusively without appending to current package passed arguments? Defaults to false.", option => configuration.OverrideArguments = option != null) @@ -74,7 +74,7 @@ public virtual void configure_argument_parser(OptionSet optionSet, ChocolateyCon option => configuration.NotSilent = option != null) .Add("params=|parameters=|pkgparameters=|packageparameters=|package-parameters=", "PackageParameters - Parameters to pass to the package. Defaults to unspecified.", - option => configuration.PackageParameters = option.remove_surrounding_quotes()) + option => configuration.PackageParameters = option.UnquoteSafe()) .Add("argsglobal|args-global|installargsglobal|install-args-global|applyargstodependencies|apply-args-to-dependencies|apply-install-arguments-to-dependencies", "Apply Install Arguments To Dependencies - Should install arguments be applied to dependent packages? Defaults to false.", option => configuration.ApplyInstallArgumentsToDependencies = option != null) @@ -94,43 +94,43 @@ public virtual void configure_argument_parser(OptionSet optionSet, ChocolateyCon "Fail On Unfound Packages - If a package is not found in sources specified, fail instead of warn.", option => configuration.UpgradeCommand.FailOnUnfound = option != null) .Add("ignore-unfound", - "Ignore Unfound Packages - Ignore packages that are not found on the sources used (or the defaults). Overrides the default feature '{0}' set to '{1}'. Available in 0.10.9+.".format_with(ApplicationParameters.Features.IgnoreUnfoundPackagesOnUpgradeOutdated, configuration.Features.IgnoreUnfoundPackagesOnUpgradeOutdated.to_string()), + "Ignore Unfound Packages - Ignore packages that are not found on the sources used (or the defaults). Overrides the default feature '{0}' set to '{1}'.".FormatWith(ApplicationParameters.Features.IgnoreUnfoundPackagesOnUpgradeOutdated, configuration.Features.IgnoreUnfoundPackagesOnUpgradeOutdated.ToStringSafe()), option => configuration.Features.IgnoreUnfoundPackagesOnUpgradeOutdated = option != null) .Add("failonnotinstalled|fail-on-not-installed", "Fail On Non-installed Packages - If a package is not already installed, fail instead of installing.", option => configuration.UpgradeCommand.FailOnNotInstalled = option != null) .Add("u=|user=", "User - used with authenticated feeds. Defaults to empty.", - option => configuration.SourceCommand.Username = option.remove_surrounding_quotes()) + option => configuration.SourceCommand.Username = option.UnquoteSafe()) .Add("p=|password=", "Password - the user's password to the source. Defaults to empty.", - option => configuration.SourceCommand.Password = option.remove_surrounding_quotes()) + option => configuration.SourceCommand.Password = option.UnquoteSafe()) .Add("cert=", - "Client certificate - PFX pathname for an x509 authenticated feeds. Defaults to empty. Available in 0.9.10+.", - option => configuration.SourceCommand.Certificate = option.remove_surrounding_quotes()) + "Client certificate - PFX pathname for an x509 authenticated feeds. Defaults to empty.", + option => configuration.SourceCommand.Certificate = option.UnquoteSafe()) .Add("cp=|certpassword=", - "Certificate Password - the client certificate's password to the source. Defaults to empty. Available in 0.9.10+.", - option => configuration.SourceCommand.CertificatePassword = option.remove_surrounding_quotes()) + "Certificate Password - the client certificate's password to the source. Defaults to empty.", + option => configuration.SourceCommand.CertificatePassword = option.UnquoteSafe()) .Add("ignorechecksum|ignore-checksum|ignorechecksums|ignore-checksums", - "IgnoreChecksums - Ignore checksums provided by the package. Overrides the default feature '{0}' set to '{1}'. Available in 0.9.9.9+.".format_with(ApplicationParameters.Features.ChecksumFiles, configuration.Features.ChecksumFiles.to_string()), + "IgnoreChecksums - Ignore checksums provided by the package. Overrides the default feature '{0}' set to '{1}'.".FormatWith(ApplicationParameters.Features.ChecksumFiles, configuration.Features.ChecksumFiles.ToStringSafe()), option => { if (option != null) configuration.Features.ChecksumFiles = false; }) .Add("allowemptychecksum|allowemptychecksums|allow-empty-checksums", - "Allow Empty Checksums - Allow packages to have empty/missing checksums for downloaded resources from non-secure locations (HTTP, FTP). Use this switch is not recommended if using sources that download resources from the internet. Overrides the default feature '{0}' set to '{1}'. Available in 0.10.0+.".format_with(ApplicationParameters.Features.AllowEmptyChecksums, configuration.Features.AllowEmptyChecksums.to_string()), + "Allow Empty Checksums - Allow packages to have empty/missing checksums for downloaded resources from non-secure locations (HTTP, FTP). Use this switch is not recommended if using sources that download resources from the internet. Overrides the default feature '{0}' set to '{1}'.".FormatWith(ApplicationParameters.Features.AllowEmptyChecksums, configuration.Features.AllowEmptyChecksums.ToStringSafe()), option => { if (option != null) configuration.Features.AllowEmptyChecksums = true; }) .Add("allowemptychecksumsecure|allowemptychecksumssecure|allow-empty-checksums-secure", - "Allow Empty Checksums Secure - Allow packages to have empty checksums for downloaded resources from secure locations (HTTPS). Overrides the default feature '{0}' set to '{1}'. Available in 0.10.0+.".format_with(ApplicationParameters.Features.AllowEmptyChecksumsSecure, configuration.Features.AllowEmptyChecksumsSecure.to_string()), + "Allow Empty Checksums Secure - Allow packages to have empty checksums for downloaded resources from secure locations (HTTPS). Overrides the default feature '{0}' set to '{1}'.".FormatWith(ApplicationParameters.Features.AllowEmptyChecksumsSecure, configuration.Features.AllowEmptyChecksumsSecure.ToStringSafe()), option => { if (option != null) configuration.Features.AllowEmptyChecksumsSecure = true; }) .Add("requirechecksum|requirechecksums|require-checksums", - "Require Checksums - Requires packages to have checksums for downloaded resources (both non-secure and secure). Overrides the default feature '{0}' set to '{1}' and '{2}' set to '{3}'. Available in 0.10.0+.".format_with(ApplicationParameters.Features.AllowEmptyChecksums, configuration.Features.AllowEmptyChecksums.to_string(), ApplicationParameters.Features.AllowEmptyChecksumsSecure, configuration.Features.AllowEmptyChecksumsSecure.to_string()), + "Require Checksums - Requires packages to have checksums for downloaded resources (both non-secure and secure). Overrides the default feature '{0}' set to '{1}' and '{2}' set to '{3}'.".FormatWith(ApplicationParameters.Features.AllowEmptyChecksums, configuration.Features.AllowEmptyChecksums.ToStringSafe(), ApplicationParameters.Features.AllowEmptyChecksumsSecure, configuration.Features.AllowEmptyChecksumsSecure.ToStringSafe()), option => { if (option != null) @@ -141,19 +141,19 @@ public virtual void configure_argument_parser(OptionSet optionSet, ChocolateyCon } }) .Add("checksum=|downloadchecksum=|download-checksum=", - "Download Checksum - a user provided checksum for downloaded resources for the package. Overrides the package checksum (if it has one). Defaults to empty. Available in 0.10.0+.", - option => configuration.DownloadChecksum = option.remove_surrounding_quotes()) + "Download Checksum - a user provided checksum for downloaded resources for the package. Overrides the package checksum (if it has one). Defaults to empty.", + option => configuration.DownloadChecksum = option.UnquoteSafe()) .Add("checksum64=|checksumx64=|downloadchecksumx64=|download-checksum-x64=", - "Download Checksum 64bit - a user provided checksum for 64bit downloaded resources for the package. Overrides the package 64-bit checksum (if it has one). Defaults to same as Download Checksum. Available in 0.10.0+.", - option => configuration.DownloadChecksum64 = option.remove_surrounding_quotes()) + "Download Checksum 64bit - a user provided checksum for 64bit downloaded resources for the package. Overrides the package 64-bit checksum (if it has one). Defaults to same as Download Checksum.", + option => configuration.DownloadChecksum64 = option.UnquoteSafe()) .Add("checksumtype=|checksum-type=|downloadchecksumtype=|download-checksum-type=", - "Download Checksum Type - a user provided checksum type. Overrides the package checksum type (if it has one). Used in conjunction with Download Checksum. Available values are 'md5', 'sha1', 'sha256' or 'sha512'. Defaults to 'md5'. Available in 0.10.0+.", - option => configuration.DownloadChecksumType = option.remove_surrounding_quotes()) + "Download Checksum Type - a user provided checksum type. Overrides the package checksum type (if it has one). Used in conjunction with Download Checksum. Available values are 'md5', 'sha1', 'sha256' or 'sha512'. Defaults to 'md5'.", + option => configuration.DownloadChecksumType = option.UnquoteSafe()) .Add("checksumtype64=|checksumtypex64=|checksum-type-x64=|downloadchecksumtypex64=|download-checksum-type-x64=", - "Download Checksum Type 64bit - a user provided checksum for 64bit downloaded resources for the package. Overrides the package 64-bit checksum (if it has one). Used in conjunction with Download Checksum 64bit. Available values are 'md5', 'sha1', 'sha256' or 'sha512'. Defaults to same as Download Checksum Type. Available in 0.10.0+.", - option => configuration.DownloadChecksumType64 = option.remove_surrounding_quotes()) + "Download Checksum Type 64bit - a user provided checksum for 64bit downloaded resources for the package. Overrides the package 64-bit checksum (if it has one). Used in conjunction with Download Checksum 64bit. Available values are 'md5', 'sha1', 'sha256' or 'sha512'. Defaults to same as Download Checksum Type.", + option => configuration.DownloadChecksumType64 = option.UnquoteSafe()) .Add("ignorepackagecodes|ignorepackageexitcodes|ignore-package-codes|ignore-package-exit-codes", - "IgnorePackageExitCodes - Exit with a 0 for success and 1 for non-success, no matter what package scripts provide for exit codes. Overrides the default feature '{0}' set to '{1}'. Available in 0.9.10+.".format_with(ApplicationParameters.Features.UsePackageExitCodes, configuration.Features.UsePackageExitCodes.to_string()), + "IgnorePackageExitCodes - Exit with a 0 for success and 1 for non-success, no matter what package scripts provide for exit codes. Overrides the default feature '{0}' set to '{1}'.".FormatWith(ApplicationParameters.Features.UsePackageExitCodes, configuration.Features.UsePackageExitCodes.ToStringSafe()), option => { if (option != null) @@ -162,23 +162,23 @@ public virtual void configure_argument_parser(OptionSet optionSet, ChocolateyCon } }) .Add("usepackagecodes|usepackageexitcodes|use-package-codes|use-package-exit-codes", - "UsePackageExitCodes - Package scripts can provide exit codes. Use those for choco's exit code when non-zero (this value can come from a dependency package). Chocolatey defines valid exit codes as 0, 1605, 1614, 1641, 3010. Overrides the default feature '{0}' set to '{1}'. Available in 0.9.10+.".format_with(ApplicationParameters.Features.UsePackageExitCodes, configuration.Features.UsePackageExitCodes.to_string()), + "UsePackageExitCodes - Package scripts can provide exit codes. Use those for choco's exit code when non-zero (this value can come from a dependency package). Chocolatey defines valid exit codes as 0, 1605, 1614, 1641, 3010. Overrides the default feature '{0}' set to '{1}'.".FormatWith(ApplicationParameters.Features.UsePackageExitCodes, configuration.Features.UsePackageExitCodes.ToStringSafe()), option => configuration.Features.UsePackageExitCodes = option != null ) .Add("except=", - "Except - a comma-separated list of package names that should not be upgraded when upgrading 'all'. Overrides the configuration setting '{0}' set to '{1}'. Available in 0.9.10+.".format_with(ApplicationParameters.ConfigSettings.UpgradeAllExceptions, configuration.UpgradeCommand.PackageNamesToSkip.to_string()), - option => configuration.UpgradeCommand.PackageNamesToSkip = option.remove_surrounding_quotes() + "Except - a comma-separated list of package names that should not be upgraded when upgrading 'all'. Overrides the configuration setting '{0}' set to '{1}'.".FormatWith(ApplicationParameters.ConfigSettings.UpgradeAllExceptions, configuration.UpgradeCommand.PackageNamesToSkip.ToStringSafe()), + option => configuration.UpgradeCommand.PackageNamesToSkip = option.UnquoteSafe() ) .Add("stoponfirstfailure|stop-on-first-failure|stop-on-first-package-failure", - "Stop On First Package Failure - stop running install, upgrade or uninstall on first package failure instead of continuing with others. Overrides the default feature '{0}' set to '{1}'. Available in 0.10.4+.".format_with(ApplicationParameters.Features.StopOnFirstPackageFailure, configuration.Features.StopOnFirstPackageFailure.to_string()), + "Stop On First Package Failure - stop running install, upgrade or uninstall on first package failure instead of continuing with others. Overrides the default feature '{0}' set to '{1}'.".FormatWith(ApplicationParameters.Features.StopOnFirstPackageFailure, configuration.Features.StopOnFirstPackageFailure.ToStringSafe()), option => configuration.Features.StopOnFirstPackageFailure = option != null ) .Add("skip-if-not-installed|only-upgrade-installed|skip-when-not-installed", - "Skip Packages Not Installed - if a package is not installed, do not install it during the upgrade process. Overrides the default feature '{0}' set to '{1}'. Available in 0.10.12+.".format_with(ApplicationParameters.Features.SkipPackageUpgradesWhenNotInstalled, configuration.Features.SkipPackageUpgradesWhenNotInstalled.to_string()), + "Skip Packages Not Installed - if a package is not installed, do not install it during the upgrade process. Overrides the default feature '{0}' set to '{1}'.".FormatWith(ApplicationParameters.Features.SkipPackageUpgradesWhenNotInstalled, configuration.Features.SkipPackageUpgradesWhenNotInstalled.ToStringSafe()), option => configuration.Features.SkipPackageUpgradesWhenNotInstalled = option != null ) .Add("install-if-not-installed", - "Install Missing Packages When Not Installed - if a package is not installed, install it as part of running upgrade (typically default behavior). Overrides the default feature '{0}' set to '{1}'. Available in 0.10.12+.".format_with(ApplicationParameters.Features.SkipPackageUpgradesWhenNotInstalled, configuration.Features.SkipPackageUpgradesWhenNotInstalled.to_string()), + "Install Missing Packages When Not Installed - if a package is not installed, install it as part of running upgrade (typically default behavior). Overrides the default feature '{0}' set to '{1}'.".FormatWith(ApplicationParameters.Features.SkipPackageUpgradesWhenNotInstalled, configuration.Features.SkipPackageUpgradesWhenNotInstalled.ToStringSafe()), option => { if (option != null) @@ -187,29 +187,29 @@ public virtual void configure_argument_parser(OptionSet optionSet, ChocolateyCon } }) .Add("exclude-pre|exclude-prerelease|exclude-prereleases", - "Exclude Prerelease - Should prerelease be ignored for upgrades? Will be ignored if you pass `--pre`. Available in 0.10.4+.", + "Exclude Prerelease - Should prerelease be ignored for upgrades? Will be ignored if you pass `--pre`.", option => configuration.UpgradeCommand.ExcludePrerelease = option != null ) .Add("userememberedargs|userememberedarguments|userememberedoptions|use-remembered-args|use-remembered-arguments|use-remembered-options", - "Use Remembered Options for Upgrade - use the arguments and options used during install for upgrade. Does not override arguments being passed at runtime. Overrides the default feature '{0}' set to '{1}'. Available in 0.10.4+.".format_with(ApplicationParameters.Features.UseRememberedArgumentsForUpgrades, configuration.Features.UseRememberedArgumentsForUpgrades.to_string()), + "Use Remembered Options for Upgrade - use the arguments and options used during install for upgrade. Does not override arguments being passed at runtime. Overrides the default feature '{0}' set to '{1}'.".FormatWith(ApplicationParameters.Features.UseRememberedArgumentsForUpgrades, configuration.Features.UseRememberedArgumentsForUpgrades.ToStringSafe()), option => { if (option != null) configuration.Features.UseRememberedArgumentsForUpgrades = true; }) .Add("ignorerememberedargs|ignorerememberedarguments|ignorerememberedoptions|ignore-remembered-args|ignore-remembered-arguments|ignore-remembered-options", - "Ignore Remembered Options for Upgrade - ignore the arguments and options used during install for upgrade. Overrides the default feature '{0}' set to '{1}'. Available in 0.10.4+.".format_with(ApplicationParameters.Features.UseRememberedArgumentsForUpgrades, configuration.Features.UseRememberedArgumentsForUpgrades.to_string()), + "Ignore Remembered Options for Upgrade - ignore the arguments and options used during install for upgrade. Overrides the default feature '{0}' set to '{1}'.".FormatWith(ApplicationParameters.Features.UseRememberedArgumentsForUpgrades, configuration.Features.UseRememberedArgumentsForUpgrades.ToStringSafe()), option => { if (option != null) configuration.Features.UseRememberedArgumentsForUpgrades = false; }) .Add("exitwhenrebootdetected|exit-when-reboot-detected", - "Exit When Reboot Detected - Stop running install, upgrade, or uninstall when a reboot request is detected. Requires '{0}' feature to be turned on. Will exit with either {1} or {2}. Overrides the default feature '{3}' set to '{4}'. Available in 0.10.12+.".format_with - (ApplicationParameters.Features.UsePackageExitCodes, ApplicationParameters.ExitCodes.ErrorFailNoActionReboot, ApplicationParameters.ExitCodes.ErrorInstallSuspend, ApplicationParameters.Features.ExitOnRebootDetected, configuration.Features.ExitOnRebootDetected.to_string()), + "Exit When Reboot Detected - Stop running install, upgrade, or uninstall when a reboot request is detected. Requires '{0}' feature to be turned on. Will exit with either {1} or {2}. Overrides the default feature '{3}' set to '{4}'.".FormatWith + (ApplicationParameters.Features.UsePackageExitCodes, ApplicationParameters.ExitCodes.ErrorFailNoActionReboot, ApplicationParameters.ExitCodes.ErrorInstallSuspend, ApplicationParameters.Features.ExitOnRebootDetected, configuration.Features.ExitOnRebootDetected.ToStringSafe()), option => configuration.Features.ExitOnRebootDetected = option != null ) .Add("ignoredetectedreboot|ignore-detected-reboot", - "Ignore Detected Reboot - Ignore any detected reboots if found. Overrides the default feature '{0}' set to '{1}'. Available in 0.10.12+.".format_with - (ApplicationParameters.Features.ExitOnRebootDetected, configuration.Features.ExitOnRebootDetected.to_string()), + "Ignore Detected Reboot - Ignore any detected reboots if found. Overrides the default feature '{0}' set to '{1}'.".FormatWith + (ApplicationParameters.Features.ExitOnRebootDetected, configuration.Features.ExitOnRebootDetected.ToStringSafe()), option => { if (option != null) @@ -218,8 +218,8 @@ public virtual void configure_argument_parser(OptionSet optionSet, ChocolateyCon } }) .Add("disable-repository-optimizations|disable-package-repository-optimizations", - "Disable Package Repository Optimizations - Do not use optimizations for reducing bandwidth with repository queries during package install/upgrade/outdated operations. Should not generally be used, unless a repository needs to support older methods of query. When disabled, this makes queries similar to the way they were done in Chocolatey v0.10.11 and before. Overrides the default feature '{0}' set to '{1}'. Available in 0.10.14+.".format_with - (ApplicationParameters.Features.UsePackageRepositoryOptimizations, configuration.Features.UsePackageRepositoryOptimizations.to_string()), + "Disable Package Repository Optimizations - Do not use optimizations for reducing bandwidth with repository queries during package install/upgrade/outdated operations. Should not generally be used, unless a repository needs to support older methods of query. When disabled, this makes queries similar to the way they were done in earlier versions of Chocolatey. Overrides the default feature '{0}' set to '{1}'.".FormatWith + (ApplicationParameters.Features.UsePackageRepositoryOptimizations, configuration.Features.UsePackageRepositoryOptimizations.ToStringSafe()), option => { if (option != null) @@ -238,18 +238,18 @@ public virtual void configure_argument_parser(OptionSet optionSet, ChocolateyCon ; } - public virtual void handle_additional_argument_parsing(IList unparsedArguments, ChocolateyConfiguration configuration) + public virtual void ParseAdditionalArguments(IList unparsedArguments, ChocolateyConfiguration configuration) { configuration.Input = string.Join(" ", unparsedArguments); - configuration.PackageNames = string.Join(ApplicationParameters.PackageNamesSeparator.to_string(), unparsedArguments.Where(arg => !arg.StartsWith("-"))); + configuration.PackageNames = string.Join(ApplicationParameters.PackageNamesSeparator.ToStringSafe(), unparsedArguments.Where(arg => !arg.StartsWith("-"))); if (configuration.RegularOutput) { - warn_for_removed_options(unparsedArguments.Where(arg => arg.StartsWith("-")), _removedOptions); + WarnForRemovedOptions(unparsedArguments.Where(arg => arg.StartsWith("-")), _removedOptions); } } - public virtual void handle_validation(ChocolateyConfiguration configuration) + public virtual void Validate(ChocolateyConfiguration configuration) { if (string.IsNullOrWhiteSpace(configuration.PackageNames)) { @@ -266,12 +266,12 @@ public virtual void handle_validation(ChocolateyConfiguration configuration) var unparsedOptionsAndPackages = configuration.Input.Split(new[] { " " }, StringSplitOptions.RemoveEmptyEntries); if (!configuration.Information.IsLicensedVersion) { - foreach (var argument in unparsedOptionsAndPackages.or_empty_list_if_null()) + foreach (var argument in unparsedOptionsAndPackages.OrEmpty()) { - var arg = argument.to_lower(); + var arg = argument.ToLowerSafe(); if (arg.StartsWith("-dir") || arg.StartsWith("--dir") || arg.StartsWith("-install") || arg.StartsWith("--install")) { - throw new ApplicationException("It appears you are attempting to use options that may be only available in licensed versions of Chocolatey ('{0}'). There may be ways in the open source edition to achieve what you are looking to do. Please remove the argument and consult the documentation.".format_with(arg)); + throw new ApplicationException("It appears you are attempting to use options that may be only available in licensed versions of Chocolatey ('{0}'). There may be ways in the open source edition to achieve what you are looking to do. Please remove the argument and consult the documentation.".FormatWith(arg)); } } } @@ -279,23 +279,18 @@ public virtual void handle_validation(ChocolateyConfiguration configuration) if (!string.IsNullOrWhiteSpace(configuration.SourceCommand.Username) && string.IsNullOrWhiteSpace(configuration.SourceCommand.Password)) { - this.Log().Debug(ChocolateyLoggers.LogFileOnly, "Username '{0}' provided. Asking for password.".format_with(configuration.SourceCommand.Username)); - System.Console.Write("User name '{0}' provided. Password: ".format_with(configuration.SourceCommand.Username)); - configuration.SourceCommand.Password = InteractivePrompt.get_password(configuration.PromptForConfirmation); + this.Log().Debug(ChocolateyLoggers.LogFileOnly, "Username '{0}' provided. Asking for password.".FormatWith(configuration.SourceCommand.Username)); + System.Console.Write("User name '{0}' provided. Password: ".FormatWith(configuration.SourceCommand.Username)); + configuration.SourceCommand.Password = InteractivePrompt.GetPassword(configuration.PromptForConfirmation); } } - public virtual void help_message(ChocolateyConfiguration configuration) + public virtual void HelpMessage(ChocolateyConfiguration configuration) { this.Log().Info(ChocolateyLoggers.Important, "Upgrade Command"); this.Log().Info(@" Upgrades a package or a list of packages. If you do not have a package installed, upgrade will install it. - -NOTE: 100% compatible with older Chocolatey client (0.9.8.x and below) - with options and switches. Add `-y` for previous behavior with no - prompt. In most cases you can still pass options and switches with one - dash (`-`). For more details, see the command reference (`choco -?`). "); "chocolatey".Log().Info(ChocolateyLoggers.Important, "Usage"); @@ -350,7 +345,6 @@ Exit codes that normally result from running this command. In addition to normal exit codes, packages are allowed to exit with their own codes when the feature '{0}' is turned on. Uninstall command has additional valid exit codes. - Available in v0.9.10+. Reboot Exit Codes: - 350: pending reboot detected, no action has occurred @@ -359,8 +353,7 @@ Available in v0.9.10+. In addition to the above exit codes, you may also see reboot exit codes when the feature '{1}' is turned on. It typically requires the feature '{0}' to also be turned on to work properly. - Available in v0.10.12+. -".format_with(ApplicationParameters.Features.UsePackageExitCodes, ApplicationParameters.Features.ExitOnRebootDetected)); +".FormatWith(ApplicationParameters.Features.UsePackageExitCodes, ApplicationParameters.Features.ExitOnRebootDetected)); "chocolatey".Log().Info(ChocolateyLoggers.Important, "See It In Action"); "chocolatey".Log().Info(@" @@ -378,20 +371,49 @@ pass specific options. "); } - public virtual void noop(ChocolateyConfiguration configuration) + public virtual void DryRun(ChocolateyConfiguration configuration) { - _packageService.upgrade_noop(configuration); + _packageService.UpgradeDryRun(configuration); } - public virtual void run(ChocolateyConfiguration configuration) + public virtual void Run(ChocolateyConfiguration configuration) { - _packageService.ensure_source_app_installed(configuration); - _packageService.upgrade_run(configuration); + _packageService.Upgrade(configuration); } - public virtual bool may_require_admin_access() + public virtual bool MayRequireAdminAccess() { return true; } + +#pragma warning disable IDE1006 + [Obsolete("This overload is deprecated and will be removed in v3.")] + public virtual void configure_argument_parser(OptionSet optionSet, ChocolateyConfiguration configuration) + => ConfigureArgumentParser(optionSet, configuration); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public virtual void handle_additional_argument_parsing(IList unparsedArguments, ChocolateyConfiguration configuration) + => ParseAdditionalArguments(unparsedArguments, configuration); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public virtual void handle_validation(ChocolateyConfiguration configuration) + => Validate(configuration); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public virtual void help_message(ChocolateyConfiguration configuration) + => HelpMessage(configuration); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public virtual void noop(ChocolateyConfiguration configuration) + => DryRun(configuration); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public virtual void run(ChocolateyConfiguration configuration) + => Run(configuration); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public virtual bool may_require_admin_access() + => MayRequireAdminAccess(); +#pragma warning restore IDE1006 } } diff --git a/src/chocolatey/infrastructure.app/configuration/ChocolateyConfiguration.cs b/src/chocolatey/infrastructure.app/configuration/ChocolateyConfiguration.cs index 81bfa01a83..69f38cbbb1 100644 --- a/src/chocolatey/infrastructure.app/configuration/ChocolateyConfiguration.cs +++ b/src/chocolatey/infrastructure.app/configuration/ChocolateyConfiguration.cs @@ -38,7 +38,7 @@ public ChocolateyConfiguration() RegularOutput = true; PromptForConfirmation = true; DisableCompatibilityChecks = false; - SourceType = SourceTypes.NORMAL; + SourceType = SourceTypes.Normal; Information = new InformationCommandConfiguration(); Features = new FeaturesConfiguration(); NewCommand = new NewCommandConfiguration(); @@ -65,7 +65,7 @@ public ChocolateyConfiguration() /// Creates a backup of the current version of the configuration class. /// /// One or more objects in the class or child classes are not serializable. - public void start_backup() + public void CreateBackup() { if (_configurationBackups == null) { @@ -74,7 +74,7 @@ public void start_backup() // We do this the easy way to ensure that we have a clean copy // of the original configuration file. - _configurationBackups.Push(this.deep_copy()); + _configurationBackups.Push(this.DeepCopy()); } /// @@ -89,7 +89,7 @@ public void start_backup() /// This call may make quite a lot of allocations on the Gen0 heap, as such /// it is best to keep the calls to this method at a minimum. /// - public void reset_config(bool removeBackup = false) + public void RevertChanges(bool removeBackup = false) { if (_configurationBackups == null || _configurationBackups.Count == 0) { @@ -141,7 +141,7 @@ public void reset_config(bool removeBackup = false) { // We need to do a deep copy of the value so it won't copy the reference itself, // but rather the actual values we are interested in. - property.SetValue(this, originalValue.deep_copy(), new object[0]); + property.SetValue(this, originalValue.DeepCopy(), new object[0]); } else { @@ -150,7 +150,7 @@ public void reset_config(bool removeBackup = false) } catch (Exception ex) { - throw new ApplicationException("Unable to restore the value for the property '{0}'.".format_with(property.Name), ex); + throw new ApplicationException("Unable to restore the value for the property '{0}'.".FormatWith(property.Name), ex); } } } @@ -164,67 +164,75 @@ public override string ToString() NOTE: Hiding sensitive configuration data! Please double and triple check to be sure no sensitive data is shown, especially if copying output to a gist for review."); - output_tostring(properties, GetType().GetProperties(), this, ""); + OutputToString(properties, GetType().GetProperties(), this, ""); return properties.ToString(); } - private void output_tostring(StringBuilder propertyValues, IEnumerable properties, object obj, string prepend) + private void OutputToString(StringBuilder propertyValues, IEnumerable properties, object obj, string prepend) { - foreach (var propertyInfo in properties.or_empty_list_if_null()) + foreach (var propertyInfo in properties.OrEmpty()) { // skip sensitive data info - if (propertyInfo.Name.contains("password") || propertyInfo.Name.contains("sensitive") || propertyInfo.Name == "Key" || propertyInfo.Name == "ConfigValue" || propertyInfo.Name == "MachineSources") + if (propertyInfo.Name.ContainsSafe("password") || propertyInfo.Name.ContainsSafe("sensitive") || propertyInfo.Name == "Key" || propertyInfo.Name == "ConfigValue" || propertyInfo.Name == "MachineSources") { continue; } var objectValue = propertyInfo.GetValue(obj, null); - if (propertyInfo.PropertyType.is_built_in_system_type()) + if (propertyInfo.PropertyType.IsBuiltinType()) { - if (!string.IsNullOrWhiteSpace(objectValue.to_string())) + if (!string.IsNullOrWhiteSpace(objectValue.ToStringSafe())) { - var output = "{0}{1}='{2}'|".format_with( + var output = "{0}{1}='{2}'|".FormatWith( string.IsNullOrWhiteSpace(prepend) ? "" : prepend + ".", propertyInfo.Name, - objectValue.to_string()); + objectValue.ToStringSafe()); - append_output(propertyValues, output); + AppendOutput(propertyValues, output); } } - else if (propertyInfo.PropertyType.is_collections_type()) + else if (propertyInfo.PropertyType.IsCollectionType()) { var list = objectValue as IDictionary; - foreach (var item in list.or_empty_list_if_null()) + foreach (var item in list.OrEmpty()) { - var output = "{0}{1}.{2}='{3}'|".format_with( + var output = "{0}{1}.{2}='{3}'|".FormatWith( string.IsNullOrWhiteSpace(prepend) ? "" : prepend + ".", propertyInfo.Name, item.Key, item.Value); - append_output(propertyValues, output); + AppendOutput(propertyValues, output); } } + else if (objectValue is null) + { + var output = "{0}{1}={{null}}".FormatWith( + string.IsNullOrWhiteSpace(prepend) ? "" : prepend + ".", + propertyInfo.Name); + + AppendOutput(propertyValues, output); + } else { - output_tostring(propertyValues, propertyInfo.PropertyType.GetProperties(), objectValue, propertyInfo.Name); + OutputToString(propertyValues, propertyInfo.PropertyType.GetProperties(), objectValue, propertyInfo.Name); } } } - private const int MAX_CONSOLE_LINE_LENGTH = 72; + private const int MaxConsoleLineLength = 72; private int _currentLineLength = 0; - private void append_output(StringBuilder propertyValues, string append) + private void AppendOutput(StringBuilder propertyValues, string append) { _currentLineLength += append.Length; propertyValues.AppendFormat("{0}{1}{2}", - _currentLineLength < MAX_CONSOLE_LINE_LENGTH ? string.Empty : Environment.NewLine, + _currentLineLength < MaxConsoleLineLength ? string.Empty : Environment.NewLine, append, - append.Length < MAX_CONSOLE_LINE_LENGTH ? string.Empty : Environment.NewLine); + append.Length < MaxConsoleLineLength ? string.Empty : Environment.NewLine); - if (_currentLineLength > MAX_CONSOLE_LINE_LENGTH) + if (_currentLineLength > MaxConsoleLineLength) { _currentLineLength = append.Length; } @@ -255,6 +263,7 @@ private void append_output(StringBuilder propertyValues, string append) // top level commands + public bool ShowOnlineHelp { get; set; } public bool Debug { get; set; } public bool Verbose { get; set; } public bool Trace { get; set; } @@ -468,6 +477,16 @@ private void append_output(StringBuilder propertyValues, string append) /// On .NET 4.0, get error CS0200 when private set - see http://stackoverflow.com/a/23809226/18475 /// public TemplateCommandConfiguration TemplateCommand { get; set; } + +#pragma warning disable IDE1006 + [Obsolete("This overload is deprecated and will be removed in v3.")] + public void start_backup() + => CreateBackup(); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public void reset_config(bool removeBackup = false) + => RevertChanges(removeBackup); +#pragma warning restore IDE1006 } [Serializable] @@ -553,6 +572,7 @@ public ListCommandConfiguration() public bool NotBroken { get; set; } public bool IncludeVersionOverrides { get; set; } public bool ExplicitPageSize { get; set; } + public bool ExplicitSource { get; set; } } [Serializable] diff --git a/src/chocolatey/infrastructure.app/configuration/ConfigurationOptions.cs b/src/chocolatey/infrastructure.app/configuration/ConfigurationOptions.cs index 2ff928da9a..8a19f00c1e 100644 --- a/src/chocolatey/infrastructure.app/configuration/ConfigurationOptions.cs +++ b/src/chocolatey/infrastructure.app/configuration/ConfigurationOptions.cs @@ -19,6 +19,7 @@ namespace chocolatey.infrastructure.app.configuration using System; using System.Collections.Generic; using System.ComponentModel; + using System.Diagnostics; using System.Linq; using System.Text.RegularExpressions; using adapters; @@ -30,12 +31,12 @@ public static class ConfigurationOptions private static Lazy _console = new Lazy(() => new Console()); [EditorBrowsable(EditorBrowsableState.Never)] - public static void initialize_with(Lazy console) + public static void InitializeWith(Lazy console) { _console = console; } - public static void reset_options() + public static void ClearOptions() { _optionSet.Clear(); } @@ -61,7 +62,7 @@ public static OptionSet OptionSet /// Actions to take after parsing /// Validate the configuration /// The help message. - public static void parse_arguments_and_update_configuration(ICollection args, + public static void ParseArgumentsAndUpdateConfiguration(ICollection args, ChocolateyConfiguration configuration, Action setOptions, Action> afterParse, @@ -75,8 +76,11 @@ public static void parse_arguments_and_update_configuration(ICollection { _optionSet .Add("?|help|h", - "Prints out the help menu.", - option => configuration.HelpRequested = option != null); + "Prints out the help menu.", + option => configuration.HelpRequested = option != null) + .Add("online", + "Online - Open help for specified command in default browser application. This option only works when used in combintation with the -?/--help/-h option.", + option => configuration.ShowOnlineHelp = option != null); } if (setOptions != null) @@ -90,7 +94,7 @@ public static void parse_arguments_and_update_configuration(ICollection } catch (OptionException) { - show_help(_optionSet, helpMessage); + ShowHelp(_optionSet, helpMessage); configuration.UnsuccessfulParsing = true; } @@ -102,7 +106,7 @@ public static void parse_arguments_and_update_configuration(ICollection { configuration.CommandName = commandName; } - else if (commandName.is_equal_to("-v") || commandName.is_equal_to("--version")) + else if (commandName.IsEqualTo("-v") || commandName.IsEqualTo("--version")) { // skip help menu } @@ -120,10 +124,38 @@ public static void parse_arguments_and_update_configuration(ICollection if (configuration.HelpRequested) { - show_help(_optionSet, helpMessage); + if (configuration.ShowOnlineHelp) + { + if (string.IsNullOrWhiteSpace(configuration.CommandName)) + { + "chocolatey".Log().Warn("Unable to open command help as no command name has been provided."); + return; + } + + var targetAddress = "https://ch0.co/c/{0}".FormatWith(configuration.CommandName.ToLowerSafe()); + + try + { + System.Diagnostics.Process.Start(new ProcessStartInfo(targetAddress) { UseShellExecute = true }); + } + catch (Exception) + { + "chocolatey".Log().Warn("There was an error while attempting to open the following URL: {0} in the default browser.".FormatWith(targetAddress)); + } + + return; + } + + ShowHelp(_optionSet, helpMessage); } else { + // Only show this warning once + if (configuration.ShowOnlineHelp) + { + "chocolatey".Log().Warn("The --online option has been used, without the corresponding -?/--help/-h option. Command execution will be completed without invoking help."); + } + if (validateConfiguration != null) { validateConfiguration(); @@ -136,7 +168,7 @@ public static void parse_arguments_and_update_configuration(ICollection /// /// The option_set. /// The action that displays the message - private static void show_help(OptionSet optionSet, Action helpMessage) + private static void ShowHelp(OptionSet optionSet, Action helpMessage) { if (helpMessage != null) { @@ -145,5 +177,25 @@ private static void show_help(OptionSet optionSet, Action helpMessage) optionSet.WriteOptionDescriptions(Console.Out); } + +#pragma warning disable IDE1006 + [Obsolete("This overload is deprecated and will be removed in v3.")] + [EditorBrowsable(EditorBrowsableState.Never)] + public static void initialize_with(Lazy console) + => InitializeWith(console); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public static void reset_options() + => ClearOptions(); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public static void parse_arguments_and_update_configuration(ICollection args, + ChocolateyConfiguration configuration, + Action setOptions, + Action> afterParse, + Action validateConfiguration, + Action helpMessage) + => ParseArgumentsAndUpdateConfiguration(args, configuration, setOptions, afterParse, validateConfiguration, helpMessage); +#pragma warning restore IDE1006 } } diff --git a/src/chocolatey/infrastructure.app/configuration/EnvironmentSettings.cs b/src/chocolatey/infrastructure.app/configuration/EnvironmentSettings.cs index 72792e4c98..afa69676ad 100644 --- a/src/chocolatey/infrastructure.app/configuration/EnvironmentSettings.cs +++ b/src/chocolatey/infrastructure.app/configuration/EnvironmentSettings.cs @@ -31,11 +31,11 @@ namespace chocolatey.infrastructure.app.configuration public static class EnvironmentSettings { - private const string SET_ENVIRONMENT_METHOD = "SetEnvironment"; + private const string SetEnvironmentMethod = "SetEnvironment"; private static Lazy _environmentInitializer = new Lazy(() => new Environment()); [EditorBrowsable(EditorBrowsableState.Never)] - public static void initialize_with(Lazy environment) + public static void InitializeWith(Lazy environment) { _environmentInitializer = environment; } @@ -45,7 +45,7 @@ private static IEnvironment Environment get { return _environmentInitializer.Value; } } - public static void reset_environment_variables(ChocolateyConfiguration config) + public static void ResetEnvironmentVariables(ChocolateyConfiguration config) { Environment.SetEnvironmentVariable(ApplicationParameters.Environment.ChocolateyPackageInstallLocation, null); Environment.SetEnvironmentVariable(ApplicationParameters.Environment.ChocolateyPackageInstallerType, null); @@ -63,16 +63,16 @@ public static void reset_environment_variables(ChocolateyConfiguration config) Environment.SetEnvironmentVariable("chocolateyProxyBypassOnLocal", null); } - public static void set_environment_variables(ChocolateyConfiguration config) + public static void SetEnvironmentVariables(ChocolateyConfiguration config) { - reset_environment_variables(config); + ResetEnvironmentVariables(config); Environment.SetEnvironmentVariable(ApplicationParameters.ChocolateyInstallEnvironmentVariableName, ApplicationParameters.InstallLocation); Environment.SetEnvironmentVariable("CHOCOLATEY_VERSION", config.Information.ChocolateyVersion); Environment.SetEnvironmentVariable("CHOCOLATEY_VERSION_PRODUCT", config.Information.ChocolateyProductVersion); - Environment.SetEnvironmentVariable("OS_PLATFORM", config.Information.PlatformType.get_description_or_value()); - Environment.SetEnvironmentVariable("OS_VERSION", config.Information.PlatformVersion.to_string()); - Environment.SetEnvironmentVariable("OS_NAME", config.Information.PlatformName.to_string()); + Environment.SetEnvironmentVariable("OS_PLATFORM", config.Information.PlatformType.DescriptionOrValue()); + Environment.SetEnvironmentVariable("OS_VERSION", config.Information.PlatformVersion.ToStringSafe()); + Environment.SetEnvironmentVariable("OS_NAME", config.Information.PlatformName.ToStringSafe()); // experimental until we know if this value returns correctly based on the OS and not the current process. Environment.SetEnvironmentVariable("OS_IS64BIT", config.Information.Is64BitOperatingSystem ? "true" : "false"); Environment.SetEnvironmentVariable("PROCESS_IS64BIT", config.Information.Is64BitProcess ? "true" : "false"); @@ -92,11 +92,11 @@ public static void set_environment_variables(ChocolateyConfiguration config) if (config.Features.AllowEmptyChecksums) Environment.SetEnvironmentVariable(ApplicationParameters.Environment.ChocolateyAllowEmptyChecksums, "true"); if (config.Features.AllowEmptyChecksumsSecure) Environment.SetEnvironmentVariable(ApplicationParameters.Environment.ChocolateyAllowEmptyChecksumsSecure, "true"); - Environment.SetEnvironmentVariable("chocolateyRequestTimeout", config.WebRequestTimeoutSeconds.to_string() + "000"); + Environment.SetEnvironmentVariable("chocolateyRequestTimeout", config.WebRequestTimeoutSeconds.ToStringSafe() + "000"); if (config.CommandExecutionTimeoutSeconds != 0) { - Environment.SetEnvironmentVariable("chocolateyResponseTimeout", config.CommandExecutionTimeoutSeconds.to_string() + "000"); + Environment.SetEnvironmentVariable("chocolateyResponseTimeout", config.CommandExecutionTimeoutSeconds.ToStringSafe() + "000"); } if (!string.IsNullOrWhiteSpace(config.Proxy.Location)) @@ -106,14 +106,14 @@ public static void set_environment_variables(ChocolateyConfiguration config) !string.IsNullOrWhiteSpace(config.Proxy.EncryptedPassword) ) { - proxyCreds = "{0}:{1}@".format_with(config.Proxy.User, NugetEncryptionUtility.DecryptString(config.Proxy.EncryptedPassword)); + proxyCreds = "{0}:{1}@".FormatWith(config.Proxy.User, NugetEncryptionUtility.DecryptString(config.Proxy.EncryptedPassword)); Environment.SetEnvironmentVariable("chocolateyProxyUser", config.Proxy.User); Environment.SetEnvironmentVariable("chocolateyProxyPassword", NugetEncryptionUtility.DecryptString(config.Proxy.EncryptedPassword)); } - Environment.SetEnvironmentVariable("http_proxy", "{0}{1}".format_with(proxyCreds, config.Proxy.Location)); - Environment.SetEnvironmentVariable("https_proxy", "{0}{1}".format_with(proxyCreds, config.Proxy.Location)); + Environment.SetEnvironmentVariable("http_proxy", "{0}{1}".FormatWith(proxyCreds, config.Proxy.Location)); + Environment.SetEnvironmentVariable("https_proxy", "{0}{1}".FormatWith(proxyCreds, config.Proxy.Location)); Environment.SetEnvironmentVariable("chocolateyProxyLocation", config.Proxy.Location); if (!string.IsNullOrWhiteSpace(config.Proxy.BypassList)) @@ -129,16 +129,16 @@ public static void set_environment_variables(ChocolateyConfiguration config) if (config.Features.UsePowerShellHost) Environment.SetEnvironmentVariable(ApplicationParameters.Environment.ChocolateyPowerShellHost, "true"); if (config.Force) Environment.SetEnvironmentVariable(ApplicationParameters.Environment.ChocolateyForce, "true"); if (config.Features.ExitOnRebootDetected) Environment.SetEnvironmentVariable(ApplicationParameters.Environment.ChocolateyExitOnRebootDetected, "true"); - set_licensed_environment(config); + SetLicensedEnvironment(config); } - private static void set_licensed_environment(ChocolateyConfiguration config) + private static void SetLicensedEnvironment(ChocolateyConfiguration config) { if (!config.Information.IsLicensedVersion) return; Environment.SetEnvironmentVariable("ChocolateyLicenseType", config.Information.LicenseType); - var licenseAssembly = AppDomain.CurrentDomain.GetAssemblies().FirstOrDefault(a => a.GetName().Name.is_equal_to("chocolatey.licensed")); + var licenseAssembly = AppDomain.CurrentDomain.GetAssemblies().FirstOrDefault(a => a.GetName().Name.IsEqualTo("chocolatey.licensed")); if (licenseAssembly != null) { @@ -156,7 +156,7 @@ private static void set_licensed_environment(ChocolateyConfiguration config) object componentClass = Activator.CreateInstance(licensedEnvironmentSettings); licensedEnvironmentSettings.InvokeMember( - SET_ENVIRONMENT_METHOD, + SetEnvironmentMethod, BindingFlags.InvokeMethod, null, componentClass, @@ -165,18 +165,18 @@ private static void set_licensed_environment(ChocolateyConfiguration config) } catch (Exception ex) { - var isDebug = ApplicationParameters.is_debug_mode_cli_primitive(); + var isDebug = ApplicationParameters.IsDebugModeCliPrimitive(); if (config.Debug) isDebug = true; var message = isDebug ? ex.ToString() : ex.Message; if (isDebug && ex.InnerException != null) { - message += "{0}{1}".format_with(Environment.NewLine, ex.InnerException.ToString()); + message += "{0}{1}".FormatWith(Environment.NewLine, ex.InnerException.ToString()); } "chocolatey".Log().Error( ChocolateyLoggers.Important, - @"Error when setting environment for '{0}':{1} {2}".format_with( + @"Error when setting environment for '{0}':{1} {2}".FormatWith( licensedEnvironmentSettings.FullName, Environment.NewLine, message @@ -193,28 +193,28 @@ private static void set_licensed_environment(ChocolateyConfiguration config) /// This does not remove environment variables, but will ensure all updates are shown. /// To see actual update with removed variables, one will need to restart a shell. /// - public static void update_environment_variables() + public static void UpdateEnvironmentVariables() { // grab original values - var originalEnvironmentVariables = convert_to_case_insensitive_dictionary(Environment.GetEnvironmentVariables(EnvironmentVariableTarget.Process)); - var userName = originalEnvironmentVariables[ApplicationParameters.Environment.Username].to_string(); - var architecture = originalEnvironmentVariables[ApplicationParameters.Environment.ProcessorArchitecture].to_string(); + var originalEnvironmentVariables = ConvertToCaseInsensitiveDictionary(Environment.GetEnvironmentVariables(EnvironmentVariableTarget.Process)); + var userName = originalEnvironmentVariables[ApplicationParameters.Environment.Username].ToStringSafe(); + var architecture = originalEnvironmentVariables[ApplicationParameters.Environment.ProcessorArchitecture].ToStringSafe(); var originalPath = originalEnvironmentVariables[ApplicationParameters.Environment.Path] - .to_string() + .ToStringSafe() .Split(new[] { ApplicationParameters.Environment.EnvironmentSeparator }, StringSplitOptions.RemoveEmptyEntries); var originalPathExt = originalEnvironmentVariables[ApplicationParameters.Environment.PathExtensions] - .to_string() + .ToStringSafe() .Split(new[] { ApplicationParameters.Environment.EnvironmentSeparator }, StringSplitOptions.RemoveEmptyEntries); var originalPsModulePath = originalEnvironmentVariables[ApplicationParameters.Environment.PsModulePath] - .to_string() + .ToStringSafe() .Split(new[] { ApplicationParameters.Environment.EnvironmentSeparator }, StringSplitOptions.RemoveEmptyEntries); // get updated values from the registry - var machineVariables = convert_to_case_insensitive_dictionary(Environment.GetEnvironmentVariables(EnvironmentVariableTarget.Machine)); - var userVariables = convert_to_case_insensitive_dictionary(Environment.GetEnvironmentVariables(EnvironmentVariableTarget.User)); + var machineVariables = ConvertToCaseInsensitiveDictionary(Environment.GetEnvironmentVariables(EnvironmentVariableTarget.Machine)); + var userVariables = ConvertToCaseInsensitiveDictionary(Environment.GetEnvironmentVariables(EnvironmentVariableTarget.User)); // refresh current values with updated values, machine first - refresh_environment_variables(machineVariables); + RefreshEnvironmentVariables(machineVariables); //if the user is SYSTEM, we should not even look at user Variables var setUserEnvironmentVariables = true; @@ -228,42 +228,42 @@ public static void update_environment_variables() } catch (Exception ex) { - "chocolatey".Log().Debug("Unable to determine current user to determine if LocalSystem account (to skip user env vars).{0} Reported error: {1}".format_with(Environment.NewLine, ex.Message)); + "chocolatey".Log().Debug("Unable to determine current user to determine if LocalSystem account (to skip user env vars).{0} Reported error: {1}".FormatWith(Environment.NewLine, ex.Message)); } - if (setUserEnvironmentVariables) refresh_environment_variables(userVariables); + if (setUserEnvironmentVariables) RefreshEnvironmentVariables(userVariables); // restore process overridden variables if (originalEnvironmentVariables.Contains(ApplicationParameters.Environment.Username)) Environment.SetEnvironmentVariable(ApplicationParameters.Environment.Username, userName); if (originalEnvironmentVariables.Contains(ApplicationParameters.Environment.ProcessorArchitecture)) Environment.SetEnvironmentVariable(ApplicationParameters.Environment.ProcessorArchitecture, architecture); // combine environment values that append together - var updatedPath = "{0};{1};".format_with( - machineVariables[ApplicationParameters.Environment.Path].to_string(), - userVariables[ApplicationParameters.Environment.Path].to_string() + var updatedPath = "{0};{1};".FormatWith( + machineVariables[ApplicationParameters.Environment.Path].ToStringSafe(), + userVariables[ApplicationParameters.Environment.Path].ToStringSafe() ).Replace(";;", ";"); - var updatedPathExt = "{0};{1};".format_with( - machineVariables[ApplicationParameters.Environment.PathExtensions].to_string(), - userVariables[ApplicationParameters.Environment.PathExtensions].to_string() + var updatedPathExt = "{0};{1};".FormatWith( + machineVariables[ApplicationParameters.Environment.PathExtensions].ToStringSafe(), + userVariables[ApplicationParameters.Environment.PathExtensions].ToStringSafe() ).Replace(";;", ";"); - var updatedPsModulePath = "{0};{1};".format_with( - userVariables[ApplicationParameters.Environment.PsModulePath].to_string(), - machineVariables[ApplicationParameters.Environment.PsModulePath].to_string() + var updatedPsModulePath = "{0};{1};".FormatWith( + userVariables[ApplicationParameters.Environment.PsModulePath].ToStringSafe(), + machineVariables[ApplicationParameters.Environment.PsModulePath].ToStringSafe() ).Replace(";;", ";"); // add back in process items - updatedPath += gather_process_only_items(updatedPath, originalPath); - updatedPathExt += gather_process_only_items(updatedPathExt, originalPathExt); - updatedPsModulePath = "{0};{1}".format_with(gather_process_only_items(updatedPsModulePath, originalPsModulePath),updatedPsModulePath); + updatedPath += GetProcessOnlyItems(updatedPath, originalPath); + updatedPathExt += GetProcessOnlyItems(updatedPathExt, originalPathExt); + updatedPsModulePath = "{0};{1}".FormatWith(GetProcessOnlyItems(updatedPsModulePath, originalPsModulePath),updatedPsModulePath); - if (!updatedPsModulePath.contains(ApplicationParameters.PowerShellModulePathProcessProgramFiles)) + if (!updatedPsModulePath.ContainsSafe(ApplicationParameters.PowerShellModulePathProcessProgramFiles)) { - updatedPsModulePath = "{0};{1}".format_with(ApplicationParameters.PowerShellModulePathProcessProgramFiles, updatedPsModulePath).Replace(";;", ";"); + updatedPsModulePath = "{0};{1}".FormatWith(ApplicationParameters.PowerShellModulePathProcessProgramFiles, updatedPsModulePath).Replace(";;", ";"); } - if (!updatedPsModulePath.contains(ApplicationParameters.PowerShellModulePathProcessDocuments)) + if (!updatedPsModulePath.ContainsSafe(ApplicationParameters.PowerShellModulePathProcessDocuments)) { - updatedPsModulePath = "{0};{1}".format_with(ApplicationParameters.PowerShellModulePathProcessDocuments, updatedPsModulePath).Replace(";;", ";"); + updatedPsModulePath = "{0};{1}".FormatWith(ApplicationParameters.PowerShellModulePathProcessDocuments, updatedPsModulePath).Replace(";;", ";"); } if (updatedPsModulePath.StartsWith(";")) @@ -276,22 +276,22 @@ public static void update_environment_variables() Environment.SetEnvironmentVariable(ApplicationParameters.Environment.PsModulePath, updatedPsModulePath); } - private static IDictionary convert_to_case_insensitive_dictionary(IDictionary originalDictionary) + private static IDictionary ConvertToCaseInsensitiveDictionary(IDictionary originalDictionary) { if (originalDictionary == null) return new Hashtable(new Dictionary(), StringComparer.OrdinalIgnoreCase); return new Hashtable(originalDictionary, StringComparer.OrdinalIgnoreCase); } - private static void refresh_environment_variables(IDictionary environmentVariables) + private static void RefreshEnvironmentVariables(IDictionary environmentVariables) { - foreach (DictionaryEntry variable in environmentVariables.or_empty_list_if_null()) + foreach (DictionaryEntry variable in environmentVariables.OrEmpty()) { - Environment.SetEnvironmentVariable(variable.Key.to_string(), variable.Value.to_string()); + Environment.SetEnvironmentVariable(variable.Key.ToStringSafe(), variable.Value.ToStringSafe()); } } - private static string gather_process_only_items(string currentValues, IEnumerable originalValues) + private static string GetProcessOnlyItems(string currentValues, IEnumerable originalValues) { var additionalItems = new StringBuilder(); var items = currentValues.Split( @@ -299,7 +299,7 @@ private static string gather_process_only_items(string currentValues, IEnumerabl StringSplitOptions.RemoveEmptyEntries ); - foreach (string originalValue in originalValues.or_empty_list_if_null()) + foreach (string originalValue in originalValues.OrEmpty()) { if (!items.Contains(originalValue, StringComparer.InvariantCultureIgnoreCase)) { @@ -307,7 +307,26 @@ private static string gather_process_only_items(string currentValues, IEnumerabl } } - return additionalItems.to_string(); + return additionalItems.ToStringSafe(); } + +#pragma warning disable IDE1006 + [Obsolete("This overload is deprecated and will be removed in v3.")] + [EditorBrowsable(EditorBrowsableState.Never)] + public static void initialize_with(Lazy environment) + => InitializeWith(environment); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public static void reset_environment_variables(ChocolateyConfiguration config) + => ResetEnvironmentVariables(config); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public static void set_environment_variables(ChocolateyConfiguration config) + => SetEnvironmentVariables(config); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public static void update_environment_variables() + => UpdateEnvironmentVariables(); +#pragma warning restore IDE1006 } } diff --git a/src/chocolatey/infrastructure.app/domain/ChocolateyPackageMetadata.cs b/src/chocolatey/infrastructure.app/domain/ChocolateyPackageMetadata.cs index 0b11d08544..2ec61e67f5 100644 --- a/src/chocolatey/infrastructure.app/domain/ChocolateyPackageMetadata.cs +++ b/src/chocolatey/infrastructure.app/domain/ChocolateyPackageMetadata.cs @@ -68,7 +68,7 @@ public ChocolateyPackageMetadata(NuspecReader reader) public ChocolateyPackageMetadata(string packagePath, IFileSystem filesystem) { - if (filesystem.get_file_extension(packagePath) == NuGetConstants.PackageExtension) + if (filesystem.GetFileExtension(packagePath) == NuGetConstants.PackageExtension) { using (var archiveReader = new PackageArchiveReader(packagePath)) { @@ -110,7 +110,7 @@ public ChocolateyPackageMetadata(string packagePath, IFileSystem filesystem) FrameworkReferenceGroups = reader.GetFrameworkRefGroups(); } } - else if (filesystem.get_file_extension(packagePath) == NuGetConstants.ManifestExtension) + else if (filesystem.GetFileExtension(packagePath) == NuGetConstants.ManifestExtension) { var reader = new NuspecReader(packagePath); diff --git a/src/chocolatey/infrastructure.app/domain/CommandNameType.cs b/src/chocolatey/infrastructure.app/domain/CommandNameType.cs index e4a15492dc..55a9d6f7fb 100644 --- a/src/chocolatey/infrastructure.app/domain/CommandNameType.cs +++ b/src/chocolatey/infrastructure.app/domain/CommandNameType.cs @@ -16,11 +16,24 @@ namespace chocolatey.infrastructure.app.domain { + using System; + public enum CommandNameType { - list, - install, - upgrade, - uninstall, + List, + Install, + Upgrade, + Uninstall, + +#pragma warning disable IDE1006 + [Obsolete("This overload is deprecated and will be removed in v3.")] + list = List, + [Obsolete("This overload is deprecated and will be removed in v3.")] + install = Install, + [Obsolete("This overload is deprecated and will be removed in v3.")] + upgrade = Upgrade, + [Obsolete("This overload is deprecated and will be removed in v3.")] + uninstall = Uninstall, +#pragma warning restore IDE1006 } } diff --git a/src/chocolatey/infrastructure.app/domain/ConfigCommandType.cs b/src/chocolatey/infrastructure.app/domain/ConfigCommandType.cs index 595aa89ec5..b82ef2d17b 100644 --- a/src/chocolatey/infrastructure.app/domain/ConfigCommandType.cs +++ b/src/chocolatey/infrastructure.app/domain/ConfigCommandType.cs @@ -16,12 +16,27 @@ namespace chocolatey.infrastructure.app.domain { + using System; + public enum ConfigCommandType { - unknown, - list, - get, - set, - unset, + Unknown, + List, + Get, + Set, + Unset, + +#pragma warning disable IDE1006 + [Obsolete("This overload is deprecated and will be removed in v3.")] + unknown = Unknown, + [Obsolete("This overload is deprecated and will be removed in v3.")] + list = List, + [Obsolete("This overload is deprecated and will be removed in v3.")] + get = Get, + [Obsolete("This overload is deprecated and will be removed in v3.")] + set = Set, + [Obsolete("This overload is deprecated and will be removed in v3.")] + unset = Unset, +#pragma warning restore IDE1006 } } diff --git a/src/chocolatey/infrastructure.app/domain/FeatureCommandType.cs b/src/chocolatey/infrastructure.app/domain/FeatureCommandType.cs index fcbe4f274a..f91ac060b4 100644 --- a/src/chocolatey/infrastructure.app/domain/FeatureCommandType.cs +++ b/src/chocolatey/infrastructure.app/domain/FeatureCommandType.cs @@ -16,11 +16,25 @@ namespace chocolatey.infrastructure.app.domain { + using System; + public enum FeatureCommandType { - unknown, - list, - enable, - disable, + Unknown, + List, + Get, + Enable, + Disable, + +#pragma warning disable IDE1006 + [Obsolete("This overload is deprecated and will be removed in v3.")] + unknown = Unknown, + [Obsolete("This overload is deprecated and will be removed in v3.")] + list = List, + [Obsolete("This overload is deprecated and will be removed in v3.")] + enable = Enable, + [Obsolete("This overload is deprecated and will be removed in v3.")] + disable = Disable, +#pragma warning restore IDE1006 } } diff --git a/src/chocolatey/infrastructure.app/domain/GenericRegistryValue.cs b/src/chocolatey/infrastructure.app/domain/GenericRegistryValue.cs index ab36793def..b428968ad1 100644 --- a/src/chocolatey/infrastructure.app/domain/GenericRegistryValue.cs +++ b/src/chocolatey/infrastructure.app/domain/GenericRegistryValue.cs @@ -42,10 +42,10 @@ bool IEquatable.Equals(GenericRegistryValue other) { if (other == null) return false; - return ParentKeyName.is_equal_to(other.ParentKeyName) - && Name.is_equal_to(other.Name) - && Value.is_equal_to(other.Value) - && Type.to_string().is_equal_to(other.Type.to_string()) + return ParentKeyName.IsEqualTo(other.ParentKeyName) + && Name.IsEqualTo(other.Name) + && Value.IsEqualTo(other.Value) + && Type.ToStringSafe().IsEqualTo(other.Type.ToStringSafe()) ; } } diff --git a/src/chocolatey/infrastructure.app/domain/InstallTokens.cs b/src/chocolatey/infrastructure.app/domain/InstallTokens.cs index 18f43fd3e1..a72bc64045 100644 --- a/src/chocolatey/infrastructure.app/domain/InstallTokens.cs +++ b/src/chocolatey/infrastructure.app/domain/InstallTokens.cs @@ -16,13 +16,30 @@ namespace chocolatey.infrastructure.app.domain { + using System; + public static class InstallTokens { - public const string INSTALLER_LOCATION = "{{INSTALLER_LOCATION}}"; - public const string CUSTOM_INSTALL_LOCATION = "{{CUSTOM_INSTALL_LOCATION}}"; - public const string PACKAGE_LOCATION = "{{PACKAGE_LOCATION}}"; - public const string LANGUAGE = "{{LANGUAGE}}"; - public const string UNINSTALLER_LOCATION = "{{UNINSTALLER_LOCATION}}"; - public const string TEMP_LOCATION = "{{TEMP_LOCATION}}"; + public const string InstallerLocation = "{{INSTALLER_LOCATION}}"; + public const string CustomInstallLocation = "{{CUSTOM_INSTALL_LOCATION}}"; + public const string PackageLocation = "{{PACKAGE_LOCATION}}"; + public const string Language = "{{LANGUAGE}}"; + public const string UninstallerLocation = "{{UNINSTALLER_LOCATION}}"; + public const string TempLocation = "{{TEMP_LOCATION}}"; + +#pragma warning disable IDE1006 + [Obsolete("This overload is deprecated and will be removed in v3.")] + public const string INSTALLER_LOCATION = InstallerLocation; + [Obsolete("This overload is deprecated and will be removed in v3.")] + public const string CUSTOM_INSTALL_LOCATION = CustomInstallLocation; + [Obsolete("This overload is deprecated and will be removed in v3.")] + public const string PACKAGE_LOCATION = PackageLocation; + [Obsolete("This overload is deprecated and will be removed in v3.")] + public const string LANGUAGE = Language; + [Obsolete("This overload is deprecated and will be removed in v3.")] + public const string UNINSTALLER_LOCATION = UninstallerLocation; + [Obsolete("This overload is deprecated and will be removed in v3.")] + public const string TEMP_LOCATION = TempLocation; +#pragma warning restore IDE1006 } } diff --git a/src/chocolatey/infrastructure.app/domain/PinCommandType.cs b/src/chocolatey/infrastructure.app/domain/PinCommandType.cs index 61fdae0ce8..92aa9b4ff2 100644 --- a/src/chocolatey/infrastructure.app/domain/PinCommandType.cs +++ b/src/chocolatey/infrastructure.app/domain/PinCommandType.cs @@ -16,11 +16,24 @@ namespace chocolatey.infrastructure.app.domain { + using System; + public enum PinCommandType { - unknown, - list, - add, - remove, + Unknown, + List, + Add, + Remove, + +#pragma warning disable IDE1006 + [Obsolete("This overload is deprecated and will be removed in v3.")] + unknown = Unknown, + [Obsolete("This overload is deprecated and will be removed in v3.")] + list = List, + [Obsolete("This overload is deprecated and will be removed in v3.")] + add = Add, + [Obsolete("This overload is deprecated and will be removed in v3.")] + remove = Remove, +#pragma warning restore IDE1006 } } diff --git a/src/chocolatey/infrastructure.app/domain/RegistryApplicationKey.cs b/src/chocolatey/infrastructure.app/domain/RegistryApplicationKey.cs index 6cd46ea625..dc49cef296 100644 --- a/src/chocolatey/infrastructure.app/domain/RegistryApplicationKey.cs +++ b/src/chocolatey/infrastructure.app/domain/RegistryApplicationKey.cs @@ -74,10 +74,10 @@ public class RegistryApplicationKey : IEquatable /// /// http://community.spiceworks.com/how_to/show/2238-how-add-remove-programs-works /// - public bool is_in_programs_and_features() + public bool IsInProgramsAndFeatures() { return !string.IsNullOrWhiteSpace(DisplayName) - && !string.IsNullOrWhiteSpace(UninstallString.to_string()) + && !string.IsNullOrWhiteSpace(UninstallString.ToStringSafe()) && InstallerType != InstallerType.HotfixOrSecurityUpdate && InstallerType != InstallerType.ServicePack && string.IsNullOrWhiteSpace(ParentKeyName) @@ -88,7 +88,7 @@ public bool is_in_programs_and_features() public override string ToString() { - return "{0}|{1}|{2}|{3}|{4}".format_with( + return "{0}|{1}|{2}|{3}|{4}".FormatWith( DisplayName, DisplayVersion, InstallerType, @@ -101,7 +101,7 @@ public override int GetHashCode() { return DisplayName.GetHashCode() & DisplayVersion.GetHashCode() - & UninstallString.to_string().GetHashCode() + & UninstallString.ToStringSafe().GetHashCode() & KeyPath.GetHashCode(); } @@ -116,11 +116,17 @@ bool IEquatable.Equals(RegistryApplicationKey other) { if (ReferenceEquals(other, null)) return false; - return DisplayName.to_string().is_equal_to(other.DisplayName) - && DisplayVersion.is_equal_to(other.DisplayVersion) - && UninstallString.to_string().is_equal_to(other.UninstallString.to_string()) - && KeyPath.is_equal_to(other.KeyPath) + return DisplayName.ToStringSafe().IsEqualTo(other.DisplayName) + && DisplayVersion.IsEqualTo(other.DisplayVersion) + && UninstallString.ToStringSafe().IsEqualTo(other.UninstallString.ToStringSafe()) + && KeyPath.IsEqualTo(other.KeyPath) ; } + +#pragma warning disable IDE1006 + [Obsolete("This overload is deprecated and will be removed in v3.")] + public bool is_in_programs_and_features() + => IsInProgramsAndFeatures(); +#pragma warning restore IDE1006 } } diff --git a/src/chocolatey/infrastructure.app/domain/RegistryValueExtensions.cs b/src/chocolatey/infrastructure.app/domain/RegistryValueExtensions.cs index 2f29afd95a..7a3f6e1860 100644 --- a/src/chocolatey/infrastructure.app/domain/RegistryValueExtensions.cs +++ b/src/chocolatey/infrastructure.app/domain/RegistryValueExtensions.cs @@ -16,22 +16,29 @@ namespace chocolatey.infrastructure.app.domain { + using System; using System.Security; using Microsoft.Win32; public static class RegistryValueExtensions { - public static string get_value_as_string(this RegistryKey key, string name) + public static string AsXmlSafeString(this RegistryKey key, string name) { if (key == null) return string.Empty; // Since it is possible that registry keys contain characters that are not valid // in XML files, ensure that all content is escaped, prior to serialization // https://docs.microsoft.com/en-us/dotnet/api/system.security.securityelement.escape?view=netframework-4.0 - return SecurityElement.Escape(key.GetValue(name).to_string()).to_string() + return SecurityElement.Escape(key.GetValue(name).ToStringSafe()).ToStringSafe() .Replace(""", "\"") .Replace("'", "'") .Replace("\0", string.Empty); } + +#pragma warning disable IDE1006 + [Obsolete("This overload is deprecated and will be removed in v3.")] + public static string get_value_as_string(this RegistryKey key, string name) + => AsXmlSafeString(key, name); +#pragma warning restore IDE1006 } } diff --git a/src/chocolatey/infrastructure.app/domain/SourceCommandType.cs b/src/chocolatey/infrastructure.app/domain/SourceCommandType.cs index cde21aa854..a8020de803 100644 --- a/src/chocolatey/infrastructure.app/domain/SourceCommandType.cs +++ b/src/chocolatey/infrastructure.app/domain/SourceCommandType.cs @@ -16,13 +16,30 @@ namespace chocolatey.infrastructure.app.domain { + using System; + public enum SourceCommandType { - unknown, - list, - add, - remove, - enable, - disable, + Unknown, + List, + Add, + Remove, + Enable, + Disable, + +#pragma warning disable IDE1006 + [Obsolete("This overload is deprecated and will be removed in v3.")] + unknown = Unknown, + [Obsolete("This overload is deprecated and will be removed in v3.")] + list = List, + [Obsolete("This overload is deprecated and will be removed in v3.")] + add = Add, + [Obsolete("This overload is deprecated and will be removed in v3.")] + remove = Remove, + [Obsolete("This overload is deprecated and will be removed in v3.")] + enable = Enable, + [Obsolete("This overload is deprecated and will be removed in v3.")] + disable = Disable, +#pragma warning restore IDE1006 } } diff --git a/src/chocolatey/infrastructure.app/domain/SourceType.cs b/src/chocolatey/infrastructure.app/domain/SourceType.cs index 66dc5af681..a9beab9cb0 100644 --- a/src/chocolatey/infrastructure.app/domain/SourceType.cs +++ b/src/chocolatey/infrastructure.app/domain/SourceType.cs @@ -25,11 +25,11 @@ namespace chocolatey.infrastructure.app.domain public enum SourceType { //this is what it should be when it's not set - normal, - ruby, - python, - windowsfeature, - windowsfeatures, - cygwin, + Normal, + Ruby, + Python, + WindowsFeature, + WindowsFeatures, + Cygwin, } } diff --git a/src/chocolatey/infrastructure.app/domain/SourceTypes.cs b/src/chocolatey/infrastructure.app/domain/SourceTypes.cs index fcbaf44b74..8299e528fc 100644 --- a/src/chocolatey/infrastructure.app/domain/SourceTypes.cs +++ b/src/chocolatey/infrastructure.app/domain/SourceTypes.cs @@ -29,35 +29,50 @@ public static class SourceTypes /// The source is of type Cygwin and need to be handled by an /// alternative source runner. /// - public const string CYGWIN = "cygwin"; + public const string Cygwin = "cygwin"; /// /// The source is a normal type, ie a chocolatey/nuget source. /// - public const string NORMAL = "normal"; + public const string Normal = "normal"; /// /// The source is of type Python and need to be handled by an /// alternative source runner. /// - public const string PYTHON = "python"; + public const string Python = "python"; /// /// The source is of type Ruby and need to be handled by an /// alternative source runner. /// - public const string RUBY = "ruby"; + public const string Ruby = "ruby"; /// /// The source is a windows feature and is only provided as an - /// alias for + /// alias for /// - public const string WINDOWS_FEATURE = "windowsfeature"; + public const string WindowsFeature = "windowsfeature"; /// /// The source is a windows feature and need to be handled by an /// alternative source runner. /// - public const string WINDOWS_FEATURES = "windowsfeatures"; + public const string WindowsFeatures = "windowsfeatures"; + +#pragma warning disable IDE1006 + [Obsolete("This overload is deprecated and will be removed in v3.")] + public const string CYGWIN = Cygwin; + [Obsolete("This overload is deprecated and will be removed in v3.")] + public const string NORMAL = Normal; + [Obsolete("This overload is deprecated and will be removed in v3.")] + public const string PYTHON = Python; + [Obsolete("This overload is deprecated and will be removed in v3.")] + public const string RUBY = Ruby; + [Obsolete("This overload is deprecated and will be removed in v3.")] + public const string WINDOWS_FEATURE = WindowsFeature; + [Obsolete("This overload is deprecated and will be removed in v3.")] + public const string WINDOWS_FEATURES = WindowsFeatures; +#pragma warning restore IDE1006 } } diff --git a/src/chocolatey/infrastructure.app/domain/TemplateCommandType.cs b/src/chocolatey/infrastructure.app/domain/TemplateCommandType.cs index c6124612d2..38b0321b63 100644 --- a/src/chocolatey/infrastructure.app/domain/TemplateCommandType.cs +++ b/src/chocolatey/infrastructure.app/domain/TemplateCommandType.cs @@ -16,10 +16,21 @@ namespace chocolatey.infrastructure.app.domain { + using System; + public enum TemplateCommandType { - unknown, - list, - info + Unknown, + List, + Info, + +#pragma warning disable IDE1006 + [Obsolete("This overload is deprecated and will be removed in v3.")] + unknown = Unknown, + [Obsolete("This overload is deprecated and will be removed in v3.")] + list = List, + [Obsolete("This overload is deprecated and will be removed in v3.")] + info = Info, +#pragma warning restore IDE1006 } } diff --git a/src/chocolatey/infrastructure.app/domain/installers/BitRockInstaller.cs b/src/chocolatey/infrastructure.app/domain/installers/BitRockInstaller.cs index 7ec5908f7d..49fb3f8cec 100644 --- a/src/chocolatey/infrastructure.app/domain/installers/BitRockInstaller.cs +++ b/src/chocolatey/infrastructure.app/domain/installers/BitRockInstaller.cs @@ -30,17 +30,17 @@ public class BitRockInstaller : InstallerBase { public BitRockInstaller() { - InstallExecutable = "\"{0}\"".format_with(InstallTokens.INSTALLER_LOCATION); + InstallExecutable = "\"{0}\"".FormatWith(InstallTokens.InstallerLocation); SilentInstall = "--mode unattended"; // http://answers.bitrock.com/questions/215/how-can-i-restart-the-computer-after-installation-has-completed NoReboot = ""; LogFile = ""; // http://installbuilder.bitrock.com/docs/installbuilder-userguide.html#_command_line_parameters // http://answers.bitrock.com/questions/57/how-do-i-specify-a-different-default-installation-directory-for-unix-and-windows - CustomInstallLocation = "--installdir {0}".format_with(InstallTokens.CUSTOM_INSTALL_LOCATION); + CustomInstallLocation = "--installdir {0}".FormatWith(InstallTokens.CustomInstallLocation); Language = ""; OtherInstallOptions = "--unattendedmodeui none"; - UninstallExecutable = "\"{0}\"".format_with(InstallTokens.UNINSTALLER_LOCATION); + UninstallExecutable = "\"{0}\"".FormatWith(InstallTokens.UninstallerLocation); SilentUninstall = "--mode unattended"; OtherUninstallOptions = "--unattendedmodeui none"; ValidInstallExitCodes = new List diff --git a/src/chocolatey/infrastructure.app/domain/installers/CustomInstaller.cs b/src/chocolatey/infrastructure.app/domain/installers/CustomInstaller.cs index 1571520aa9..be9c4c351d 100644 --- a/src/chocolatey/infrastructure.app/domain/installers/CustomInstaller.cs +++ b/src/chocolatey/infrastructure.app/domain/installers/CustomInstaller.cs @@ -16,20 +16,21 @@ namespace chocolatey.infrastructure.app.domain.installers { + using System; using System.Collections.Generic; public class CustomInstaller : InstallerBase { public CustomInstaller() { - InstallExecutable = "\"{0}\"".format_with(InstallTokens.INSTALLER_LOCATION); + InstallExecutable = "\"{0}\"".FormatWith(InstallTokens.InstallerLocation); SilentInstall = "/S"; NoReboot = ""; LogFile = ""; CustomInstallLocation = ""; Language = ""; OtherInstallOptions = ""; - UninstallExecutable = "\"{0}\"".format_with(InstallTokens.UNINSTALLER_LOCATION); + UninstallExecutable = "\"{0}\"".FormatWith(InstallTokens.UninstallerLocation); SilentUninstall = "/S"; OtherUninstallOptions = ""; ValidInstallExitCodes = new List { 0 }; @@ -41,7 +42,7 @@ public override InstallerType InstallerType get { return InstallerType.Custom; } } - public override string build_install_command_arguments(bool logFile, bool customInstallLocation, bool languageRequested) + public override string BuildInstallCommandArguments(bool logFile, bool customInstallLocation, bool languageRequested) { if (customInstallLocation) this.Log().Warn("CustomInstaller doesn't support custom install locations."); if (languageRequested) this.Log().Warn("CustomInstaller doesn't support custom language options."); @@ -49,7 +50,7 @@ public override string build_install_command_arguments(bool logFile, bool custom return string.Empty; } - public override string build_uninstall_command_arguments() + public override string BuildUninstallCommandArguments() { return string.Empty; } diff --git a/src/chocolatey/infrastructure.app/domain/installers/GhostInstaller.cs b/src/chocolatey/infrastructure.app/domain/installers/GhostInstaller.cs index 4abdf41202..dfd05ade8f 100644 --- a/src/chocolatey/infrastructure.app/domain/installers/GhostInstaller.cs +++ b/src/chocolatey/infrastructure.app/domain/installers/GhostInstaller.cs @@ -30,14 +30,14 @@ public class GhostInstaller : InstallerBase { public GhostInstaller() { - InstallExecutable = "\"{0}\"".format_with(InstallTokens.INSTALLER_LOCATION); + InstallExecutable = "\"{0}\"".FormatWith(InstallTokens.InstallerLocation); SilentInstall = "-s"; NoReboot = ""; LogFile = ""; CustomInstallLocation = ""; Language = ""; OtherInstallOptions = ""; - UninstallExecutable = "\"{0}\"".format_with(InstallTokens.UNINSTALLER_LOCATION); + UninstallExecutable = "\"{0}\"".FormatWith(InstallTokens.UninstallerLocation); SilentUninstall = "-u -s"; OtherUninstallOptions = ""; ValidInstallExitCodes = new List { 0 }; diff --git a/src/chocolatey/infrastructure.app/domain/installers/IInstaller.cs b/src/chocolatey/infrastructure.app/domain/installers/IInstaller.cs index 629700ed18..785e5671ed 100644 --- a/src/chocolatey/infrastructure.app/domain/installers/IInstaller.cs +++ b/src/chocolatey/infrastructure.app/domain/installers/IInstaller.cs @@ -16,6 +16,7 @@ namespace chocolatey.infrastructure.app.domain.installers { + using System; using System.Collections.Generic; public interface IInstaller @@ -34,7 +35,15 @@ public interface IInstaller IEnumerable ValidInstallExitCodes { get; } IEnumerable ValidUninstallExitCodes { get; } + string BuildInstallCommandArguments(bool logFile, bool customInstallLocation, bool languageRequested); + string BuildUninstallCommandArguments(); + +#pragma warning disable IDE1006 + [Obsolete("This overload is deprecated and will be removed in v3.")] string build_install_command_arguments(bool logFile, bool customInstallLocation, bool languageRequested); + + [Obsolete("This overload is deprecated and will be removed in v3.")] string build_uninstall_command_arguments(); +#pragma warning restore IDE1006 } } diff --git a/src/chocolatey/infrastructure.app/domain/installers/InnoSetupInstaller.cs b/src/chocolatey/infrastructure.app/domain/installers/InnoSetupInstaller.cs index f5d4fdcb2d..96ce3859c6 100644 --- a/src/chocolatey/infrastructure.app/domain/installers/InnoSetupInstaller.cs +++ b/src/chocolatey/infrastructure.app/domain/installers/InnoSetupInstaller.cs @@ -28,14 +28,14 @@ public class InnoSetupInstaller : InstallerBase { public InnoSetupInstaller() { - InstallExecutable = "\"{0}\" ".format_with(InstallTokens.INSTALLER_LOCATION); + InstallExecutable = "\"{0}\" ".FormatWith(InstallTokens.InstallerLocation); SilentInstall = "/VERYSILENT"; NoReboot = "/NORESTART /RESTARTEXITCODE=3010"; - LogFile = "/LOG=\"{0}\\InnoSetup.Install.log\"".format_with(InstallTokens.PACKAGE_LOCATION); - CustomInstallLocation = "/DIR=\"{0}\"".format_with(InstallTokens.CUSTOM_INSTALL_LOCATION); - Language = "/LANG={0}".format_with(InstallTokens.LANGUAGE); + LogFile = "/LOG=\"{0}\\InnoSetup.Install.log\"".FormatWith(InstallTokens.PackageLocation); + CustomInstallLocation = "/DIR=\"{0}\"".FormatWith(InstallTokens.CustomInstallLocation); + Language = "/LANG={0}".FormatWith(InstallTokens.Language); OtherInstallOptions = "/SP- /SUPPRESSMSGBOXES /CLOSEAPPLICATIONS /FORCECLOSEAPPLICATIONS /NOICONS"; - UninstallExecutable = "\"{0}\"".format_with(InstallTokens.UNINSTALLER_LOCATION); + UninstallExecutable = "\"{0}\"".FormatWith(InstallTokens.UninstallerLocation); SilentUninstall = "/VERYSILENT"; OtherUninstallOptions = "/SUPPRESSMSGBOXES"; // http://www.jrsoftware.org/ishelp/index.php?topic=setupexitcodes diff --git a/src/chocolatey/infrastructure.app/domain/installers/InstallForJInstaller.cs b/src/chocolatey/infrastructure.app/domain/installers/InstallForJInstaller.cs index a2f5b5436a..7136efcc01 100644 --- a/src/chocolatey/infrastructure.app/domain/installers/InstallForJInstaller.cs +++ b/src/chocolatey/infrastructure.app/domain/installers/InstallForJInstaller.cs @@ -30,14 +30,14 @@ public class InstallForJInstaller : InstallerBase { public InstallForJInstaller() { - InstallExecutable = "\"{0}\"".format_with(InstallTokens.INSTALLER_LOCATION); + InstallExecutable = "\"{0}\"".FormatWith(InstallTokens.InstallerLocation); SilentInstall = "-q"; NoReboot = ""; LogFile = ""; //logging is done automatically to i4j_nlog_* file in temp directory - http://resources.ej-technologies.com/install4j/help/doc/helptopics/installers/errors.html - CustomInstallLocation = "-dir \"{0}\"".format_with(InstallTokens.CUSTOM_INSTALL_LOCATION); + CustomInstallLocation = "-dir \"{0}\"".FormatWith(InstallTokens.CustomInstallLocation); Language = ""; OtherInstallOptions = "-overwrite"; // -wait 60 - UninstallExecutable = "\"{0}\"".format_with(InstallTokens.UNINSTALLER_LOCATION); + UninstallExecutable = "\"{0}\"".FormatWith(InstallTokens.UninstallerLocation); SilentUninstall = "-q"; OtherUninstallOptions = ""; ValidInstallExitCodes = new List diff --git a/src/chocolatey/infrastructure.app/domain/installers/InstallShieldInstaller.cs b/src/chocolatey/infrastructure.app/domain/installers/InstallShieldInstaller.cs index 23cb8679d0..d935eca87f 100644 --- a/src/chocolatey/infrastructure.app/domain/installers/InstallShieldInstaller.cs +++ b/src/chocolatey/infrastructure.app/domain/installers/InstallShieldInstaller.cs @@ -28,14 +28,14 @@ public class InstallShieldInstaller : InstallerBase { public InstallShieldInstaller() { - InstallExecutable = "\"{0}\"".format_with(InstallTokens.INSTALLER_LOCATION); + InstallExecutable = "\"{0}\"".FormatWith(InstallTokens.InstallerLocation); SilentInstall = "/s /v\"/qn\""; NoReboot = "/v\"REBOOT=ReallySuppress\""; - LogFile = "/f2\"{0}\\MSI.Install.log\"".format_with(InstallTokens.PACKAGE_LOCATION); - CustomInstallLocation = "/v\"INSTALLDIR=\\\"{0}\\\"".format_with(InstallTokens.CUSTOM_INSTALL_LOCATION); - Language = "/l\"{0}\"".format_with(InstallTokens.LANGUAGE); + LogFile = "/f2\"{0}\\MSI.Install.log\"".FormatWith(InstallTokens.PackageLocation); + CustomInstallLocation = "/v\"INSTALLDIR=\\\"{0}\\\"".FormatWith(InstallTokens.CustomInstallLocation); + Language = "/l\"{0}\"".FormatWith(InstallTokens.Language); OtherInstallOptions = "/sms"; // pause - UninstallExecutable = "\"{0}\"".format_with(InstallTokens.UNINSTALLER_LOCATION); + UninstallExecutable = "\"{0}\"".FormatWith(InstallTokens.UninstallerLocation); SilentUninstall = "/uninst /s"; OtherUninstallOptions = "/sms"; // http://helpnet.installshield.com/installshield18helplib/IHelpSetup_EXEErrors.htm diff --git a/src/chocolatey/infrastructure.app/domain/installers/InstallerBase.cs b/src/chocolatey/infrastructure.app/domain/installers/InstallerBase.cs index 82da0a37c8..8682e11c74 100644 --- a/src/chocolatey/infrastructure.app/domain/installers/InstallerBase.cs +++ b/src/chocolatey/infrastructure.app/domain/installers/InstallerBase.cs @@ -16,6 +16,7 @@ namespace chocolatey.infrastructure.app.domain.installers { + using System; using System.Collections.Generic; using System.Text; @@ -36,10 +37,10 @@ public abstract class InstallerBase : IInstaller public IEnumerable ValidInstallExitCodes { get; protected set; } public IEnumerable ValidUninstallExitCodes { get; protected set; } - public virtual string build_install_command_arguments(bool logFile, bool customInstallLocation, bool languageRequested) + public virtual string BuildInstallCommandArguments(bool logFile, bool customInstallLocation, bool languageRequested) { var args = new StringBuilder(); - args.Append("{0} {1} {2}".format_with(SilentInstall, NoReboot, OtherInstallOptions).trim_safe()); + args.Append("{0} {1} {2}".FormatWith(SilentInstall, NoReboot, OtherInstallOptions).TrimSafe()); if (languageRequested) args.AppendFormat(" {0}", Language); //MSI may have issues with 1622 - opening a log file location if (logFile) args.AppendFormat(" {0}", LogFile); @@ -49,10 +50,21 @@ public virtual string build_install_command_arguments(bool logFile, bool customI return args.ToString(); } - public virtual string build_uninstall_command_arguments() + public virtual string BuildUninstallCommandArguments() { //MSI has issues with 1622 - opening a log file location - return "{0} {1} {2}".format_with(SilentUninstall, NoReboot, OtherUninstallOptions).trim_safe(); + return "{0} {1} {2}".FormatWith(SilentUninstall, NoReboot, OtherUninstallOptions).TrimSafe(); } + +#pragma warning disable IDE1006 + [Obsolete("This overload is deprecated and will be removed in v3.")] + public virtual string build_install_command_arguments(bool logFile, bool customInstallLocation, bool languageRequested) + => BuildInstallCommandArguments(logFile, customInstallLocation, languageRequested); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public virtual string build_uninstall_command_arguments() + => BuildUninstallCommandArguments(); +#pragma warning restore IDE1006 + } } diff --git a/src/chocolatey/infrastructure.app/domain/installers/IzPackInstaller.cs b/src/chocolatey/infrastructure.app/domain/installers/IzPackInstaller.cs index 716aa2a567..1c796619cd 100644 --- a/src/chocolatey/infrastructure.app/domain/installers/IzPackInstaller.cs +++ b/src/chocolatey/infrastructure.app/domain/installers/IzPackInstaller.cs @@ -31,14 +31,14 @@ public class IzPackInstaller : InstallerBase public IzPackInstaller() { InstallExecutable = "java"; - SilentInstall = "-jar \"{0}\" -options-system".format_with(InstallTokens.INSTALLER_LOCATION); + SilentInstall = "-jar \"{0}\" -options-system".FormatWith(InstallTokens.InstallerLocation); NoReboot = ""; LogFile = ""; - CustomInstallLocation = "-DINSTALL_PATH=\"{0}\"".format_with(InstallTokens.CUSTOM_INSTALL_LOCATION); + CustomInstallLocation = "-DINSTALL_PATH=\"{0}\"".FormatWith(InstallTokens.CustomInstallLocation); Language = ""; OtherInstallOptions = ""; UninstallExecutable = "java"; //currently untested - SilentUninstall = "-jar \"{0}\"".format_with(InstallTokens.UNINSTALLER_LOCATION); + SilentUninstall = "-jar \"{0}\"".FormatWith(InstallTokens.UninstallerLocation); OtherUninstallOptions = ""; ValidInstallExitCodes = new List { diff --git a/src/chocolatey/infrastructure.app/domain/installers/MsiInstaller.cs b/src/chocolatey/infrastructure.app/domain/installers/MsiInstaller.cs index 9de037777a..c5a8bdb986 100644 --- a/src/chocolatey/infrastructure.app/domain/installers/MsiInstaller.cs +++ b/src/chocolatey/infrastructure.app/domain/installers/MsiInstaller.cs @@ -34,15 +34,15 @@ public MsiInstaller() { //todo: #2573 fully qualify msiexec InstallExecutable = "msiexec.exe"; - SilentInstall = "/i \"{0}\" /qn".format_with(InstallTokens.INSTALLER_LOCATION); // /quiet + SilentInstall = "/i \"{0}\" /qn".FormatWith(InstallTokens.InstallerLocation); // /quiet // http://msdn.microsoft.com/en-us/library/aa371101.aspx NoReboot = "/norestart"; //REBOOT=ReallySuppress - LogFile = "/l*v \"{0}\\MSI.Install.log\"".format_with(InstallTokens.PACKAGE_LOCATION); + LogFile = "/l*v \"{0}\\MSI.Install.log\"".FormatWith(InstallTokens.PackageLocation); // https://msdn.microsoft.com/en-us/library/aa372064.aspx // http://apprepack.blogspot.com/2012/08/installdir-vs-targetdir.html - CustomInstallLocation = "TARGETDIR=\"{0}\"".format_with(InstallTokens.CUSTOM_INSTALL_LOCATION); + CustomInstallLocation = "TARGETDIR=\"{0}\"".FormatWith(InstallTokens.CustomInstallLocation); // http://msdn.microsoft.com/en-us/library/aa370856.aspx - Language = "ProductLanguage={0}".format_with(InstallTokens.LANGUAGE); + Language = "ProductLanguage={0}".FormatWith(InstallTokens.Language); // http://msdn.microsoft.com/en-us/library/aa367559.aspx OtherInstallOptions = "ALLUSERS=1 DISABLEDESKTOPSHORTCUT=1 ADDDESKTOPICON=0 ADDSTARTMENU=0"; UninstallExecutable = "msiexec.exe"; diff --git a/src/chocolatey/infrastructure.app/domain/installers/MsiPatchInstaller.cs b/src/chocolatey/infrastructure.app/domain/installers/MsiPatchInstaller.cs index e3bff935b0..a93f2722b1 100644 --- a/src/chocolatey/infrastructure.app/domain/installers/MsiPatchInstaller.cs +++ b/src/chocolatey/infrastructure.app/domain/installers/MsiPatchInstaller.cs @@ -24,10 +24,10 @@ public MsiPatchInstaller() { //todo: #2573 fully qualify msiexec InstallExecutable = "msiexec.exe"; - SilentInstall = "/p \"{0}\" /qn".format_with(InstallTokens.INSTALLER_LOCATION); + SilentInstall = "/p \"{0}\" /qn".FormatWith(InstallTokens.InstallerLocation); // http://msdn.microsoft.com/en-us/library/aa371101.aspx NoReboot = "/norestart"; - LogFile = "/l*v \"{0}\\MSP.Install.log\"".format_with(InstallTokens.PACKAGE_LOCATION); + LogFile = "/l*v \"{0}\\MSP.Install.log\"".FormatWith(InstallTokens.PackageLocation); // https://msdn.microsoft.com/en-us/library/aa372064.aspx // http://apprepack.blogspot.com/2012/08/installdir-vs-targetdir.html CustomInstallLocation = ""; @@ -36,7 +36,7 @@ public MsiPatchInstaller() // http://msdn.microsoft.com/en-us/library/aa367559.aspx OtherInstallOptions = "REINSTALLMODE=sumo REINSTALL=ALL"; UninstallExecutable = "msiexec.exe"; - SilentUninstall = "/package {0} /qn".format_with(InstallTokens.UNINSTALLER_LOCATION); + SilentUninstall = "/package {0} /qn".FormatWith(InstallTokens.UninstallerLocation); OtherUninstallOptions = "MSIPATCHREMOVE={PATCH_GUID_HERE}"; // https://msdn.microsoft.com/en-us/library/aa376931.aspx // https://support.microsoft.com/en-us/kb/290158 diff --git a/src/chocolatey/infrastructure.app/domain/installers/NsisInstaller.cs b/src/chocolatey/infrastructure.app/domain/installers/NsisInstaller.cs index f3e89d3051..ca7a4c2673 100644 --- a/src/chocolatey/infrastructure.app/domain/installers/NsisInstaller.cs +++ b/src/chocolatey/infrastructure.app/domain/installers/NsisInstaller.cs @@ -30,15 +30,15 @@ public class NsisInstaller : InstallerBase { public NsisInstaller() { - InstallExecutable = "\"{0}\"".format_with(InstallTokens.INSTALLER_LOCATION); + InstallExecutable = "\"{0}\"".FormatWith(InstallTokens.InstallerLocation); SilentInstall = "/S"; NoReboot = ""; LogFile = ""; // must be last thing specified and contain no quotes, even if there are spaces - CustomInstallLocation = "/D={0}".format_with(InstallTokens.CUSTOM_INSTALL_LOCATION); + CustomInstallLocation = "/D={0}".FormatWith(InstallTokens.CustomInstallLocation); Language = ""; OtherInstallOptions = ""; - UninstallExecutable = "\"{0}\"".format_with(InstallTokens.UNINSTALLER_LOCATION); + UninstallExecutable = "\"{0}\"".FormatWith(InstallTokens.UninstallerLocation); SilentUninstall = "/S"; OtherUninstallOptions = ""; ValidInstallExitCodes = new List { 0 }; diff --git a/src/chocolatey/infrastructure.app/domain/installers/PackageForTheWebInstaller.cs b/src/chocolatey/infrastructure.app/domain/installers/PackageForTheWebInstaller.cs index f0c6341df1..8569026572 100644 --- a/src/chocolatey/infrastructure.app/domain/installers/PackageForTheWebInstaller.cs +++ b/src/chocolatey/infrastructure.app/domain/installers/PackageForTheWebInstaller.cs @@ -27,14 +27,14 @@ public class PackageForTheWebInstaller : InstallerBase { public PackageForTheWebInstaller() { - InstallExecutable = "\"{0}\"".format_with(InstallTokens.INSTALLER_LOCATION); + InstallExecutable = "\"{0}\"".FormatWith(InstallTokens.InstallerLocation); SilentInstall = "/s"; NoReboot = ""; LogFile = ""; CustomInstallLocation = ""; Language = ""; OtherInstallOptions = ""; - UninstallExecutable = "\"{0}\"".format_with(InstallTokens.UNINSTALLER_LOCATION); + UninstallExecutable = "\"{0}\"".FormatWith(InstallTokens.UninstallerLocation); SilentUninstall = "/s"; OtherUninstallOptions = ""; ValidInstallExitCodes = new List diff --git a/src/chocolatey/infrastructure.app/domain/installers/QtInstaller.cs b/src/chocolatey/infrastructure.app/domain/installers/QtInstaller.cs index a95a8c66d2..fb21501619 100644 --- a/src/chocolatey/infrastructure.app/domain/installers/QtInstaller.cs +++ b/src/chocolatey/infrastructure.app/domain/installers/QtInstaller.cs @@ -29,7 +29,7 @@ public class QtInstaller : InstallerBase { public QtInstaller() { - InstallExecutable = "\"{0}\"".format_with(InstallTokens.INSTALLER_LOCATION); + InstallExecutable = "\"{0}\"".FormatWith(InstallTokens.InstallerLocation); SilentInstall = ""; NoReboot = ""; LogFile = ""; @@ -38,7 +38,7 @@ public QtInstaller() CustomInstallLocation = ""; Language = ""; OtherInstallOptions = ""; - UninstallExecutable = "\"{0}\"".format_with(InstallTokens.UNINSTALLER_LOCATION); + UninstallExecutable = "\"{0}\"".FormatWith(InstallTokens.UninstallerLocation); SilentUninstall = ""; OtherUninstallOptions = ""; ValidInstallExitCodes = new List diff --git a/src/chocolatey/infrastructure.app/domain/installers/SetupFactoryInstaller.cs b/src/chocolatey/infrastructure.app/domain/installers/SetupFactoryInstaller.cs index 8ca5695e4b..a41dd41f8a 100644 --- a/src/chocolatey/infrastructure.app/domain/installers/SetupFactoryInstaller.cs +++ b/src/chocolatey/infrastructure.app/domain/installers/SetupFactoryInstaller.cs @@ -30,7 +30,7 @@ public class SetupFactoryInstaller : InstallerBase { public SetupFactoryInstaller() { - InstallExecutable = "\"{0}\"".format_with(InstallTokens.INSTALLER_LOCATION); + InstallExecutable = "\"{0}\"".FormatWith(InstallTokens.InstallerLocation); SilentInstall = "/S"; NoReboot = ""; LogFile = ""; @@ -42,7 +42,7 @@ public SetupFactoryInstaller() Language = ""; //OtherInstallOptions = "\"/T:{0}\"".format_with(InstallTokens.TEMP_LOCATION); OtherInstallOptions = ""; - UninstallExecutable = "\"{0}\"".format_with(InstallTokens.UNINSTALLER_LOCATION); + UninstallExecutable = "\"{0}\"".FormatWith(InstallTokens.UninstallerLocation); SilentUninstall = "/S"; OtherUninstallOptions = ""; ValidInstallExitCodes = new List diff --git a/src/chocolatey/infrastructure.app/domain/installers/SquirrelInstaller.cs b/src/chocolatey/infrastructure.app/domain/installers/SquirrelInstaller.cs index 7ff3bd6f8d..225f19a9b9 100644 --- a/src/chocolatey/infrastructure.app/domain/installers/SquirrelInstaller.cs +++ b/src/chocolatey/infrastructure.app/domain/installers/SquirrelInstaller.cs @@ -28,14 +28,14 @@ public class SquirrelInstaller : InstallerBase { public SquirrelInstaller() { - InstallExecutable = "\"{0}\"".format_with(InstallTokens.INSTALLER_LOCATION); + InstallExecutable = "\"{0}\"".FormatWith(InstallTokens.InstallerLocation); SilentInstall = "-s"; NoReboot = ""; LogFile = ""; CustomInstallLocation = ""; Language = ""; OtherInstallOptions = ""; - UninstallExecutable = "\"{0}\"".format_with(InstallTokens.UNINSTALLER_LOCATION); + UninstallExecutable = "\"{0}\"".FormatWith(InstallTokens.UninstallerLocation); SilentUninstall = "-s"; OtherUninstallOptions = ""; ValidInstallExitCodes = new List diff --git a/src/chocolatey/infrastructure.app/domain/installers/WindowsUpdateInstaller.cs b/src/chocolatey/infrastructure.app/domain/installers/WindowsUpdateInstaller.cs index bc9832da48..961cb9f7b8 100644 --- a/src/chocolatey/infrastructure.app/domain/installers/WindowsUpdateInstaller.cs +++ b/src/chocolatey/infrastructure.app/domain/installers/WindowsUpdateInstaller.cs @@ -30,14 +30,14 @@ public WindowsUpdateInstaller() { //todo: #2583 fully qualify wusa InstallExecutable = "wusa.exe"; - SilentInstall = "\"{0}\" /quiet".format_with(InstallTokens.INSTALLER_LOCATION); + SilentInstall = "\"{0}\" /quiet".FormatWith(InstallTokens.InstallerLocation); NoReboot = "/norestart"; - LogFile = "/log:\"{0}\\MSP_install_log.evtx\"".format_with(InstallTokens.PACKAGE_LOCATION); + LogFile = "/log:\"{0}\\MSP_install_log.evtx\"".FormatWith(InstallTokens.PackageLocation); CustomInstallLocation = ""; Language = ""; OtherInstallOptions = ""; UninstallExecutable = "wusa.exe"; - SilentUninstall = "\"{0}\" /quiet".format_with(InstallTokens.UNINSTALLER_LOCATION); + SilentUninstall = "\"{0}\" /quiet".FormatWith(InstallTokens.UninstallerLocation); OtherUninstallOptions = ""; // https://msdn.microsoft.com/en-us/library/aa376931.aspx // https://support.microsoft.com/en-us/kb/290158 diff --git a/src/chocolatey/infrastructure.app/domain/installers/WiseInstaller.cs b/src/chocolatey/infrastructure.app/domain/installers/WiseInstaller.cs index de3eade10f..dbec70b392 100644 --- a/src/chocolatey/infrastructure.app/domain/installers/WiseInstaller.cs +++ b/src/chocolatey/infrastructure.app/domain/installers/WiseInstaller.cs @@ -31,7 +31,7 @@ public class WiseInstaller : InstallerBase { public WiseInstaller() { - InstallExecutable = "\"{0}\"".format_with(InstallTokens.INSTALLER_LOCATION); + InstallExecutable = "\"{0}\"".FormatWith(InstallTokens.InstallerLocation); SilentInstall = "/s"; NoReboot = ""; LogFile = ""; @@ -39,10 +39,10 @@ public WiseInstaller() CustomInstallLocation = ""; Language = ""; OtherInstallOptions = ""; - UninstallExecutable = "\"{0}\"".format_with(InstallTokens.UNINSTALLER_LOCATION); + UninstallExecutable = "\"{0}\"".FormatWith(InstallTokens.UninstallerLocation); SilentUninstall = "/s"; // http://www.symantec.com/connect/blogs/wisescript-command-line-options - OtherUninstallOptions = "\"{0}\\Uninstall.Log\"".format_with(InstallTokens.TEMP_LOCATION); + OtherUninstallOptions = "\"{0}\\Uninstall.Log\"".FormatWith(InstallTokens.TempLocation); ValidInstallExitCodes = new List { 0 diff --git a/src/chocolatey/infrastructure.app/nuget/ChocolateyNuGetProjectContext.cs b/src/chocolatey/infrastructure.app/nuget/ChocolateyNuGetProjectContext.cs index b50e293d6c..49637d6852 100644 --- a/src/chocolatey/infrastructure.app/nuget/ChocolateyNuGetProjectContext.cs +++ b/src/chocolatey/infrastructure.app/nuget/ChocolateyNuGetProjectContext.cs @@ -40,16 +40,16 @@ public void Log(MessageLevel level, string message, params object[] args) switch (level) { case MessageLevel.Debug: - _logger.LogDebug(message.format_with(args)); + _logger.LogDebug(message.FormatWith(args)); break; case MessageLevel.Info: - _logger.LogInformation(message.format_with(args)); + _logger.LogInformation(message.FormatWith(args)); break; case MessageLevel.Warning: - _logger.LogWarning(message.format_with(args)); + _logger.LogWarning(message.FormatWith(args)); break; case MessageLevel.Error: - _logger.LogError(message.format_with(args)); + _logger.LogError(message.FormatWith(args)); break; } } @@ -71,7 +71,7 @@ public void ReportError(ILogMessage message) public FileConflictAction ResolveFileConflict(string message) { - _logger.LogWarning("File conflict, overwriting all: {0}".format_with(message)); + _logger.LogWarning("File conflict, overwriting all: {0}".FormatWith(message)); return FileConflictAction.OverwriteAll; } diff --git a/src/chocolatey/infrastructure.app/nuget/ChocolateyNuGetSettings.cs b/src/chocolatey/infrastructure.app/nuget/ChocolateyNuGetSettings.cs index 78df4ad26c..6825a98707 100644 --- a/src/chocolatey/infrastructure.app/nuget/ChocolateyNuGetSettings.cs +++ b/src/chocolatey/infrastructure.app/nuget/ChocolateyNuGetSettings.cs @@ -13,7 +13,7 @@ namespace chocolatey.infrastructure.app.nuget public class ChocolateyNuGetSettings : ISettings { //private ClientPolicyContext - private const string CONFIG_SECTION_NAME = "config"; + private const string ConfigSectionName = "config"; //private SettingSection _configSettingSection; public ChocolateyNuGetSettings(ChocolateyConfiguration config) @@ -26,7 +26,7 @@ public ChocolateyNuGetSettings(ChocolateyConfiguration config) public void AddOrUpdate(string sectionName, SettingItem item) { - this.Log().Warn("NuGet tried to add an item to section {0}".format_with(sectionName)); + this.Log().Warn("NuGet tried to add an item to section {0}".FormatWith(sectionName)); } public IList GetConfigFilePaths() => Enumerable.Empty().ToList(); @@ -37,7 +37,7 @@ public SettingSection GetSection(string sectionName) { switch (sectionName) { - case CONFIG_SECTION_NAME: + case ConfigSectionName: //TODO fix return null; //break; @@ -48,7 +48,7 @@ public SettingSection GetSection(string sectionName) public void Remove(string sectionName, SettingItem item) { - this.Log().Warn("NuGet tried to remove an item to section {0}".format_with(sectionName)); + this.Log().Warn("NuGet tried to remove an item to section {0}".FormatWith(sectionName)); } public void SaveToDisk() diff --git a/src/chocolatey/infrastructure.app/nuget/ChocolateyNugetCredentialProvider.cs b/src/chocolatey/infrastructure.app/nuget/ChocolateyNugetCredentialProvider.cs index b6af369597..08818ff71d 100644 --- a/src/chocolatey/infrastructure.app/nuget/ChocolateyNugetCredentialProvider.cs +++ b/src/chocolatey/infrastructure.app/nuget/ChocolateyNugetCredentialProvider.cs @@ -28,13 +28,11 @@ namespace chocolatey.infrastructure.app.nuget using NuGet.Configuration; using System.Threading; - // ReSharper disable InconsistentNaming - public sealed class ChocolateyNugetCredentialProvider : ICredentialProvider { private readonly ChocolateyConfiguration _config; - private const string INVALID_URL = "http://somewhere123zzaafasd.invalid"; + private const string InvalidUrl = "http://somewhere123zzaafasd.invalid"; /// /// Unique identifier of this credential provider @@ -59,13 +57,13 @@ public Task GetAsync(Uri uri, IWebProxy proxy, CredentialReq this.Log().Warn("Invalid credentials specified."); } - var configSourceUri = new Uri(INVALID_URL); + var configSourceUri = new Uri(InvalidUrl); - this.Log().Debug(ChocolateyLoggers.Verbose, "Attempting to gather credentials for '{0}'".format_with(uri.OriginalString)); + this.Log().Debug(ChocolateyLoggers.Verbose, "Attempting to gather credentials for '{0}'".FormatWith(uri.OriginalString)); try { // the source to validate against is typically passed in - var firstSpecifiedSource = _config.Sources.to_string().Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries).FirstOrDefault().to_string(); + var firstSpecifiedSource = _config.Sources.ToStringSafe().Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries).FirstOrDefault().ToStringSafe(); if (!string.IsNullOrWhiteSpace(firstSpecifiedSource)) { configSourceUri = new Uri(firstSpecifiedSource); @@ -73,11 +71,11 @@ public Task GetAsync(Uri uri, IWebProxy proxy, CredentialReq } catch (Exception ex) { - this.Log().Warn("Cannot determine uri from specified source:{0} {1}".format_with(Environment.NewLine, ex.Message)); + this.Log().Warn("Cannot determine uri from specified source:{0} {1}".FormatWith(Environment.NewLine, ex.Message)); } // did the user pass credentials and a source? - if (_config.Sources.TrimEnd('/').is_equal_to(uri.OriginalString.TrimEnd('/')) || configSourceUri.Host.is_equal_to(uri.Host)) + if (_config.Sources.TrimEnd('/').IsEqualTo(uri.OriginalString.TrimEnd('/')) || configSourceUri.Host.IsEqualTo(uri.Host)) { if (!string.IsNullOrWhiteSpace(_config.SourceCommand.Username) && !string.IsNullOrWhiteSpace(_config.SourceCommand.Password)) { @@ -97,13 +95,13 @@ public Task GetAsync(Uri uri, IWebProxy proxy, CredentialReq try { var sourceUri = new Uri(sourceUrl); - return sourceUri.Host.is_equal_to(uri.Host) + return sourceUri.Host.IsEqualTo(uri.Host) && !string.IsNullOrWhiteSpace(s.Username) && !string.IsNullOrWhiteSpace(s.EncryptedPassword); } catch (Exception) { - this.Log().Error("Source '{0}' is not a valid Uri".format_with(sourceUrl)); + this.Log().Error("Source '{0}' is not a valid Uri".FormatWith(sourceUrl)); } return false; @@ -120,12 +118,12 @@ public Task GetAsync(Uri uri, IWebProxy proxy, CredentialReq else if (candidateSources.Count > 1) { // find the source that is the closest match - foreach (var candidateSource in candidateSources.or_empty_list_if_null()) + foreach (var candidateSource in candidateSources.OrEmpty()) { var candidateRegEx = new Regex(Regex.Escape(candidateSource.Key.TrimEnd('/')),RegexOptions.CultureInvariant | RegexOptions.IgnoreCase); if (candidateRegEx.IsMatch(uri.OriginalString.TrimEnd('/'))) { - this.Log().Debug("Source selected will be '{0}'".format_with(candidateSource.Key.TrimEnd('/'))); + this.Log().Debug("Source selected will be '{0}'".FormatWith(candidateSource.Key.TrimEnd('/'))); source = candidateSource; break; } @@ -135,15 +133,15 @@ public Task GetAsync(Uri uri, IWebProxy proxy, CredentialReq { // use the first source. If it fails, fall back to grabbing credentials from the user var candidateSource = candidateSources.First(); - this.Log().Debug("Evaluated {0} candidate sources but was unable to find a match, using {1}".format_with(candidateSources.Count, candidateSource.Key.TrimEnd('/'))); + this.Log().Debug("Evaluated {0} candidate sources but was unable to find a match, using {1}".FormatWith(candidateSources.Count, candidateSource.Key.TrimEnd('/'))); source = candidateSource; } } if (source == null) { - this.Log().Debug("Asking user for credentials for '{0}'".format_with(uri.OriginalString)); - return Task.FromResult(new CredentialResponse(get_credentials_from_user(uri, proxy, credentialType))); + this.Log().Debug("Asking user for credentials for '{0}'".FormatWith(uri.OriginalString)); + return Task.FromResult(new CredentialResponse(GetUserCredentials(uri, proxy, credentialType))); } else { @@ -154,7 +152,7 @@ public Task GetAsync(Uri uri, IWebProxy proxy, CredentialReq } - public ICredentials get_credentials_from_user(Uri uri, IWebProxy proxy, CredentialRequestType credentialType) + public ICredentials GetUserCredentials(Uri uri, IWebProxy proxy, CredentialRequestType credentialType) { if (!_config.Information.IsInteractive) { @@ -165,13 +163,13 @@ public ICredentials get_credentials_from_user(Uri uri, IWebProxy proxy, Credenti string message = credentialType == CredentialRequestType.Proxy ? "Please provide proxy credentials:" : - "Please provide credentials for: {0}".format_with(uri.OriginalString); + "Please provide credentials for: {0}".FormatWith(uri.OriginalString); this.Log().Info(ChocolateyLoggers.Important, message); Console.Write("User name: "); string username = Console.ReadLine(); Console.Write("Password: "); - var password = InteractivePrompt.get_password(_config.PromptForConfirmation); + var password = InteractivePrompt.GetPassword(_config.PromptForConfirmation); if (string.IsNullOrWhiteSpace(password)) { @@ -187,7 +185,11 @@ public ICredentials get_credentials_from_user(Uri uri, IWebProxy proxy, Credenti return credentials; } - } - // ReSharper restore InconsistentNaming +#pragma warning disable IDE1006 + [Obsolete("This overload is deprecated and will be removed in v3.")] + public ICredentials get_credentials_from_user(Uri uri, IWebProxy proxy, CredentialRequestType credentialType) + => GetUserCredentials(uri, proxy, credentialType); +#pragma warning restore IDE1006 + } } diff --git a/src/chocolatey/infrastructure.app/nuget/ChocolateyNugetLogger.cs b/src/chocolatey/infrastructure.app/nuget/ChocolateyNugetLogger.cs index 6c5c17033c..0b6b993fc4 100644 --- a/src/chocolatey/infrastructure.app/nuget/ChocolateyNugetLogger.cs +++ b/src/chocolatey/infrastructure.app/nuget/ChocolateyNugetLogger.cs @@ -23,8 +23,6 @@ namespace chocolatey.infrastructure.app.nuget using logging; using NuGet.Common; - // ReSharper disable InconsistentNaming - public sealed class ChocolateyNugetLogger : ILogger { public void LogDebug(string message) @@ -76,7 +74,7 @@ public void LogInformationSummary(string message) public void Log(LogLevel level, string message) { - var prefixedMessage = prefix_all_lines("[NuGet]", message); + var prefixedMessage = PrefixAllLines("[NuGet]", message); switch (level) { @@ -121,7 +119,7 @@ public Task LogAsync(ILogMessage log) return LogAsync(log.Level, log.Message); } - private static string prefix_all_lines(string prefix, string message) + private static string PrefixAllLines(string prefix, string message) { if (message == null || (string.IsNullOrWhiteSpace(message) && message.IndexOf('\n') < 0)) { @@ -129,7 +127,7 @@ private static string prefix_all_lines(string prefix, string message) } else if (message.IndexOf('\n') < 0) { - return "{0} {1}".format_with(prefix, message); + return "{0} {1}".FormatWith(prefix, message); } var builder = new StringBuilder(message.Length); @@ -154,6 +152,4 @@ private static string prefix_all_lines(string prefix, string message) return builder.ToString(0, builder.Length - Environment.NewLine.Length); } } - - // ReSharper restore InconsistentNaming } diff --git a/src/chocolatey/infrastructure.app/nuget/ChocolateyPackagePathResolver.cs b/src/chocolatey/infrastructure.app/nuget/ChocolateyPackagePathResolver.cs index 3533bce2db..03f2c0a0ba 100644 --- a/src/chocolatey/infrastructure.app/nuget/ChocolateyPackagePathResolver.cs +++ b/src/chocolatey/infrastructure.app/nuget/ChocolateyPackagePathResolver.cs @@ -25,8 +25,6 @@ namespace chocolatey.infrastructure.app.nuget using NuGet.ProjectManagement; using NuGet.Versioning; - // ReSharper disable InconsistentNaming - public sealed class ChocolateyPackagePathResolver : PackagePathResolver { public string RootDirectory { get; set; } @@ -43,7 +41,7 @@ public override string GetInstallPath(PackageIdentity packageIdentity) => GetInstallPath(packageIdentity.Id); public string GetInstallPath(string packageId) - => _filesystem.combine_paths(RootDirectory, packageId); + => _filesystem.CombinePaths(RootDirectory, packageId); [Obsolete("This overload will be removed in a future version.")] public string GetInstallPath(string id, NuGetVersion version) @@ -52,6 +50,4 @@ public string GetInstallPath(string id, NuGetVersion version) public override string GetPackageFileName(PackageIdentity packageIdentity) => packageIdentity.Id + NuGetConstants.PackageExtension; } - - // ReSharper restore InconsistentNaming } diff --git a/src/chocolatey/infrastructure.app/nuget/NuGetEndpointResources.cs b/src/chocolatey/infrastructure.app/nuget/NuGetEndpointResources.cs new file mode 100644 index 0000000000..8143077a98 --- /dev/null +++ b/src/chocolatey/infrastructure.app/nuget/NuGetEndpointResources.cs @@ -0,0 +1,155 @@ +// Copyright © 2023-Present Chocolatey Software, Inc +// +// 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. + +namespace chocolatey.infrastructure.app.nuget +{ + using System; + using System.Collections.Concurrent; + using System.Collections.Generic; + using chocolatey.infrastructure.logging; + using NuGet.Protocol.Core.Types; + + public sealed class NuGetEndpointResources + { + private static readonly ConcurrentDictionary _cachedResources = new ConcurrentDictionary(); + + private bool _resolvingFailed; + private readonly Lazy _dependencyInfoResource; + private readonly Lazy _downloadResource; + private readonly Lazy _findPackageResource; + private readonly Lazy _listResource; + private readonly Lazy _packageMetadataResource; + private readonly Lazy _packageUpdateResource; + private readonly Lazy _searchResource; + + private NuGetEndpointResources(SourceRepository _sourceRepository) + { + Source = _sourceRepository; + + _dependencyInfoResource = new Lazy(() => ResolveResource()); + _downloadResource = new Lazy(() => ResolveResource()); + _findPackageResource = new Lazy(() => ResolveResource()); + _listResource = new Lazy(() => ResolveResource()); + _packageMetadataResource = new Lazy(() => ResolveResource()); + _packageUpdateResource = new Lazy(() => ResolveResource()); + _searchResource = new Lazy(() => ResolveResource()); + } + + public DependencyInfoResource DependencyInfoResource + { + get + { + return _dependencyInfoResource.Value; + } + } + + public DownloadResource DownloadResource + { + get + { + return _downloadResource.Value; + } + } + + public FindPackageByIdResource FindPackageResource + { + get + { + return _findPackageResource.Value; + } + } + + public ListResource ListResource + { + get + { + return _listResource.Value; + } + } + + public PackageMetadataResource PackageMetadataResource + { + get + { + return _packageMetadataResource.Value; + } + } + + public PackageUpdateResource PackageUpdateResource + { + get + { + return _packageUpdateResource.Value; + } + } + + public PackageSearchResource SearchResource + { + get + { + return _searchResource.Value; + } + } + + public SourceRepository Source { get; private set; } + + public static NuGetEndpointResources GetResourcesBySource(SourceRepository source) + { + return _cachedResources.GetOrAdd(source, (key) => + { + var endpointResource = new NuGetEndpointResources(key); + + return endpointResource; + }); + } + + public static IEnumerable GetResourcesBySource(IEnumerable sources) + { + foreach (SourceRepository source in sources) + { + yield return GetResourcesBySource(source); + } + } + + private T ResolveResource() + where T : class, INuGetResource + { + T resource = default; + + try + { + this.Log().Debug("Resolving resource {0} for source {1}", typeof(T).Name, Source.PackageSource.Source); +#pragma warning disable RS0030 // Do not used banned APIs + resource = Source.GetResource(); +#pragma warning restore RS0030 // Do not used banned APIs + } + catch (AggregateException ex) when (!(ex.InnerException is null)) + { + if (!_resolvingFailed) + { + this.Log().Warn(ex.InnerException.Message); + _resolvingFailed = true; + } + } + + if (resource == default) + { + this.Log().Warn(ChocolateyLoggers.LogFileOnly, "The source {0} failed to get a {1} resource".FormatWith(Source.PackageSource.Source, typeof(T))); + } + + return resource; + } + } +} diff --git a/src/chocolatey/infrastructure.app/nuget/NuGetEndpointResourcesExtensions.cs b/src/chocolatey/infrastructure.app/nuget/NuGetEndpointResourcesExtensions.cs new file mode 100644 index 0000000000..14877e9e04 --- /dev/null +++ b/src/chocolatey/infrastructure.app/nuget/NuGetEndpointResourcesExtensions.cs @@ -0,0 +1,44 @@ +// Copyright © 2023-Present Chocolatey Software, Inc +// +// 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. + +namespace chocolatey.infrastructure.app.nuget +{ + using System.Collections.Generic; + using System.Linq; + using NuGet.Protocol.Core.Types; + + public static class NuGetEndpointResourcesExtensions + { + public static IEnumerable MetadataResources(this IEnumerable resources) + { + return resources.Where(r => r.PackageMetadataResource != null).Select(r => r.PackageMetadataResource); + } + + public static IEnumerable DependencyInfoResources(this IEnumerable resources) + { + return resources.Where(r => r.DependencyInfoResource != null).Select(r => r.DependencyInfoResource); + } + + public static IEnumerable ListResources(this IEnumerable resources) + { + return resources.Where(r => r.ListResource != null).Select(r => r.ListResource); + } + + public static IEnumerable SearchResources(this IEnumerable resources) + { + return resources.Where(r => r.SearchResource != null).Select(r => r.SearchResource); + } + } +} diff --git a/src/chocolatey/infrastructure.app/nuget/NugetCommon.cs b/src/chocolatey/infrastructure.app/nuget/NugetCommon.cs index 3d15fca157..20911503e8 100644 --- a/src/chocolatey/infrastructure.app/nuget/NugetCommon.cs +++ b/src/chocolatey/infrastructure.app/nuget/NugetCommon.cs @@ -52,20 +52,23 @@ namespace chocolatey.infrastructure.app.nuget using Environment = adapters.Environment; using System.Collections.Concurrent; - // ReSharper disable InconsistentNaming - public sealed class NugetCommon { private static readonly ConcurrentDictionary _repositories = new ConcurrentDictionary(); + [Obsolete("This member is unused and should probably be removed.")] private static Lazy _console = new Lazy(() => new Console()); +#pragma warning disable IDE1006 [EditorBrowsable(EditorBrowsableState.Never)] + [Obsolete("This member is unused and should probably be removed.")] public static void initialize_with(Lazy console) { _console = console; } +#pragma warning restore IDE1006 + [Obsolete("This member is unused and should probably be removed.")] private static IConsole Console { get { return _console.Value; } @@ -94,14 +97,14 @@ public static SourceRepository GetLocalRepository() public static IEnumerable GetRemoteRepositories(ChocolateyConfiguration configuration, ILogger nugetLogger, IFileSystem filesystem) { // Set user agent for all NuGet library calls. Should not affect any HTTP calls that Chocolatey itself would make. - UserAgent.SetUserAgentString(new UserAgentStringBuilder("{0}/{1} via NuGet Client".format_with(ApplicationParameters.UserAgent, configuration.Information.ChocolateyProductVersion))); + UserAgent.SetUserAgentString(new UserAgentStringBuilder("{0}/{1} via NuGet Client".FormatWith(ApplicationParameters.UserAgent, configuration.Information.ChocolateyProductVersion))); // ensure credentials can be grabbed from configuration SetHttpHandlerCredentialService(configuration); if (!string.IsNullOrWhiteSpace(configuration.Proxy.Location)) { - "chocolatey".Log().Debug("Using proxy server '{0}'.".format_with(configuration.Proxy.Location)); + "chocolatey".Log().Debug("Using proxy server '{0}'.".FormatWith(configuration.Proxy.Location)); var proxy = new System.Net.WebProxy(configuration.Proxy.Location, true); if (!String.IsNullOrWhiteSpace(configuration.Proxy.User) && !String.IsNullOrWhiteSpace(configuration.Proxy.EncryptedPassword)) @@ -111,7 +114,7 @@ public static IEnumerable GetRemoteRepositories(ChocolateyConf if (!string.IsNullOrWhiteSpace(configuration.Proxy.BypassList)) { - "chocolatey".Log().Debug("Proxy has a bypass list of '{0}'.".format_with(configuration.Proxy.BypassList.escape_curly_braces())); + "chocolatey".Log().Debug("Proxy has a bypass list of '{0}'.".FormatWith(configuration.Proxy.BypassList.EscapeCurlyBraces())); proxy.BypassList = configuration.Proxy.BypassList.Replace("*",".*").Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries); } @@ -124,12 +127,12 @@ public static IEnumerable GetRemoteRepositories(ChocolateyConf ProxyCache.Instance.Override(new System.Net.WebProxy()); } - IEnumerable sources = configuration.Sources.to_string().Split(new[] { ";", "," }, StringSplitOptions.RemoveEmptyEntries); + IEnumerable sources = configuration.Sources.ToStringSafe().Split(new[] { ";", "," }, StringSplitOptions.RemoveEmptyEntries); IList repositories = new List(); var updatedSources = new StringBuilder(); - foreach (var sourceValue in sources.or_empty_list_if_null()) + foreach (var sourceValue in sources.OrEmpty()) { var source = sourceValue; var bypassProxy = false; @@ -137,37 +140,37 @@ public static IEnumerable GetRemoteRepositories(ChocolateyConf var sourceClientCertificates = new List(); if (!string.IsNullOrWhiteSpace(configuration.SourceCommand.Certificate)) { - "chocolatey".Log().Debug("Using passed in certificate for source {0}".format_with(source)); + "chocolatey".Log().Debug("Using passed in certificate for source {0}".FormatWith(source)); sourceClientCertificates.Add(new X509Certificate2(configuration.SourceCommand.Certificate, configuration.SourceCommand.CertificatePassword)); } - if (configuration.MachineSources.Any(m => m.Name.is_equal_to(source) || m.Key.is_equal_to(source))) + if (configuration.MachineSources.Any(m => m.Name.IsEqualTo(source) || m.Key.IsEqualTo(source))) { try { - var machineSource = configuration.MachineSources.FirstOrDefault(m => m.Key.is_equal_to(source)); + var machineSource = configuration.MachineSources.FirstOrDefault(m => m.Key.IsEqualTo(source)); if (machineSource == null) { - machineSource = configuration.MachineSources.FirstOrDefault(m => m.Name.is_equal_to(source)); - "chocolatey".Log().Debug("Switching source name {0} to actual source value '{1}'.".format_with(sourceValue, machineSource.Key.to_string())); + machineSource = configuration.MachineSources.FirstOrDefault(m => m.Name.IsEqualTo(source)); + "chocolatey".Log().Debug("Switching source name {0} to actual source value '{1}'.".FormatWith(sourceValue, machineSource.Key.ToStringSafe())); source = machineSource.Key; } if (machineSource != null) { bypassProxy = machineSource.BypassProxy; - if (bypassProxy) "chocolatey".Log().Debug("Source '{0}' is configured to bypass proxies.".format_with(source)); + if (bypassProxy) "chocolatey".Log().Debug("Source '{0}' is configured to bypass proxies.".FormatWith(source)); if (!string.IsNullOrWhiteSpace(machineSource.Certificate)) { - "chocolatey".Log().Debug("Using configured certificate for source {0}".format_with(source)); + "chocolatey".Log().Debug("Using configured certificate for source {0}".FormatWith(source)); sourceClientCertificates.Add(new X509Certificate2(machineSource.Certificate, NugetEncryptionUtility.DecryptString(machineSource.EncryptedCertificatePassword))); } } } catch (Exception ex) { - "chocolatey".Log().Warn("Attempted to use a source name {0} to get default source but failed:{1} {2}".format_with(sourceValue, System.Environment.NewLine, ex.Message)); + "chocolatey".Log().Warn("Attempted to use a source name {0} to get default source but failed:{1} {2}".FormatWith(sourceValue, System.Environment.NewLine, ex.Message)); } } @@ -188,7 +191,7 @@ public static IEnumerable GetRemoteRepositories(ChocolateyConf string fullsource; try { - fullsource = filesystem.get_full_path(source); + fullsource = filesystem.GetFullPath(source); } catch { @@ -199,10 +202,10 @@ public static IEnumerable GetRemoteRepositories(ChocolateyConf if (!nugetSource.IsLocal) { - throw new ApplicationException("Source '{0}' is unable to be parsed".format_with(source)); + throw new ApplicationException("Source '{0}' is unable to be parsed".FormatWith(source)); } - "chocolatey".Log().Debug("Updating Source path from {0} to {1}".format_with(source, fullsource)); + "chocolatey".Log().Debug("Updating Source path from {0} to {1}".FormatWith(source, fullsource)); updatedSources.AppendFormat("{0};", fullsource); } else @@ -215,7 +218,9 @@ public static IEnumerable GetRemoteRepositories(ChocolateyConf if (nugetSource.IsHttp || nugetSource.IsHttps) { +#pragma warning disable RS0030 // Do not used banned APIs var httpSourceResource = repo.GetResource(); +#pragma warning restore RS0030 // Do not used banned APIs if (httpSourceResource != null) { httpSourceResource.HttpSource.HttpCacheDirectory = ApplicationParameters.HttpCacheLocation; @@ -229,45 +234,21 @@ public static IEnumerable GetRemoteRepositories(ChocolateyConf if (updatedSources.Length != 0) { - configuration.Sources = updatedSources.Remove(updatedSources.Length - 1, 1).to_string(); + configuration.Sources = updatedSources.Remove(updatedSources.Length - 1, 1).ToStringSafe(); } return repositories; } - public static IEnumerable GetRepositoryResource(IEnumerable packageRepositories) where T : class, INuGetResource + public static IReadOnlyList GetRepositoryResources(ChocolateyConfiguration configuration, ILogger nugetLogger, IFileSystem filesystem) { - foreach (var repository in packageRepositories) - { - var resource = repository.GetResource(); - if (resource is null) - { - "chocolatey".Log().Warn(ChocolateyLoggers.LogFileOnly, "The source {0} failed to get a {1} resource".format_with(repository.PackageSource.Source, typeof(T))); - } - else - { - yield return resource; - } - } + IEnumerable remoteRepositories = GetRemoteRepositories(configuration, nugetLogger, filesystem); + return GetRepositoryResources(remoteRepositories); } - // TODO: Refactor this to not use a tuple, or make private method. - public static IEnumerable<(SourceRepository repository, - PackageSearchResource searchResource, - FindPackageByIdResource findPackageByIdResource, - PackageMetadataResource packageMetadataResource, - ListResource listResource - )> GetRepositoryResources(IEnumerable packageRepositories) + public static IReadOnlyList GetRepositoryResources(IEnumerable packageRepositories) { - foreach (var repository in packageRepositories) - { - yield return ( - repository, - repository.GetResource(), - repository.GetResource(), - repository.GetResource(), - repository.GetResource()); - } + return NuGetEndpointResources.GetResourcesBySource(packageRepositories).ToList(); } public static void SetHttpHandlerCredentialService(ChocolateyConfiguration configuration) @@ -356,17 +337,32 @@ public static async Task GetPackageDependencies(PackageIdentity package, NuGetFramework framework, SourceCacheContext cacheContext, ILogger logger, - IEnumerable dependencyInfoResources, + IEnumerable resources, ISet availablePackages, ISet dependencyCache, ChocolateyConfiguration configuration) { if (availablePackages.Contains(package)) return; + var dependencyInfoResources = resources.DependencyInfoResources(); + foreach (var dependencyInfoResource in dependencyInfoResources) { - var dependencyInfo = await dependencyInfoResource.ResolvePackage( - package, framework, cacheContext, logger, CancellationToken.None); + SourcePackageDependencyInfo dependencyInfo = null; + + try + { + dependencyInfo = await dependencyInfoResource.ResolvePackage( + package, framework, cacheContext, logger, CancellationToken.None); + } + catch (AggregateException ex) when (!(ex.InnerException is null)) + { + "chocolatey".Log().Warn(ex.InnerException.Message); + } + catch (Exception ex) + { + "chocolatey".Log().Warn(ex.InnerException.Message); + } if (dependencyInfo == null) continue; @@ -376,7 +372,7 @@ public static async Task GetPackageDependencies(PackageIdentity package, if (dependencyCache.Contains(dependency)) continue; dependencyCache.Add(dependency); await GetPackageDependencies( - dependency.Id, framework, cacheContext, logger, dependencyInfoResources, availablePackages, dependencyCache, configuration); + dependency.Id, framework, cacheContext, logger, resources, availablePackages, dependencyCache, configuration); } } } @@ -385,17 +381,32 @@ public static async Task GetPackageDependencies(string packageId, NuGetFramework framework, SourceCacheContext cacheContext, ILogger logger, - IEnumerable dependencyInfoResources, + IEnumerable resources, ISet availablePackages, ISet dependencyCache, ChocolateyConfiguration configuration) { //if (availablePackages.Contains(packageID)) return; + var dependencyInfoResources = resources.DependencyInfoResources(); + foreach (var dependencyInfoResource in dependencyInfoResources) { - var dependencyInfos = await dependencyInfoResource.ResolvePackages( - packageId, configuration.Prerelease, framework, cacheContext, logger, CancellationToken.None); + IEnumerable dependencyInfos = Array.Empty(); + + try + { + dependencyInfos = await dependencyInfoResource.ResolvePackages( + packageId, configuration.Prerelease, framework, cacheContext, logger, CancellationToken.None); + } + catch (AggregateException ex) when (!(ex.InnerException is null)) + { + "chocolatey".Log().Warn(ex.InnerException.Message); + } + catch (Exception ex) + { + "chocolatey".Log().Warn(ex.InnerException.Message); + } if (!dependencyInfos.Any()) continue; @@ -407,7 +418,7 @@ public static async Task GetPackageDependencies(string packageId, // Recursion is fun, kids await GetPackageDependencies( - dependency.Id, framework, cacheContext, logger, dependencyInfoResources, availablePackages, dependencyCache, configuration); + dependency.Id, framework, cacheContext, logger, resources, availablePackages, dependencyCache, configuration); } } } @@ -426,8 +437,5 @@ public static async Task GetPackageParents(string packageId, } } } - } - - // ReSharper restore InconsistentNaming } diff --git a/src/chocolatey/infrastructure.app/nuget/NugetEncryptionUtility.cs b/src/chocolatey/infrastructure.app/nuget/NugetEncryptionUtility.cs index a43422ca3c..f7eb65bc47 100644 --- a/src/chocolatey/infrastructure.app/nuget/NugetEncryptionUtility.cs +++ b/src/chocolatey/infrastructure.app/nuget/NugetEncryptionUtility.cs @@ -22,14 +22,12 @@ namespace chocolatey.infrastructure.app.nuget using adapters; using cryptography; - // ReSharper disable InconsistentNaming - public static class NugetEncryptionUtility { private static Lazy _encryptionUtility = new Lazy(() => new DefaultEncryptionUtility()); [EditorBrowsable(EditorBrowsableState.Never)] - public static void initialize_with(Lazy encryptionUtility) + public static void InitializeWith(Lazy encryptionUtility) { _encryptionUtility = encryptionUtility; } @@ -41,19 +39,24 @@ private static IEncryptionUtility EncryptionUtility public static string EncryptString(string cleartextValue) { - return EncryptionUtility.encrypt_string(cleartextValue); + return EncryptionUtility.EncryptString(cleartextValue); } public static string DecryptString(string encryptedString) { - return EncryptionUtility.decrypt_string(encryptedString); + return EncryptionUtility.DecryptString(encryptedString); } public static string GenerateUniqueToken(string caseInsensitiveKey) { - return EncryptionUtility.generate_unique_token(caseInsensitiveKey); + return EncryptionUtility.GenerateUniqueToken(caseInsensitiveKey); } - } - // ReSharper restore InconsistentNaming +#pragma warning disable IDE1006 + [Obsolete("This overload is deprecated and will be removed in v3.")] + [EditorBrowsable(EditorBrowsableState.Never)] + public static void initialize_with(Lazy encryptionUtility) + => InitializeWith(encryptionUtility); +#pragma warning restore IDE1006 + } } diff --git a/src/chocolatey/infrastructure.app/nuget/NugetList.cs b/src/chocolatey/infrastructure.app/nuget/NugetList.cs index 6a1c01ad57..3da6b30258 100644 --- a/src/chocolatey/infrastructure.app/nuget/NugetList.cs +++ b/src/chocolatey/infrastructure.app/nuget/NugetList.cs @@ -17,27 +17,19 @@ namespace chocolatey.infrastructure.app.nuget { using System; - using System.Collections; using System.Collections.Generic; - using System.Globalization; - using System.IO.Packaging; using System.Linq; - using System.Runtime.CompilerServices; using System.Threading; using System.Threading.Tasks; + using chocolatey.infrastructure.tolerance; using configuration; using filesystem; using NuGet.Common; - using NuGet.Configuration; - using NuGet.PackageManagement; using NuGet.Packaging; using NuGet.Packaging.Core; - using NuGet.Protocol; using NuGet.Protocol.Core.Types; using NuGet.Versioning; - // ReSharper disable InconsistentNaming - public static class NugetList { public static int LastPackageLimitUsed { get; private set; } @@ -46,41 +38,34 @@ public static class NugetList public static IEnumerable GetPackages(ChocolateyConfiguration configuration, ILogger nugetLogger, IFileSystem filesystem) { - return execute_package_search(configuration, nugetLogger, filesystem).GetAwaiter().GetResult(); + return SearchPackagesAsync(configuration, nugetLogger, filesystem).GetAwaiter().GetResult(); } public static int GetCount(ChocolateyConfiguration configuration, ILogger nugetLogger, IFileSystem filesystem) { - var packageRepositories = NugetCommon.GetRemoteRepositories(configuration, nugetLogger, filesystem); - var packageRepositoriesResources = NugetCommon.GetRepositoryResources(packageRepositories); - string searchTermLower = configuration.Input.to_lower(); + var packageRepositoriesResources = NugetCommon.GetRepositoryResources(configuration, nugetLogger, filesystem); + string searchTermLower = configuration.Input.ToLowerSafe(); SearchFilter searchFilter = new SearchFilter(configuration.Prerelease); searchFilter.IncludeDelisted = configuration.ListCommand.LocalOnly; - + searchFilter.OrderBy = SearchOrderBy.DownloadCount; int totalCount = 0; - foreach (var repositoryResources in packageRepositoriesResources) + foreach (var searchResource in packageRepositoriesResources.SearchResources()) { - if (repositoryResources.searchResource == null) - { - continue; - } - - totalCount += repositoryResources.searchResource.SearchCountAsync(searchTermLower, searchFilter, nugetLogger, CancellationToken.None).GetAwaiter().GetResult(); + totalCount += searchResource.SearchCountAsync(searchTermLower, searchFilter, nugetLogger, CancellationToken.None).GetAwaiter().GetResult(); } return totalCount; } - private async static Task> execute_package_search(ChocolateyConfiguration configuration, ILogger nugetLogger, IFileSystem filesystem) + private async static Task> SearchPackagesAsync(ChocolateyConfiguration configuration, ILogger nugetLogger, IFileSystem filesystem) { ThresholdHit = false; LowerThresholdHit = false; - var packageRepositories = NugetCommon.GetRemoteRepositories(configuration, nugetLogger, filesystem); - var packageRepositoriesResources = NugetCommon.GetRepositoryResources(packageRepositories); - string searchTermLower = configuration.Input.to_lower(); + var packageRepositoryResources = NugetCommon.GetRepositoryResources(configuration, nugetLogger, filesystem); + string searchTermLower = configuration.Input.ToLowerSafe(); SearchFilter searchFilter = new SearchFilter(configuration.Prerelease); searchFilter.IncludeDelisted = configuration.ListCommand.LocalOnly; @@ -141,7 +126,7 @@ private async static Task> execute_package_se if (!configuration.ListCommand.Exact) { - foreach (var repositoryResources in packageRepositoriesResources) + foreach (var repositoryResources in packageRepositoryResources) { var skipNumber = 0; @@ -150,9 +135,9 @@ private async static Task> execute_package_se skipNumber = configuration.ListCommand.PageSize * configuration.ListCommand.Page.GetValueOrDefault(0); } - if (repositoryResources.searchResource != null && version == null) + if ((version == null || repositoryResources.ListResource == null) && repositoryResources.SearchResource != null) { - var takeNumber = get_take_numbers(configuration); + var takeNumber = GetTakeAmount(configuration); var partResults = new HashSet(new ComparePackageSearchMetadataIdOnly()); var latestResults = new List(); @@ -168,7 +153,7 @@ private async static Task> execute_package_se } partResults.Clear(); - partResults.AddRange(await repositoryResources.searchResource.SearchAsync(searchTermLower, searchFilter, skipNumber, takeNumber, nugetLogger, CancellationToken.None)); + partResults.AddRange(await repositoryResources.SearchResource.SearchAsync(searchTermLower, searchFilter, skipNumber, takeNumber, nugetLogger, CancellationToken.None)); skipNumber += takeNumber; perSourceThresholdLimit -= partResults.Count; perSourceThresholdMinLimit -= partResults.Count; @@ -187,7 +172,7 @@ private async static Task> execute_package_se if (versionInfo.PackageSearchMetadata == null) { //This is horribly inefficient, having to get the metadata again but that is the NuGet resources for you - results.Add(await repositoryResources.packageMetadataResource.GetMetadataAsync(new PackageIdentity(result.Identity.Id, versionInfo.Version), cacheContext, nugetLogger, CancellationToken.None)); + results.Add(await repositoryResources.PackageMetadataResource.GetMetadataAsync(new PackageIdentity(result.Identity.Id, versionInfo.Version), cacheContext, nugetLogger, CancellationToken.None)); } else { @@ -201,12 +186,12 @@ private async static Task> execute_package_se results.AddRange(latestResults); } } - else + else if (repositoryResources.ListResource != null) { configuration.Prerelease = configuration.Prerelease || (version != null && version.IsPrerelease); configuration.AllVersions = configuration.AllVersions || (version != null); - var tempResults = await repositoryResources.listResource.ListAsync(searchTermLower, configuration.Prerelease, configuration.AllVersions, false, nugetLogger, CancellationToken.None); + var tempResults = await repositoryResources.ListResource.ListAsync(searchTermLower, configuration.Prerelease, configuration.AllVersions, false, nugetLogger, CancellationToken.None); var enumerator = tempResults.GetEnumeratorAsync(); var perSourceThresholdLimit = thresholdLimit; @@ -246,15 +231,15 @@ private async static Task> execute_package_se { if (configuration.AllVersions) { - foreach (var repositoryResources in packageRepositoriesResources) + foreach (var repositoryResources in packageRepositoryResources) { - results.AddRange(await repositoryResources.packageMetadataResource.GetMetadataAsync( + results.AddRange(await repositoryResources.PackageMetadataResource.GetMetadataAsync( searchTermLower, configuration.Prerelease, false, cacheContext, nugetLogger, CancellationToken.None)); } } else { - var exactPackage = find_package(searchTermLower, configuration, nugetLogger, cacheContext, packageRepositoriesResources.Select(x => x.packageMetadataResource), packageRepositoriesResources.Select(x => x.listResource), version); + var exactPackage = FindPackage(searchTermLower, configuration, nugetLogger, cacheContext, packageRepositoryResources, version); if (exactPackage == null) return new List().AsQueryable(); @@ -281,7 +266,7 @@ private async static Task> execute_package_se if (configuration.ListCommand.ByTagOnly) { - results = results.Where(p => p.Tags.contains(searchTermLower, StringComparison.InvariantCultureIgnoreCase)).ToHashSet(); + results = results.Where(p => p.Tags.ContainsSafe(searchTermLower, StringComparison.InvariantCultureIgnoreCase)).ToHashSet(); } if (configuration.ListCommand.ApprovedOnly) @@ -306,7 +291,7 @@ private async static Task> execute_package_se return results.AsQueryable(); } - private static int get_take_numbers(ChocolateyConfiguration configuration) + private static int GetTakeAmount(ChocolateyConfiguration configuration) { // We calculate the amount of items we take at the same time, while making // sure to take the minimum value of 30 packages which we know is a safe value @@ -320,7 +305,8 @@ private static int get_take_numbers(ChocolateyConfiguration configuration) return 30; } - public static ISet find_all_package_versions(string packageName, ChocolateyConfiguration config, ILogger nugetLogger, ChocolateySourceCacheContext cacheContext, IEnumerable resources) + [Obsolete("Will be removed in v3, use overload with NuGetEndpointResources instead!")] + public static ISet FindAllPackageVersions(string packageName, ChocolateyConfiguration config, ILogger nugetLogger, ChocolateySourceCacheContext cacheContext, IEnumerable resources) { var metadataList = new HashSet(); foreach (var resource in resources) @@ -330,78 +316,95 @@ public static ISet find_all_package_versions(string pack return metadataList; } + public static ISet FindAllPackageVersions(string packageName, ChocolateyConfiguration config, ILogger nugetLogger, ChocolateySourceCacheContext cacheContext, IEnumerable resources) + { + // Currently this method is a duplicate of its overload, + // but using NuGetEndpointResources here gives us more flexibility in the future + // if we need to call one of the other methods if it is possible. + var metadataList = new HashSet(); + + foreach (PackageMetadataResource resource in resources.MetadataResources()) + { + metadataList.AddRange(resource.GetMetadataAsync(packageName, config.Prerelease, false, cacheContext, nugetLogger, CancellationToken.None).GetAwaiter().GetResult()); + } + return metadataList; + } + /// /// Searches for packages that are available based on name and other options /// /// Name of package to search for /// Chocolatey configuration used to help supply the search parameters /// The nuget logger - /// The PackageMetaDataResources that should be queried - /// The ListResources that should be queried + /// The resources that should be queried /// Version to search for /// Settings for caching of results from sources /// One result or nothing - public static IPackageSearchMetadata find_package( + public static IPackageSearchMetadata FindPackage( string packageName, ChocolateyConfiguration config, ILogger nugetLogger, ChocolateySourceCacheContext cacheContext, - IEnumerable packageMetadataResources, - IEnumerable listResources, + IEnumerable resources, NuGetVersion version = null) { - // We can only use the optimized ListResource query when the user has asked us to, via the UsePackageRepositoryOptimizations - // feature, as well as when a ListResource exists for the feed in question. Some technologies, such as Sleet or Baget, only - // offer V3 feeds, not V2, and as a result, no ListResource is available. - if (config.Features.UsePackageRepositoryOptimizations && listResources.Any()) + var packagesList = new HashSet(); + var packageNameLower = packageName.ToLowerSafe(); + + foreach (var resource in resources) { if (version is null) { - // We only need to force a lower case package name when we - // are using our own repository optimization queries. - var packageNameLower = packageName.to_lower(); - var metadataList = new HashSet(); - - foreach (var listResource in listResources) + // We can only use the optimized ListResource query when the user has asked us to, via the UsePackageRepositoryOptimizations + // feature, as well as when a ListResource exists for the feed in question. Some technologies, such as Sleet or Baget, only + // offer V3 feeds, not V2, and as a result, no ListResource is available. + if (config.Features.UsePackageRepositoryOptimizations && resource.ListResource != null) { - var package = listResource.PackageAsync(packageNameLower, config.Prerelease, nugetLogger, CancellationToken.None).GetAwaiter().GetResult(); - if (package != null) + var package = FaultTolerance.TryCatchWithLoggingException( + () => resource.ListResource.PackageAsync(packageNameLower, config.Prerelease, nugetLogger, CancellationToken.None).GetAwaiter().GetResult(), + errorMessage: "Unable to connect to source '{0}'".FormatWith(resource.Source.PackageSource.Source), + throwError: false, + logWarningInsteadOfError: true); + + if (!(package is null)) { - metadataList.Add(package); + packagesList.Add(package); } } + else + { + var packages = FaultTolerance.TryCatchWithLoggingException( + () => resource.PackageMetadataResource.GetMetadataAsync(packageNameLower, config.Prerelease, includeUnlisted: false, sourceCacheContext: cacheContext, log: nugetLogger, token: CancellationToken.None).GetAwaiter().GetResult(), + errorMessage: "Unable to connect to source '{0}'".FormatWith(resource.Source.PackageSource.Source), + throwError: false, + logWarningInsteadOfError: true).OrEmpty(); - return metadataList.OrderByDescending(p => p.Identity.Version).FirstOrDefault(); + packagesList.AddRange(packages); + } } - } - else - { - if (version is null) + else { - var metadataList = new HashSet(); + var package = FaultTolerance.TryCatchWithLoggingException( + () => resource.PackageMetadataResource.GetMetadataAsync(new PackageIdentity(packageNameLower, version), cacheContext, nugetLogger, CancellationToken.None).GetAwaiter().GetResult(), + errorMessage: "Unable to connect to source '{0}'".FormatWith(resource.Source.PackageSource.Source), + throwError: false, + logWarningInsteadOfError: true); - foreach (var packageMetadataResource in packageMetadataResources) + if (!(package is null)) { - metadataList.AddRange(packageMetadataResource.GetMetadataAsync(packageName, config.Prerelease, false, cacheContext, nugetLogger, CancellationToken.None).GetAwaiter().GetResult()); + packagesList.Add(package); } - - return metadataList.OrderByDescending(p => p.Identity.Version).FirstOrDefault(); } } - foreach (var resource in packageMetadataResources) - { - var metadata = resource.GetMetadataAsync(new PackageIdentity(packageName, version), cacheContext, nugetLogger, CancellationToken.None).GetAwaiter().GetResult(); - - if (metadata != null) - { - return metadata; - } - } - - //If no packages found, then return nothing - return null; + return packagesList.OrderByDescending(p => p.Identity.Version).FirstOrDefault(); } + +#pragma warning disable IDE1006 + [Obsolete("This overload is deprecated and will be removed in v3.")] + public static ISet find_all_package_versions(string packageName, ChocolateyConfiguration config, ILogger nugetLogger, ChocolateySourceCacheContext cacheContext, IEnumerable resources) + => FindAllPackageVersions(packageName, config, nugetLogger, cacheContext, resources); +#pragma warning restore IDE1006 } public class ComparePackageSearchMetadataIdOnly: IEqualityComparer @@ -456,7 +459,4 @@ public int GetHashCode(IPackageSearchMetadata obj) return obj.Identity.GetHashCode(); } } - - - // ReSharper restore InconsistentNaming } diff --git a/src/chocolatey/infrastructure.app/nuget/NugetPack.cs b/src/chocolatey/infrastructure.app/nuget/NugetPack.cs index c3474b24fb..994d58e557 100644 --- a/src/chocolatey/infrastructure.app/nuget/NugetPack.cs +++ b/src/chocolatey/infrastructure.app/nuget/NugetPack.cs @@ -26,8 +26,6 @@ namespace chocolatey.infrastructure.app.nuget using NuGet.Configuration; using NuGet.Packaging; - // ReSharper disable InconsistentNaming - public sealed class NugetPack { public static bool BuildPackage(PackageBuilder builder, IFileSystem fileSystem, string outputPath) @@ -35,10 +33,10 @@ public static bool BuildPackage(PackageBuilder builder, IFileSystem fileSystem, ExcludeFiles(builder.Files); // Track if the package file was already present on disk - bool isExistingPackage = fileSystem.file_exists(outputPath); + bool isExistingPackage = fileSystem.FileExists(outputPath); try { - using (Stream stream = fileSystem.create_file(outputPath)) + using (Stream stream = fileSystem.CreateFile(outputPath)) { // Truncate if needed, as Mono fails to truncate if (stream.Length > 0) @@ -50,9 +48,9 @@ public static bool BuildPackage(PackageBuilder builder, IFileSystem fileSystem, } catch { - if (!isExistingPackage && fileSystem.file_exists(outputPath)) + if (!isExistingPackage && fileSystem.FileExists(outputPath)) { - fileSystem.delete_file(outputPath); + fileSystem.DeleteFile(outputPath); } throw; } @@ -65,7 +63,7 @@ private static void ExcludeFiles(ICollection packageFiles) // Always exclude the nuspec file // Review: This exclusion should be done by the package builder because it knows which file would collide with the auto-generated // manifest file. - var filter = Platform.get_platform() == PlatformType.Windows ? @"**\*" : "**/*"; + var filter = Platform.GetPlatform() == PlatformType.Windows ? @"**\*" : "**/*"; var excludes = new HashSet(StringComparer.OrdinalIgnoreCase); var wildCards = excludes.Concat(new[] { filter + PackagingConstants.ManifestExtension, filter + NuGetConstants.PackageExtension }); @@ -83,6 +81,4 @@ private static string ResolvePath(IPackageFile packageFile) return physicalPackageFile.SourcePath; } } - - // ReSharper restore InconsistentNaming } diff --git a/src/chocolatey/infrastructure.app/nuget/NugetPush.cs b/src/chocolatey/infrastructure.app/nuget/NugetPush.cs index d7a14ba5d7..daec85fda5 100644 --- a/src/chocolatey/infrastructure.app/nuget/NugetPush.cs +++ b/src/chocolatey/infrastructure.app/nuget/NugetPush.cs @@ -21,17 +21,14 @@ namespace chocolatey.infrastructure.app.nuget using logging; using System.Collections.Generic; using System.Linq; - using System.Threading.Tasks; using filesystem; using NuGet.Common; - using NuGet.Configuration; - using NuGet.Protocol; using NuGet.Protocol.Core.Types; using System.Net.Http; public class NugetPush { - public static void push_package(ChocolateyConfiguration config, string nupkgFilePath, ILogger nugetLogger, string nupkgFileName, IFileSystem filesystem) + public static void PushPackage(ChocolateyConfiguration config, string nupkgFilePath, ILogger nugetLogger, string nupkgFileName, IFileSystem filesystem) { var timeout = TimeSpan.FromSeconds(Math.Abs(config.CommandExecutionTimeoutSeconds)); if (timeout.Seconds <= 0) @@ -46,8 +43,8 @@ public static void push_package(ChocolateyConfiguration config, string nupkgFile const bool skipDuplicate = false; //OK to use FirstOrDefault in this case as the command validates that there is only one source - SourceRepository sourceRepository = NugetCommon.GetRemoteRepositories(config, nugetLogger, filesystem).FirstOrDefault(); - PackageUpdateResource packageUpdateResource = sourceRepository.GetResource(); + NuGetEndpointResources sourceEndpoint = NugetCommon.GetRepositoryResources(config, nugetLogger, filesystem).FirstOrDefault(); + PackageUpdateResource packageUpdateResource = sourceEndpoint.PackageUpdateResource; var nupkgFilePaths = new List() { nupkgFilePath }; try @@ -72,7 +69,7 @@ public static void push_package(ChocolateyConfiguration config, string nupkgFile { if (config.Sources == ApplicationParameters.ChocolateyCommunityFeedPushSource && message.Contains("already exists and cannot be modified")) { - throw new ApplicationException("An error has occurred. This package version already exists on the repository and cannot be modified.{0}Package versions that are approved, rejected, or exempted cannot be modified.{0}See https://docs.chocolatey.org/en-us/community-repository/moderation/ for more information".format_with(Environment.NewLine), ex); + throw new ApplicationException("An error has occurred. This package version already exists on the repository and cannot be modified.{0}Package versions that are approved, rejected, or exempted cannot be modified.{0}See https://docs.chocolatey.org/en-us/community-repository/moderation/ for more information".FormatWith(Environment.NewLine), ex); } if (message.Contains("406") || message.Contains("409")) @@ -85,7 +82,13 @@ public static void push_package(ChocolateyConfiguration config, string nupkgFile throw; } - "chocolatey".Log().Info(ChocolateyLoggers.Important, () => "{0} was pushed successfully to {1}".format_with(nupkgFileName, config.Sources)); + "chocolatey".Log().Info(ChocolateyLoggers.Important, () => "{0} was pushed successfully to {1}".FormatWith(nupkgFileName, config.Sources)); } + +#pragma warning disable IDE1006 + [Obsolete("This overload is deprecated and will be removed in v3.")] + public static void push_package(ChocolateyConfiguration config, string nupkgFilePath, ILogger nugetLogger, string nupkgFileName, IFileSystem filesystem) + => PushPackage(config, nupkgFilePath, nugetLogger, nupkgFileName, filesystem); +#pragma warning restore IDE1006 } } diff --git a/src/chocolatey/infrastructure.app/registration/ChocolateyRegistrationModule.cs b/src/chocolatey/infrastructure.app/registration/ChocolateyRegistrationModule.cs index 5d293ced5e..334b8aa580 100644 --- a/src/chocolatey/infrastructure.app/registration/ChocolateyRegistrationModule.cs +++ b/src/chocolatey/infrastructure.app/registration/ChocolateyRegistrationModule.cs @@ -35,61 +35,70 @@ namespace chocolatey.infrastructure.app.registration using chocolatey.infrastructure.rules; using chocolatey.infrastructure.app.rules; using System.Linq; + using System; + using System.Security.AccessControl; internal class ChocolateyRegistrationModule : IExtensionModule { - public void register_dependencies(IContainerRegistrator registrator, ChocolateyConfiguration configuration) + public void RegisterDependencies(IContainerRegistrator registrator, ChocolateyConfiguration configuration) { // Should be replaced by a extension registration instead of a full configuration // Which would be possible to override by any extension, which we most likely do // not want in the long run. - registrator.register_service(); - registrator.register_service(); + registrator.RegisterService(); + registrator.RegisterService(); //nuget - registrator.register_service(); - registrator.register_service(); + registrator.RegisterService(); + registrator.RegisterService(); //registrator.register_service(); - registrator.register_service(); - registrator.register_service(); - registrator.register_service(); - registrator.register_service(); - registrator.register_service(); - registrator.register_service(); - registrator.register_service(); - registrator.register_instance((resolver) => new CryptoHashProvider(resolver.resolve())); - registrator.register_service(); - registrator.register_service(); - registrator.register_service(); - registrator.register_service(); - registrator.register_service(); - registrator.register_instance(() => new adapters.CustomString(string.Empty)); + registrator.RegisterService(); + registrator.RegisterService(); + registrator.RegisterService(); + registrator.RegisterService(); + registrator.RegisterService(); + registrator.RegisterService(); + registrator.RegisterService(); + registrator.RegisterInstance((resolver) => new CryptoHashProvider(resolver.Resolve())); + registrator.RegisterService(); + registrator.RegisterService(); + registrator.RegisterService(); + registrator.RegisterService(); + registrator.RegisterService(); + registrator.RegisterInstance(() => new adapters.CustomString(string.Empty)); + + registrator.RegisterSourceRunner(); + registrator.RegisterSourceRunner(); + registrator.RegisterSourceRunner(); + registrator.RegisterSourceRunner(); - registrator.register_service( - typeof(INugetService), - typeof(WindowsFeatureService), - typeof(CygwinService), - typeof(PythonService), - typeof(RubyGemsService)); + registrator.RegisterService( + typeof(INugetService)); - registrator.register_service(); + registrator.RegisterService(); - registrator.register_service( + registrator.RegisterService( typeof(RemovePendingPackagesTask)); - registrator.register_service( + registrator.RegisterService( typeof(GlobalConfigurationValidation), typeof(SystemStateValidation)); // Rule registrations - registrator.register_service(); + registrator.RegisterService(); var availableRules = GetType().Assembly .GetTypes() .Where(t => !t.IsInterface && !t.IsAbstract && typeof(IMetadataRule).IsAssignableFrom(t)) .ToArray(); - registrator.register_service(availableRules); + registrator.RegisterService(availableRules); } + +#pragma warning disable IDE1006 + [Obsolete("This overload is deprecated and will be removed in v3.")] + public void register_dependencies(IContainerRegistrator registrator, ChocolateyConfiguration configuration) + => RegisterDependencies(registrator, configuration); +#pragma warning restore IDE1006 } } diff --git a/src/chocolatey/infrastructure.app/registration/ContainerBinding.cs b/src/chocolatey/infrastructure.app/registration/ContainerBinding.cs index afc4637d44..b4e136ea36 100644 --- a/src/chocolatey/infrastructure.app/registration/ContainerBinding.cs +++ b/src/chocolatey/infrastructure.app/registration/ContainerBinding.cs @@ -51,24 +51,24 @@ public IEnumerable RegisterComponents(Container container) { var availableExtensions = new List(); - var configuration = Config.get_configuration_settings(); + var configuration = Config.GetConfigurationSettings(); var registrator = new SimpleInjectorContainerRegistrator(); // We can not resolve this class, as that will prevent future registrations var fileSystem = new DotNetFileSystem(); - var xmlService = new XmlService(fileSystem, new cryptography.CryptoHashProvider(fileSystem)); + var xmlService = new XmlService(fileSystem, new CryptoHashProvider(fileSystem)); var mainRegistrator = new ChocolateyRegistrationModule(); registrator.CanReplaceRegister = true; - registrator.register_instance(() => fileSystem); - registrator.register_instance(() => Config.get_configuration_settings()); - mainRegistrator.register_dependencies(registrator, configuration); - registrator.register_assembly_commands(Assembly.GetExecutingAssembly()); + registrator.RegisterInstance(() => fileSystem); + registrator.RegisterInstance(() => Config.GetConfigurationSettings()); + mainRegistrator.RegisterDependencies(registrator, configuration); + registrator.RegisterAssemblyCommands(Assembly.GetExecutingAssembly()); registrator.CanReplaceRegister = false; - var assemblies = fileSystem.get_extension_assemblies(); - var currentAssemblyVersionString = VersionInformation.get_current_assembly_version(); + var assemblies = fileSystem.GetExtensionAssemblies(); + var currentAssemblyVersionString = VersionInformation.GetCurrentAssemblyVersion(); Version currentAssemblyVersion; if (!Version.TryParse(currentAssemblyVersionString, out currentAssemblyVersion)) { @@ -77,13 +77,13 @@ public IEnumerable RegisterComponents(Container container) var arguments = Environment.GetCommandLineArgs(); - var disableCompatibilityChecks = ConfigurationBuilder.is_compatibility_checks_disabled(fileSystem, xmlService) || - arguments.Any(a => a.is_equal_to("--skip-compatibility-checks")); + var disableCompatibilityChecks = ConfigurationBuilder.AreCompatibilityChecksDisabled(fileSystem, xmlService) || + arguments.Any(a => a.IsEqualTo("--skip-compatibility-checks")); - var chocoVersion = NuGetVersion.Parse(VersionInformation.get_current_assembly_version()); - registrator = register_extensions(availableExtensions, configuration, registrator, assemblies, currentAssemblyVersion, chocoVersion, disableCompatibilityChecks); + var chocoVersion = NuGetVersion.Parse(VersionInformation.GetCurrentAssemblyVersion()); + registrator = RegisterExtensions(availableExtensions, configuration, registrator, assemblies, currentAssemblyVersion, chocoVersion, disableCompatibilityChecks); - container = registrator.build_container(container); + container = registrator.BuildContainer(container); var availableExtensionsArray = availableExtensions.Distinct().ToArray(); @@ -100,13 +100,13 @@ public IEnumerable RegisterComponents(Container container) return availableExtensionsArray; } - private SimpleInjectorContainerRegistrator register_extensions(List availableExtensions, ChocolateyConfiguration configuration, SimpleInjectorContainerRegistrator registrator, IEnumerable assemblies, Version currentAssemblyVersion, NuGetVersion chocoVersion, bool disableCompatibilityChecks) + private SimpleInjectorContainerRegistrator RegisterExtensions(List availableExtensions, ChocolateyConfiguration configuration, SimpleInjectorContainerRegistrator registrator, IEnumerable assemblies, Version currentAssemblyVersion, NuGetVersion chocoVersion, bool disableCompatibilityChecks) { foreach (var assembly in assemblies) { var assemblyName = assembly.GetName().Name; var extensionInformation = new ExtensionInformation(assembly); - var minimumChocolateyVersionString = VersionInformation.get_minimum_chocolatey_version(assembly); + var minimumChocolateyVersionString = VersionInformation.GetMinimumChocolateyVersion(assembly); Version minimumChocolateyVersion; if (!disableCompatibilityChecks && Version.TryParse(minimumChocolateyVersionString, out minimumChocolateyVersion) && currentAssemblyVersion < minimumChocolateyVersion) @@ -132,7 +132,7 @@ You can override this compatibility check and force loading the extension by pas try { - var registrationClasses = assembly.get_extension_modules(); + var registrationClasses = assembly.GetExtensionModules(); this.Log().Debug("Trying to load and register extension '{0}'", assemblyName); @@ -151,14 +151,14 @@ You can override this compatibility check and force loading the extension by pas this.Log().Debug("Calling registration module '{0}' in extension '{1}'!", registration.GetType().Name, assemblyName); clonedRegistrator._validationHandlers.Clear(); - clonedRegistrator.register_validator((instanceType) => validate_minimum_chocolatey_version(instanceType, chocoVersion)); - registration.register_dependencies(clonedRegistrator, configuration.deep_copy()); + clonedRegistrator.RegisterValidator((instanceType) => ValidateMinimumChocolateyVersion(instanceType, chocoVersion)); + registration.RegisterDependencies(clonedRegistrator, configuration.DeepCopy()); hasRegisteredDependencies = !clonedRegistrator.RegistrationFailed; } if (hasRegisteredDependencies) { - clonedRegistrator.register_assembly_commands(assembly); + clonedRegistrator.RegisterAssemblyCommands(assembly); hasRegisteredDependencies = !clonedRegistrator.RegistrationFailed; } @@ -188,7 +188,7 @@ You can override this compatibility check and force loading the extension by pas { registrator.CanReplaceRegister = false; - if (hasRegisteredDependencies || !extensionInformation.Name.is_equal_to("chocolatey.licensed")) + if (hasRegisteredDependencies || !extensionInformation.Name.IsEqualTo("chocolatey.licensed")) { availableExtensions.Add(extensionInformation); } @@ -198,14 +198,17 @@ You can override this compatibility check and force loading the extension by pas return registrator; } - private bool validate_minimum_chocolatey_version(Type instanceType, NuGetVersion chocoVersion) + private bool ValidateMinimumChocolateyVersion(Type instanceType, NuGetVersion chocoVersion) { if (instanceType == null) { return false; } - var methodImpl = instanceType.GetMethod("supports_chocolatey", BindingFlags.Static | BindingFlags.Public); + // NOTE: This method, SupportsChocolatey, does not currently exist anywhere in our code bases. + // This validation check was put in place for future proofing the interaction between Chocolatey + // and its consumers. + var methodImpl = instanceType.GetMethod("SupportsChocolatey", BindingFlags.Static | BindingFlags.Public); if (methodImpl == null) { @@ -222,6 +225,4 @@ private bool validate_minimum_chocolatey_version(Type instanceType, NuGetVersion } } } - - // ReSharper restore InconsistentNaming } diff --git a/src/chocolatey/infrastructure.app/registration/IContainerRegistrator.cs b/src/chocolatey/infrastructure.app/registration/IContainerRegistrator.cs index 6fc28e0d26..027c3975b0 100644 --- a/src/chocolatey/infrastructure.app/registration/IContainerRegistrator.cs +++ b/src/chocolatey/infrastructure.app/registration/IContainerRegistrator.cs @@ -21,20 +21,49 @@ public interface IContainerRegistrator { bool RegistrationFailed { get; } + void RegisterValidator(Func validation_func); + + void RegisterService(bool transient = false) + where TImplementation : class, TService; + + void RegisterService(params Type[] types); + + void RegisterSourceRunner() + where TService : class; + + void RegisterSourceRunner(Type serviceType); + + void RegisterInstance(Func instance) + where TImplementation : class; + + void RegisterInstance(Func instance) + where TImplementation : class, TService; + + void RegisterInstance(Func instance) + where TImplementation : class, TService; + +#pragma warning disable IDE1006 + [Obsolete("This overload is deprecated and will be removed in v3.")] void register_validator(Func validation_func); + [Obsolete("This overload is deprecated and will be removed in v3.")] void register_service(bool transient = false) where TImplementation : class, TService; + [Obsolete("This overload is deprecated and will be removed in v3.")] void register_service(params Type[] types); + [Obsolete("This overload is deprecated and will be removed in v3.")] void register_instance(Func instance) where TImplementation : class; + [Obsolete("This overload is deprecated and will be removed in v3.")] void register_instance(Func instance) where TImplementation : class, TService; + [Obsolete("This overload is deprecated and will be removed in v3.")] void register_instance(Func instance) where TImplementation : class, TService; +#pragma warning restore IDE1006 } } diff --git a/src/chocolatey/infrastructure.app/registration/IContainerResolver.cs b/src/chocolatey/infrastructure.app/registration/IContainerResolver.cs index 8555831e3d..89788e0343 100644 --- a/src/chocolatey/infrastructure.app/registration/IContainerResolver.cs +++ b/src/chocolatey/infrastructure.app/registration/IContainerResolver.cs @@ -16,14 +16,25 @@ namespace chocolatey.infrastructure.app.registration { + using System; using System.Collections.Generic; public interface IContainerResolver { + TService Resolve() + where TService : class; + + IEnumerable ResolveAll() + where TService : class; + +#pragma warning disable IDE1006 + [Obsolete("This overload is deprecated and will be removed in v3.")] TService resolve() where TService : class; + [Obsolete("This overload is deprecated and will be removed in v3.")] IEnumerable resolve_all() where TService : class; +#pragma warning restore IDE1006 } } diff --git a/src/chocolatey/infrastructure.app/registration/IExtensionConfiguration.cs b/src/chocolatey/infrastructure.app/registration/IExtensionConfiguration.cs index 0ae88bcb14..e36bdc73bc 100644 --- a/src/chocolatey/infrastructure.app/registration/IExtensionConfiguration.cs +++ b/src/chocolatey/infrastructure.app/registration/IExtensionConfiguration.cs @@ -34,6 +34,11 @@ public interface IExtensionConfiguration /// /// The initial configuration for the settings. /// This is not used, and is only a placeholder for the future. + object CreateInitialExtensionConfiguration(); + +#pragma warning disable IDE1006 + [Obsolete("This overload is deprecated and will be removed in v3.")] object create_initial_extension_configuration(); +#pragma warning restore IDE1006 } } diff --git a/src/chocolatey/infrastructure.app/registration/IExtensionEnvironment.cs b/src/chocolatey/infrastructure.app/registration/IExtensionEnvironment.cs index f2d9eba3f7..4984b9abe1 100644 --- a/src/chocolatey/infrastructure.app/registration/IExtensionEnvironment.cs +++ b/src/chocolatey/infrastructure.app/registration/IExtensionEnvironment.cs @@ -16,6 +16,7 @@ namespace chocolatey.infrastructure.app.registration { + using System; using System.Collections.Generic; using chocolatey.infrastructure.app.configuration; @@ -30,6 +31,11 @@ public interface IExtensionEnvironment /// The configuration used for the entire chocolatey ecosystem. /// The configuration values that needs to be set as environment variables. /// This is not used, and is only a placeholder for the future. + IDictionary GetEnvironmentConfiguration(ChocolateyConfiguration config); + +#pragma warning disable IDE1006 + [Obsolete("This overload is deprecated and will be removed in v3.")] IDictionary get_environment_configuration(ChocolateyConfiguration config); +#pragma warning restore IDE1006 } } diff --git a/src/chocolatey/infrastructure.app/registration/IExtensionModule.cs b/src/chocolatey/infrastructure.app/registration/IExtensionModule.cs index 56ec7d85a1..c11116ca26 100644 --- a/src/chocolatey/infrastructure.app/registration/IExtensionModule.cs +++ b/src/chocolatey/infrastructure.app/registration/IExtensionModule.cs @@ -17,9 +17,15 @@ namespace chocolatey.infrastructure.app.registration { using chocolatey.infrastructure.app.configuration; + using System; public interface IExtensionModule { + void RegisterDependencies(IContainerRegistrator registrator, ChocolateyConfiguration configuration); + +#pragma warning disable IDE1006 + [Obsolete("This overload is deprecated and will be removed in v3.")] void register_dependencies(IContainerRegistrator registrator, ChocolateyConfiguration configuration); +#pragma warning restore IDE1006 } } diff --git a/src/chocolatey/infrastructure.app/registration/SimpleInjectorContainerRegistrator.cs b/src/chocolatey/infrastructure.app/registration/SimpleInjectorContainerRegistrator.cs index 78bf595f11..3c2e5dd824 100644 --- a/src/chocolatey/infrastructure.app/registration/SimpleInjectorContainerRegistrator.cs +++ b/src/chocolatey/infrastructure.app/registration/SimpleInjectorContainerRegistrator.cs @@ -23,6 +23,7 @@ namespace chocolatey.infrastructure.app.registration using System.Reflection; using chocolatey.infrastructure.adapters; using chocolatey.infrastructure.app.attributes; + using chocolatey.infrastructure.app.services; using infrastructure.commands; using infrastructure.events; using infrastructure.services; @@ -60,7 +61,7 @@ public SimpleInjectorContainerRegistrator() public object Clone() { var cloned = (SimpleInjectorContainerRegistrator)MemberwiseClone(); - cloned._allCommands = _allCommands.deep_copy(); + cloned._allCommands = _allCommands.DeepCopy(); cloned._instanceActionRegistrations = new ConcurrentDictionary>(); foreach (var instanceRegistration in _instanceActionRegistrations) @@ -71,20 +72,20 @@ public object Clone() cloned._instanceActionRegistrations.TryAdd(key, value); } - cloned._multiServices = _multiServices.deep_copy(); - cloned._registeredCommands = _registeredCommands.deep_copy(); - cloned._singletonServices = _singletonServices.deep_copy(); - cloned._transientServices = _transientServices.deep_copy(); + cloned._multiServices = _multiServices.DeepCopy(); + cloned._registeredCommands = _registeredCommands.DeepCopy(); + cloned._singletonServices = _singletonServices.DeepCopy(); + cloned._transientServices = _transientServices.DeepCopy(); cloned._validationHandlers = new List>(); return cloned; } - public void register_assembly_commands(IAssembly assembly) + public void RegisterAssemblyCommands(IAssembly assembly) { try { - var types = assembly.get_loadable_types() + var types = assembly.GetLoadableTypes() .Where(t => t.IsClass && !t.IsAbstract && typeof(ICommand).IsAssignableFrom(t) && @@ -97,7 +98,7 @@ public void register_assembly_commands(IAssembly assembly) break; } - register_command(t); + RegisterCommand(t); } } catch (Exception ex) @@ -108,11 +109,11 @@ public void register_assembly_commands(IAssembly assembly) } } - public void register_command(Type commandType) + public void RegisterCommand(Type commandType) { - ensure_not_built(); + EnsureNotBuilt(); - if (!can_register_service(commandType)) + if (!CanRegisterService(commandType)) { return; } @@ -121,22 +122,22 @@ public void register_command(Type commandType) if (commandForAttribute == null) { - throw new ArgumentException("{0} does not register a specific command!".format_with(commandType.Name)); + throw new ArgumentException("{0} does not register a specific command!".FormatWith(commandType.Name)); } if (!commandType.GetInterfaces().Contains(typeof(ICommand))) { - throw new ArgumentException("{0} does not implement the interface 'ICommand'. All commands must implement this interface!".format_with(commandType.Name)); + throw new ArgumentException("{0} does not implement the interface 'ICommand'. All commands must implement this interface!".FormatWith(commandType.Name)); } - var commandName = get_command_name(commandForAttribute); + var commandName = GetCommandName(commandForAttribute); _registeredCommands.AddOrUpdate(commandName, addValueFactory: (key) => { var commandTypeAttributes = commandType.GetCustomAttributes(typeof(CommandForAttribute), false).Cast(); - validate_commands_replacement(commandTypeAttributes); + ValidateCommandReplacements(commandTypeAttributes); - add_commands(commandTypeAttributes); + AddCommands(commandTypeAttributes); this.Log().Debug("Registering new command '{0}' in assembly '{1}'", commandName, @@ -144,7 +145,7 @@ public void register_command(Type commandType) return commandType; }, updateValueFactory: (key, value) => { - if (!value.Assembly.FullName.is_equal_to(_chocoAssembly.FullName) && !commandType.IsAssignableFrom(value)) + if (!value.Assembly.FullName.IsEqualTo(_chocoAssembly.FullName) && !commandType.IsAssignableFrom(value)) { // We do not allow extensions to override eachothers command. // This may change in the future to allow multiple command handlers. @@ -156,21 +157,21 @@ public void register_command(Type commandType) return value; } - validate_replace_permissions(); + ValidateReplacePermissions(); - var removedCommands = remove_commands(value, commandName).ToList(); + var removedCommands = RemoveCommands(value, commandName).ToList(); try { var commandTypeAttributes = commandType.GetCustomAttributes(typeof(CommandForAttribute), false).Cast(); - validate_commands_replacement(commandTypeAttributes); + ValidateCommandReplacements(commandTypeAttributes); this.Log().Debug("Replacing existing command '{0}' from assembly '{1}' with implementation in assembly '{2}'", commandName, value.Assembly.GetName().Name, commandType.Assembly.GetName().Name); - add_commands(commandTypeAttributes); + AddCommands(commandTypeAttributes); } catch (Exception ex) { @@ -183,52 +184,107 @@ public void register_command(Type commandType) }); } - public void register_instance(Func instance) + public void RegisterInstance(Func instance) where TImplementation : class, TService { - register_instance((container) => instance()); + RegisterInstance((container) => instance()); } - public void register_instance(Func instance) + public void RegisterInstance(Func instance) where TImplementation : class, TService { - register_instance(typeof(TService), (container) => instance(container)); + RegisterInstance(typeof(TService), (container) => instance(container)); } - public void register_instance(Func instance) + public void RegisterInstance(Func instance) where TImplementation : class { - register_instance(instance); + RegisterInstance(instance); } - public void register_service(params Type[] types) + public void RegisterService(params Type[] types) { foreach (var serviceType in types) { - register_service(typeof(TImplementation), serviceType); + RegisterService(typeof(TImplementation), serviceType); } } - public void register_service(bool transient = false) + public void RegisterService(bool transient = false) where TImplementation : class, TService { var interfaceType = typeof(TService); var serviceType = typeof(TImplementation); - register_service(interfaceType, serviceType, transient); + RegisterService(interfaceType, serviceType, transient); } - public void register_validator(Func validation_func) + public void RegisterValidator(Func validation_func) { _validationHandlers.Add(validation_func); } - internal Container build_container(Container container) + public void RegisterSourceRunner() where TService : class + { + RegisterSourceRunner(typeof(TService)); + } + + public void RegisterSourceRunner(Type serviceType) + { + EnsureNotBuilt(); + + if (!CanRegisterService(serviceType)) + { + return; + } + + if (!typeof(IAlternativeSourceRunner).IsAssignableFrom(serviceType)) + { + return; + } + + AddToMultiServices(typeof(IAlternativeSourceRunner), serviceType); + + foreach (var interfaceType in serviceType.GetInterfaces()) + { + if (interfaceType == typeof(ICountSourceRunner)) + { + AddToMultiServices(interfaceType, serviceType); + } + + if (interfaceType == typeof(IListSourceRunner)) + { + AddToMultiServices(interfaceType, serviceType); + } + + if (interfaceType == typeof(ISearchableSourceRunner)) + { + AddToMultiServices(interfaceType, serviceType); + } + + if (interfaceType == typeof(IInstallSourceRunner)) + { + AddToMultiServices(interfaceType, serviceType); + } + + if (interfaceType == typeof(IUpgradeSourceRunner)) + { + AddToMultiServices(interfaceType, serviceType); + } + + if (interfaceType == typeof(IUninstallSourceRunner)) + { + AddToMultiServices(interfaceType, serviceType); + } + } + } + + internal Container BuildContainer(Container container) { container.RegisterAll(_registeredCommands.Values); - add_services_to_container(container, _singletonServices, Lifestyle.Singleton); - add_services_to_container(container, _transientServices, Lifestyle.Transient); + AddServicesToContainer(container, _singletonServices, Lifestyle.Singleton); + AddServicesToContainer(container, _transientServices, Lifestyle.Transient); foreach (var multiService in _multiServices) { @@ -252,14 +308,14 @@ internal Container build_container(Container container) container.RegisterSingle(); - EventManager.initialize_with(container.GetInstance); + EventManager.InitializeWith(container.GetInstance); _isBuilt = true; return container; } - private static void add_services_to_container(Container container, ConcurrentDictionary services, Lifestyle lifestyle) + private static void AddServicesToContainer(Container container, ConcurrentDictionary services, Lifestyle lifestyle) { foreach (var service in services) { @@ -267,11 +323,11 @@ private static void add_services_to_container(Container container, ConcurrentDic } } - private void add_commands(IEnumerable commandTypeAttributes) + private void AddCommands(IEnumerable commandTypeAttributes) { foreach (var commandFor in commandTypeAttributes) { - var commandName = commandFor.CommandName.to_lower(); + var commandName = commandFor.CommandName.ToLowerSafe(); if (!_allCommands.Contains(commandName)) { @@ -280,12 +336,12 @@ private void add_commands(IEnumerable commandTypeAttributes } } - private void add_to_multi_services(Type interfaceType, Type serviceType) + private void AddToMultiServices(Type interfaceType, Type serviceType) { - ensure_not_built(); - validate_service_registration(interfaceType, serviceType, validate_multi_services: false); + EnsureNotBuilt(); + ValidateServiceRegistrations(interfaceType, serviceType, validate_multi_services: false); - remove_existing_registration(interfaceType); + RemoveRegistration(interfaceType); _multiServices.AddOrUpdate(interfaceType, new List { serviceType }, (key, value) => { @@ -298,7 +354,7 @@ private void add_to_multi_services(Type interfaceType, Type serviceType) }); } - private bool can_register_service(Type serviceType) + private bool CanRegisterService(Type serviceType) { foreach (var validator in _validationHandlers) { @@ -311,7 +367,7 @@ private bool can_register_service(Type serviceType) return true; } - private void ensure_not_built() + private void EnsureNotBuilt() { if (_isBuilt) { @@ -319,9 +375,9 @@ private void ensure_not_built() } } - private string get_command_name(CommandForAttribute commandForAttribute) + private string GetCommandName(CommandForAttribute commandForAttribute) { - var commandName = commandForAttribute.CommandName.to_lower(); + var commandName = commandForAttribute.CommandName.ToLowerSafe(); // First check if we have stored the actual command if (_registeredCommands.ContainsKey(commandName)) @@ -343,7 +399,7 @@ private string get_command_name(CommandForAttribute commandForAttribute) foreach (var aliasCommand in allCommandForAttributes) { - if (aliasCommand.CommandName.is_equal_to(commandName)) + if (aliasCommand.CommandName.IsEqualTo(commandName)) { return command.Key; } @@ -353,24 +409,24 @@ private string get_command_name(CommandForAttribute commandForAttribute) // If we have gotten here, that means all commands have a registered // command for this type, but it can not be found. As such we need to // throw an error so it can be looked at. - throw new ApplicationException("The command '{0}' has been globally registered, but can not be found!".format_with(commandName)); + throw new ApplicationException("The command '{0}' has been globally registered, but can not be found!".FormatWith(commandName)); } - private void register_instance(Type serviceType, Func instanceAction) + private void RegisterInstance(Type serviceType, Func instanceAction) { - ensure_not_built(); + EnsureNotBuilt(); - validate_service_registration(serviceType, serviceType, validate_multi_services: true); - remove_existing_registration(serviceType); + ValidateServiceRegistrations(serviceType, serviceType, validate_multi_services: true); + RemoveRegistration(serviceType); _instanceActionRegistrations.AddOrUpdate(serviceType, instanceAction, (key, value) => instanceAction); } - private void register_service(Type interfaceType, Type serviceType, bool transient = false) + private void RegisterService(Type interfaceType, Type serviceType, bool transient = false) { - ensure_not_built(); + EnsureNotBuilt(); - if (!can_register_service(serviceType)) + if (!CanRegisterService(serviceType)) { return; } @@ -379,12 +435,12 @@ private void register_service(Type interfaceType, Type serviceType, bool transie if (multiServiceAttribute != null && multiServiceAttribute.IsMultiService) { - add_to_multi_services(interfaceType, serviceType); + AddToMultiServices(interfaceType, serviceType); } else { - validate_service_registration(interfaceType, serviceType, validate_multi_services: true); - remove_existing_registration(interfaceType); + ValidateServiceRegistrations(interfaceType, serviceType, validate_multi_services: true); + RemoveRegistration(interfaceType); if (transient) { @@ -397,13 +453,13 @@ private void register_service(Type interfaceType, Type serviceType, bool transie } } - private IEnumerable remove_commands(Type commandType, string initialCommand) + private IEnumerable RemoveCommands(Type commandType, string initialCommand) { var allCommandsForAttribute = commandType.GetCustomAttributes(typeof(CommandForAttribute), false).Cast(); foreach (var commandFor in allCommandsForAttribute) { - var commandName = commandFor.CommandName.to_lower(); + var commandName = commandFor.CommandName.ToLowerSafe(); if (_allCommands.Contains(commandName)) { _allCommands.Remove(commandName); @@ -411,14 +467,14 @@ private IEnumerable remove_commands(Type commandType, string initialComm Type tempType; - if (!commandName.is_equal_to(initialCommand) && _registeredCommands.TryRemove(commandName, out tempType)) + if (!commandName.IsEqualTo(initialCommand) && _registeredCommands.TryRemove(commandName, out tempType)) { yield return commandName; } } } - private void remove_existing_registration(Type interfaceType) + private void RemoveRegistration(Type interfaceType) { Type tempType; Func tempAction; @@ -427,22 +483,22 @@ private void remove_existing_registration(Type interfaceType) _instanceActionRegistrations.TryRemove(interfaceType, out tempAction); } - private void validate_commands_replacement(IEnumerable commandTypeAttributes) + private void ValidateCommandReplacements(IEnumerable commandTypeAttributes) { - validate_replace_permissions(); + ValidateReplacePermissions(); foreach (var commandFor in commandTypeAttributes) { - var commandName = commandFor.CommandName.to_lower(); + var commandName = commandFor.CommandName.ToLowerSafe(); if (_allCommands.Contains(commandName)) { - throw new ApplicationException("The command '{0}' is already registered for a different command handler!".format_with(commandName)); + throw new ApplicationException("The command '{0}' is already registered for a different command handler!".FormatWith(commandName)); } } } - private void validate_replace_permissions() + private void ValidateReplacePermissions() { if (!CanReplaceRegister) { @@ -450,7 +506,7 @@ private void validate_replace_permissions() } } - private void validate_service_registration(Type interfaceType, Type serviceType, bool validate_multi_services) + private void ValidateServiceRegistrations(Type interfaceType, Type serviceType, bool validate_multi_services) { if (interfaceType == typeof(IContainerRegistrator) || serviceType.GetInterfaces().Contains(typeof(IContainerRegistrator))) @@ -474,7 +530,7 @@ private void validate_service_registration(Type interfaceType, Type serviceType, if (!valid) { - throw new ApplicationException("The type '{0}' is not inheriting from '{1}'. Unable to continue the registration.".format_with( + throw new ApplicationException("The type '{0}' is not inheriting from '{1}'. Unable to continue the registration.".FormatWith( serviceType.Name, interfaceType.Name)); } @@ -484,8 +540,46 @@ private void validate_service_registration(Type interfaceType, Type serviceType, _instanceActionRegistrations.ContainsKey(interfaceType) || (validate_multi_services && _multiServices.ContainsKey(interfaceType))) { - validate_replace_permissions(); + ValidateReplacePermissions(); } } + +#pragma warning disable IDE1006 + [Obsolete("This overload is deprecated and will be removed in v3.")] + public void register_assembly_commands(IAssembly assembly) + => RegisterAssemblyCommands(assembly); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public void register_command(Type commandType) + => RegisterCommand(commandType); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public void register_instance(Func instance) + where TImplementation : class, TService + => RegisterInstance(instance); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public void register_instance(Func instance) + where TImplementation : class, TService + => RegisterInstance(instance); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public void register_instance(Func instance) + where TImplementation : class + => RegisterInstance(instance); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public void register_service(params Type[] types) + => RegisterService(types); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public void register_service(bool transient = false) + where TImplementation : class, TService + => RegisterService(transient); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public void register_validator(Func validation_func) + => RegisterValidator(validation_func); +#pragma warning restore IDE1006 } } diff --git a/src/chocolatey/infrastructure.app/registration/SimpleInjectorContainerResolver.cs b/src/chocolatey/infrastructure.app/registration/SimpleInjectorContainerResolver.cs index cff173343b..c36b010fa4 100644 --- a/src/chocolatey/infrastructure.app/registration/SimpleInjectorContainerResolver.cs +++ b/src/chocolatey/infrastructure.app/registration/SimpleInjectorContainerResolver.cs @@ -16,6 +16,7 @@ namespace chocolatey.infrastructure.app.registration { + using System; using System.Collections.Generic; using SimpleInjector; @@ -28,16 +29,28 @@ public SimpleInjectorContainerResolver(Container container) _container = container; } - public TService resolve() + public TService Resolve() where TService : class { return _container.GetInstance(); } - public IEnumerable resolve_all() + public IEnumerable ResolveAll() where TService : class { return _container.GetAllInstances(); } + +#pragma warning disable IDE1006 + [Obsolete("This overload is deprecated and will be removed in v3.")] + public TService resolve() + where TService : class + => Resolve(); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public IEnumerable resolve_all() + where TService : class + => ResolveAll(); +#pragma warning restore IDE1006 } } diff --git a/src/chocolatey/infrastructure.app/rules/EmptyOrInvalidUrlMetadataRule.cs b/src/chocolatey/infrastructure.app/rules/EmptyOrInvalidUrlMetadataRule.cs index e18badd9a2..89662fedba 100644 --- a/src/chocolatey/infrastructure.app/rules/EmptyOrInvalidUrlMetadataRule.cs +++ b/src/chocolatey/infrastructure.app/rules/EmptyOrInvalidUrlMetadataRule.cs @@ -22,7 +22,7 @@ namespace chocolatey.infrastructure.app.rules internal sealed class EmptyOrInvalidUrlMetadataRule : MetadataRuleBase { - public override IEnumerable validate(NuspecReader reader) + public override IEnumerable Validate(NuspecReader reader) { var items = new[] { @@ -37,20 +37,26 @@ public override IEnumerable validate(NuspecReader reader) foreach (var item in items) { - if (has_element(reader, item)) + if (HasElement(reader, item)) { - var value = get_element_value(reader, item); + var value = GetElementValue(reader, item); if (string.IsNullOrWhiteSpace(value)) { - yield return new RuleResult(RuleType.Error, RuleIdentifiers.EmptyRequiredElement, "The {0} element in the package nuspec file cannot be empty.".format_with(item)); + yield return GetRule(RuleIdentifiers.EmptyRequiredElement, "The {0} element in the package nuspec file cannot be empty.".FormatWith(item)); } else if (!Uri.TryCreate(value, UriKind.Absolute, out _)) { - yield return new RuleResult(RuleType.Error, RuleIdentifiers.InvalidTypeElement, "'{0}' is not a valid URL for the {1} element in the package nuspec file.".format_with(value, item)); + yield return GetRule(RuleIdentifiers.InvalidTypeElement, "'{0}' is not a valid URL for the {1} element in the package nuspec file.".FormatWith(value, item)); } } } } + + protected override IEnumerable GetRules() + { + yield return new ImmutableRule(RuleType.Error, RuleIdentifiers.EmptyRequiredElement, "A required element does not contain any content."); + yield return new ImmutableRule(RuleType.Error, RuleIdentifiers.InvalidTypeElement, "The specified content of the element is not of the expected type and can not be accepted."); + } } -} +} \ No newline at end of file diff --git a/src/chocolatey/infrastructure.app/rules/FrameWorkReferencesMetadataRule.cs b/src/chocolatey/infrastructure.app/rules/FrameWorkReferencesMetadataRule.cs index 313fc19850..671aa41dae 100644 --- a/src/chocolatey/infrastructure.app/rules/FrameWorkReferencesMetadataRule.cs +++ b/src/chocolatey/infrastructure.app/rules/FrameWorkReferencesMetadataRule.cs @@ -19,14 +19,19 @@ namespace chocolatey.infrastructure.app.rules using chocolatey.infrastructure.rules; using NuGet.Packaging; - internal sealed class FrameWorkReferencesMetadataRule : MetadataRuleBase + internal class FrameWorkReferencesMetadataRule : MetadataRuleBase { - public override IEnumerable validate(NuspecReader reader) + public override IEnumerable Validate(NuspecReader reader) { - if (has_element(reader, "frameworkReferences")) + if (HasElement(reader, "frameworkReferences")) { - yield return new RuleResult(RuleType.Error, RuleIdentifiers.UnsupportedElementUsed, " elements are not supported in Chocolatey CLI."); + yield return GetRule(RuleIdentifiers.UnsupportedElementUsed, " elements are not supported in Chocolatey CLI."); } } + + protected override IEnumerable GetRules() + { + yield return new ImmutableRule(RuleType.Error, RuleIdentifiers.UnsupportedElementUsed, "Unsupported element is used."); + } } -} +} \ No newline at end of file diff --git a/src/chocolatey/infrastructure.app/rules/IconMetadataRule.cs b/src/chocolatey/infrastructure.app/rules/IconMetadataRule.cs index 6167463676..25e3e46031 100644 --- a/src/chocolatey/infrastructure.app/rules/IconMetadataRule.cs +++ b/src/chocolatey/infrastructure.app/rules/IconMetadataRule.cs @@ -19,14 +19,14 @@ namespace chocolatey.infrastructure.app.rules using chocolatey.infrastructure.rules; using NuGet.Packaging; - internal sealed class IconMetadataRule : IMetadataRule + internal sealed class IconMetadataRule : FrameWorkReferencesMetadataRule { - public IEnumerable validate(NuspecReader reader) + public override IEnumerable Validate(NuspecReader reader) { if (!(reader.GetIcon() is null)) { - yield return new RuleResult(RuleType.Error, RuleIdentifiers.UnsupportedElementUsed, " elements are not supported in Chocolatey CLI, use instead."); + yield return GetRule(RuleIdentifiers.UnsupportedElementUsed, " elements are not supported in Chocolatey CLI, use instead."); } } } -} +} \ No newline at end of file diff --git a/src/chocolatey/infrastructure.app/rules/LicenseMetadataRule.cs b/src/chocolatey/infrastructure.app/rules/LicenseMetadataRule.cs index 074d1b8077..ff86b3818f 100644 --- a/src/chocolatey/infrastructure.app/rules/LicenseMetadataRule.cs +++ b/src/chocolatey/infrastructure.app/rules/LicenseMetadataRule.cs @@ -16,18 +16,17 @@ namespace chocolatey.infrastructure.app.rules { using System.Collections.Generic; - using System.Runtime.CompilerServices; using chocolatey.infrastructure.rules; using NuGet.Packaging; - internal sealed class LicenseMetadataRule : IMetadataRule + internal sealed class LicenseMetadataRule : FrameWorkReferencesMetadataRule { - public IEnumerable validate(NuspecReader reader) + public override IEnumerable Validate(NuspecReader reader) { if (!(reader.GetLicenseMetadata() is null)) { - yield return new RuleResult(RuleType.Error, RuleIdentifiers.UnsupportedElementUsed, " elements are not supported in Chocolatey CLI, use instead."); + yield return GetRule(RuleIdentifiers.UnsupportedElementUsed, " elements are not supported in Chocolatey CLI, use instead."); } } } -} +} \ No newline at end of file diff --git a/src/chocolatey/infrastructure.app/rules/MetadataRuleBase.cs b/src/chocolatey/infrastructure.app/rules/MetadataRuleBase.cs index e0a72d34f0..c02517f966 100644 --- a/src/chocolatey/infrastructure.app/rules/MetadataRuleBase.cs +++ b/src/chocolatey/infrastructure.app/rules/MetadataRuleBase.cs @@ -24,16 +24,44 @@ namespace chocolatey.infrastructure.app.rules public abstract class MetadataRuleBase : IMetadataRule { - public abstract IEnumerable validate(NuspecReader reader); + private IDictionary _cachedRules; - protected static bool has_element(NuspecReader reader, string name) + public abstract IEnumerable Validate(NuspecReader reader); + + public IReadOnlyList GetAvailableRules() + { + if (_cachedRules is null || _cachedRules.Count == 0) + { + _cachedRules = GetRules().ToDictionary(r => r.Id, r => r); + } + + return _cachedRules.Values.ToList().AsReadOnly(); + } + + protected RuleResult GetRule(string id, string summary = null) + { + if (_cachedRules is null || _cachedRules.Count == 0) + { + // Just to populate the cached dictionary + GetAvailableRules(); + } + + if (!_cachedRules.TryGetValue(id, out ImmutableRule result)) + { + throw new ArgumentOutOfRangeException(nameof(id), "No rule with the identifier {0} could be found!".FormatWith(id)); + } + + return RuleResult.FromImmutableRule(result, summary); + } + + protected static bool HasElement(NuspecReader reader, string name) { var metadataNode = reader.Xml.Root.Elements().FirstOrDefault(e => StringComparer.Ordinal.Equals(e.Name.LocalName, "metadata")); return !(metadataNode is null || metadataNode.Elements(XName.Get(name, metadataNode.GetDefaultNamespace().NamespaceName)).FirstOrDefault() is null); } - protected static string get_element_value(NuspecReader reader, string name) + protected static string GetElementValue(NuspecReader reader, string name) { var metadataNode = reader.Xml.Root.Elements().FirstOrDefault(e => StringComparer.Ordinal.Equals(e.Name.LocalName, "metadata")); @@ -51,5 +79,21 @@ protected static string get_element_value(NuspecReader reader, string name) return element.Value; } + + protected abstract IEnumerable GetRules(); + +#pragma warning disable IDE1006 + [Obsolete("This overload is deprecated and will be removed in v3.")] + public virtual IEnumerable validate(NuspecReader reader) + => Validate(reader); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + protected static bool has_element(NuspecReader reader, string name) + => HasElement(reader, name); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + protected static string get_element_value(NuspecReader reader, string name) + => GetElementValue(reader, name); +#pragma warning restore IDE1006 } -} +} \ No newline at end of file diff --git a/src/chocolatey/infrastructure.app/rules/PackageTypesMetadataRule.cs b/src/chocolatey/infrastructure.app/rules/PackageTypesMetadataRule.cs index bb3e8f8f3b..d7de9f58e4 100644 --- a/src/chocolatey/infrastructure.app/rules/PackageTypesMetadataRule.cs +++ b/src/chocolatey/infrastructure.app/rules/PackageTypesMetadataRule.cs @@ -19,14 +19,14 @@ namespace chocolatey.infrastructure.app.rules using chocolatey.infrastructure.rules; using NuGet.Packaging; - internal sealed class PackageTypesMetadataRule : MetadataRuleBase + internal sealed class PackageTypesMetadataRule : FrameWorkReferencesMetadataRule { - public override IEnumerable validate(NuspecReader reader) + public override IEnumerable Validate(NuspecReader reader) { - if (has_element(reader, "packageTypes")) + if (HasElement(reader, "packageTypes")) { - yield return new RuleResult(RuleType.Error, RuleIdentifiers.UnsupportedElementUsed, " elements are not supported in Chocolatey CLI."); + yield return GetRule(RuleIdentifiers.UnsupportedElementUsed, " elements are not supported in Chocolatey CLI."); } } } -} +} \ No newline at end of file diff --git a/src/chocolatey/infrastructure.app/rules/ReadmeMetadataRule.cs b/src/chocolatey/infrastructure.app/rules/ReadmeMetadataRule.cs index 090b86ee7d..b96713d4c4 100644 --- a/src/chocolatey/infrastructure.app/rules/ReadmeMetadataRule.cs +++ b/src/chocolatey/infrastructure.app/rules/ReadmeMetadataRule.cs @@ -19,14 +19,14 @@ namespace chocolatey.infrastructure.app.rules using chocolatey.infrastructure.rules; using NuGet.Packaging; - internal sealed class ReadmeMetadataRule : IMetadataRule + internal sealed class ReadmeMetadataRule : FrameWorkReferencesMetadataRule { - public IEnumerable validate(NuspecReader reader) + public override IEnumerable Validate(NuspecReader reader) { if (!(reader.GetReadme() is null)) { - yield return new RuleResult(RuleType.Error, RuleIdentifiers.UnsupportedElementUsed, " elements are not supported in Chocolatey CLI."); + yield return GetRule(RuleIdentifiers.UnsupportedElementUsed, " elements are not supported in Chocolatey CLI."); } } } -} +} \ No newline at end of file diff --git a/src/chocolatey/infrastructure.app/rules/RepositoryMetadataRule.cs b/src/chocolatey/infrastructure.app/rules/RepositoryMetadataRule.cs index 84e15400fe..f85bea00ae 100644 --- a/src/chocolatey/infrastructure.app/rules/RepositoryMetadataRule.cs +++ b/src/chocolatey/infrastructure.app/rules/RepositoryMetadataRule.cs @@ -21,16 +21,16 @@ namespace chocolatey.infrastructure.app.rules using chocolatey.infrastructure.rules; using NuGet.Packaging; - internal sealed class RepositoryMetadataRule : MetadataRuleBase + internal sealed class RepositoryMetadataRule : FrameWorkReferencesMetadataRule { - public override IEnumerable validate(NuspecReader reader) + public override IEnumerable Validate(NuspecReader reader) { var metadataNode = reader.Xml.Root.Elements().FirstOrDefault(e => StringComparer.Ordinal.Equals(e.Name.LocalName, "metadata")); - if (has_element(reader, "repository")) + if (HasElement(reader, "repository")) { - yield return new RuleResult(RuleType.Error, RuleIdentifiers.UnsupportedElementUsed, " elements are not supported in Chocolatey CLI, use instead."); + yield return GetRule(RuleIdentifiers.UnsupportedElementUsed, " elements are not supported in Chocolatey CLI, use instead."); } } } -} +} \ No newline at end of file diff --git a/src/chocolatey/infrastructure.app/rules/RequireLicenseAcceptanceMetadataRule.cs b/src/chocolatey/infrastructure.app/rules/RequireLicenseAcceptanceMetadataRule.cs index ef58e0585e..6db956d85f 100644 --- a/src/chocolatey/infrastructure.app/rules/RequireLicenseAcceptanceMetadataRule.cs +++ b/src/chocolatey/infrastructure.app/rules/RequireLicenseAcceptanceMetadataRule.cs @@ -19,14 +19,19 @@ namespace chocolatey.infrastructure.app.rules using chocolatey.infrastructure.rules; using NuGet.Packaging; - internal sealed class RequireLicenseAcceptanceMetadataRule : IMetadataRule + internal sealed class RequireLicenseAcceptanceMetadataRule : MetadataRuleBase { - public IEnumerable validate(NuspecReader reader) + public override IEnumerable Validate(NuspecReader reader) { if (string.IsNullOrWhiteSpace(reader.GetLicenseUrl()) && reader.GetRequireLicenseAcceptance()) { - yield return new RuleResult(RuleType.Error, RuleIdentifiers.MissingElementOnRequiringLicenseAcceptance, "Enabling license acceptance requires a license url."); + yield return GetRule(RuleIdentifiers.MissingElementOnRequiringLicenseAcceptance); } } + + protected override IEnumerable GetRules() + { + yield return new ImmutableRule(RuleType.Error, RuleIdentifiers.MissingElementOnRequiringLicenseAcceptance, "Enabling license acceptance requires a license url."); + } } -} +} \ No newline at end of file diff --git a/src/chocolatey/infrastructure.app/rules/RequiredMetadataRule.cs b/src/chocolatey/infrastructure.app/rules/RequiredMetadataRule.cs index 578c7a74d6..9402e4b214 100644 --- a/src/chocolatey/infrastructure.app/rules/RequiredMetadataRule.cs +++ b/src/chocolatey/infrastructure.app/rules/RequiredMetadataRule.cs @@ -21,7 +21,7 @@ namespace chocolatey.infrastructure.app.rules internal sealed class RequiredMetadataRule : MetadataRuleBase { - public override IEnumerable validate(NuspecReader reader) + public override IEnumerable Validate(NuspecReader reader) { var requiredItems = new[] { @@ -33,11 +33,16 @@ public override IEnumerable validate(NuspecReader reader) foreach (var item in requiredItems) { - if (string.IsNullOrWhiteSpace(get_element_value(reader, item))) + if (string.IsNullOrWhiteSpace(GetElementValue(reader, item))) { - yield return new RuleResult(RuleType.Error, RuleIdentifiers.EmptyRequiredElement, "{0} is a required element in the package nuspec file.".format_with(item)); + yield return GetRule(RuleIdentifiers.EmptyRequiredElement, "{0} is a required element in the package nuspec file.".FormatWith(item)); } } } + + protected override IEnumerable GetRules() + { + yield return new ImmutableRule(RuleType.Error, RuleIdentifiers.EmptyRequiredElement, "A required element is missing or has no content in the package nuspec file."); + } } -} +} \ No newline at end of file diff --git a/src/chocolatey/infrastructure.app/rules/ServicableMetadataRule.cs b/src/chocolatey/infrastructure.app/rules/ServicableMetadataRule.cs index ea6fbeb834..61f0b0187f 100644 --- a/src/chocolatey/infrastructure.app/rules/ServicableMetadataRule.cs +++ b/src/chocolatey/infrastructure.app/rules/ServicableMetadataRule.cs @@ -19,14 +19,14 @@ namespace chocolatey.infrastructure.app.rules using chocolatey.infrastructure.rules; using NuGet.Packaging; - internal sealed class ServicableMetadataRule : MetadataRuleBase + internal sealed class ServicableMetadataRule : FrameWorkReferencesMetadataRule { - public override IEnumerable validate(NuspecReader reader) + public override IEnumerable Validate(NuspecReader reader) { - if (has_element(reader, "serviceable")) + if (HasElement(reader, "serviceable")) { - yield return new RuleResult(RuleType.Error, RuleIdentifiers.UnsupportedElementUsed, " elements are not supported in Chocolatey CLI."); + yield return GetRule(RuleIdentifiers.UnsupportedElementUsed, " elements are not supported in Chocolatey CLI."); } } } -} +} \ No newline at end of file diff --git a/src/chocolatey/infrastructure.app/rules/VersionMetadataRule.cs b/src/chocolatey/infrastructure.app/rules/VersionMetadataRule.cs index 1cc290c5b7..2cd0576267 100644 --- a/src/chocolatey/infrastructure.app/rules/VersionMetadataRule.cs +++ b/src/chocolatey/infrastructure.app/rules/VersionMetadataRule.cs @@ -22,16 +22,21 @@ namespace chocolatey.infrastructure.app.rules internal sealed class VersionMetadataRule : MetadataRuleBase { - public override IEnumerable validate(NuspecReader reader) + public override IEnumerable Validate(NuspecReader reader) { - var version = get_element_value(reader, "version"); + var version = GetElementValue(reader, "version"); // We need to check for the $version$ substitution value, as it will not be replaced // before the package gets created - if (!string.IsNullOrEmpty(version) && !version.is_equal_to("$version$") && !NuGetVersion.TryParse(version, out _)) + if (!string.IsNullOrEmpty(version) && !version.IsEqualTo("$version$") && !NuGetVersion.TryParse(version, out _)) { - yield return new RuleResult(RuleType.Error, RuleIdentifiers.InvalidTypeElement, "'{0}' is not a valid version string in the package nuspec file.".format_with(version)); + yield return GetRule(RuleIdentifiers.InvalidTypeElement, "'{0}' is not a valid version string in the package nuspec file.".FormatWith(version)); } } + + protected override IEnumerable GetRules() + { + yield return new ImmutableRule(RuleType.Error, RuleIdentifiers.InvalidTypeElement, "The specified version is not a valid version string."); + } } -} +} \ No newline at end of file diff --git a/src/chocolatey/infrastructure.app/runners/ConsoleApplication.cs b/src/chocolatey/infrastructure.app/runners/ConsoleApplication.cs index 9e4300393d..afa9dde90b 100644 --- a/src/chocolatey/infrastructure.app/runners/ConsoleApplication.cs +++ b/src/chocolatey/infrastructure.app/runners/ConsoleApplication.cs @@ -31,18 +31,18 @@ namespace chocolatey.infrastructure.app.runners /// public sealed class ConsoleApplication { - public void run(string[] args, ChocolateyConfiguration config, Container container) + public void Run(string[] args, ChocolateyConfiguration config, Container container) { var commandLine = Environment.CommandLine; - if (ArgumentsUtility.arguments_contain_sensitive_information(commandLine)) + if (ArgumentsUtility.SensitiveArgumentsProvided(commandLine)) { this.Log().Debug(() => "Command line not shown - sensitive arguments may have been passed."); } else { - this.Log().Debug(() => "Command line: {0}".format_with(commandLine)); - this.Log().Debug(() => "Received arguments: {0}".format_with(string.Join(" ", args))); + this.Log().Debug(() => "Command line: {0}".FormatWith(commandLine)); + this.Log().Debug(() => "Received arguments: {0}".FormatWith(string.Join(" ", args))); } IList commandArgs = new List(); @@ -60,25 +60,25 @@ public void run(string[] args, ChocolateyConfiguration config, Container contain } var runner = new GenericRunner(); - runner.run(config, container, isConsole: true, parseArgs: command => + runner.Run(config, container, isConsole: true, parseArgs: command => { - ConfigurationOptions.parse_arguments_and_update_configuration( + ConfigurationOptions.ParseArgumentsAndUpdateConfiguration( commandArgs, config, - (optionSet) => command.configure_argument_parser(optionSet, config), + (optionSet) => command.ConfigureArgumentParser(optionSet, config), (unparsedArgs) => { // if debug is bundled with local options, it may not get picked up when global // options are parsed. Attempt to set it again once local options are set. // This does mean some output from debug will be missed (but not much) - if (config.Debug) Log4NetAppenderConfiguration.set_logging_level_debug_when_debug(config.Debug, "{0}LoggingColoredConsoleAppender".format_with(ChocolateyLoggers.Verbose.to_string()), "{0}LoggingColoredConsoleAppender".format_with(ChocolateyLoggers.Trace.to_string())); + if (config.Debug) Log4NetAppenderConfiguration.EnableDebugLoggingIf(config.Debug, "{0}LoggingColoredConsoleAppender".FormatWith(ChocolateyLoggers.Verbose.ToStringSafe()), "{0}LoggingColoredConsoleAppender".FormatWith(ChocolateyLoggers.Trace.ToStringSafe())); - command.handle_additional_argument_parsing(unparsedArgs, config); + command.ParseAdditionalArguments(unparsedArgs, config); if (!config.Features.IgnoreInvalidOptionsSwitches) { // all options / switches should be parsed, // so show help menu if there are any left - foreach (var unparsedArg in unparsedArgs.or_empty_list_if_null()) + foreach (var unparsedArg in unparsedArgs.OrEmpty()) { if (unparsedArg.StartsWith("-") || unparsedArg.StartsWith("/")) { @@ -90,16 +90,16 @@ public void run(string[] args, ChocolateyConfiguration config, Container contain }, () => { this.Log().Debug(() => "Performing validation checks."); - command.handle_validation(config); + command.Validate(config); var validationResults = new List(); var validationChecks = container.GetAllInstances(); foreach (var validationCheck in validationChecks) { - validationResults.AddRange(validationCheck.validate(config)); + validationResults.AddRange(validationCheck.Validate(config)); } - var validationErrors = report_validation_summary(validationResults, config); + var validationErrors = ReportValidationSummary(validationResults, config); if (validationErrors != 0) { @@ -109,11 +109,11 @@ public void run(string[] args, ChocolateyConfiguration config, Container contain throw new ApplicationException(""); } }, - () => command.help_message(config)); + () => command.HelpMessage(config)); }); } - private int report_validation_summary(IList validationResults, ChocolateyConfiguration config) + private int ReportValidationSummary(IList validationResults, ChocolateyConfiguration config) { var successes = validationResults.Count(v => v.Status == ValidationStatus.Success); var warnings = validationResults.Count(v => v.Status == ValidationStatus.Warning); @@ -122,7 +122,7 @@ private int report_validation_summary(IList validationResults, var logOnWarnings = config.Features.LogValidationResultsOnWarnings; if (config.RegularOutput) { - this.Log().Info(errors + (logOnWarnings ? warnings : 0) == 0 ? ChocolateyLoggers.LogFileOnly : ChocolateyLoggers.Important, () => "{0} validations performed. {1} success(es), {2} warning(s), and {3} error(s).".format_with( + this.Log().Info(errors + (logOnWarnings ? warnings : 0) == 0 ? ChocolateyLoggers.LogFileOnly : ChocolateyLoggers.Important, () => "{0} validations performed. {1} success(es), {2} warning(s), and {3} error(s).".FormatWith( validationResults.Count, successes, warnings, @@ -133,9 +133,9 @@ private int report_validation_summary(IList validationResults, var warningLogger = logOnWarnings ? ChocolateyLoggers.Normal : ChocolateyLoggers.LogFileOnly; this.Log().Info(warningLogger, ""); this.Log().Warn(warningLogger, "Validation Warnings:"); - foreach (var warning in validationResults.Where(p => p.Status == ValidationStatus.Warning).or_empty_list_if_null()) + foreach (var warning in validationResults.Where(p => p.Status == ValidationStatus.Warning).OrEmpty()) { - this.Log().Warn(warningLogger, " - {0}".format_with(warning.Message)); + this.Log().Warn(warningLogger, " - {0}".FormatWith(warning.Message)); } } } @@ -144,13 +144,19 @@ private int report_validation_summary(IList validationResults, { this.Log().Info(""); this.Log().Error("Validation Errors:"); - foreach (var error in validationResults.Where(p => p.Status == ValidationStatus.Error).or_empty_list_if_null()) + foreach (var error in validationResults.Where(p => p.Status == ValidationStatus.Error).OrEmpty()) { - this.Log().Error(" - {0}".format_with(error.Message)); + this.Log().Error(" - {0}".FormatWith(error.Message)); } } return errors; } + +#pragma warning disable IDE1006 + [Obsolete("This overload is deprecated and will be removed in v3.")] + public void run(string[] args, ChocolateyConfiguration config, Container container) + => Run(args, config, container); +#pragma warning restore IDE1006 } } diff --git a/src/chocolatey/infrastructure.app/runners/GenericRunner.cs b/src/chocolatey/infrastructure.app/runners/GenericRunner.cs index 769d4d78fc..f4f34cd0a9 100644 --- a/src/chocolatey/infrastructure.app/runners/GenericRunner.cs +++ b/src/chocolatey/infrastructure.app/runners/GenericRunner.cs @@ -39,13 +39,13 @@ namespace chocolatey.infrastructure.app.runners public sealed class GenericRunner { - private ICommand find_command(ChocolateyConfiguration config, Container container, bool isConsole, Action parseArgs) + private ICommand FindCommand(ChocolateyConfiguration config, Container container, bool isConsole, Action parseArgs) { var commands = container.GetAllInstances(); var command = commands.Where((c) => { var attributes = c.GetType().GetCustomAttributes(typeof(CommandForAttribute), false); - return attributes.Cast().Any(attribute => attribute.CommandName.is_equal_to(config.CommandName)); + return attributes.Cast().Any(attribute => attribute.CommandName.IsEqualTo(config.CommandName)); }).FirstOrDefault(); if (command == null) @@ -54,7 +54,7 @@ private ICommand find_command(ChocolateyConfiguration config, Container containe if (!string.IsNullOrWhiteSpace(config.CommandName)) { throw new Exception(@"Could not find a command registered that meets '{0}'. - Try choco -? for command reference/help.".format_with(config.CommandName)); + Try choco -? for command reference/help.".FormatWith(config.CommandName)); } if (isConsole) Environment.ExitCode = 1; @@ -66,16 +66,16 @@ private ICommand find_command(ChocolateyConfiguration config, Container containe parseArgs.Invoke(command); } - if (command.may_require_admin_access()) + if (command.MayRequireAdminAccess()) { - warn_when_admin_needs_elevation(config); + WarnIfAdminAndNeedsElevation(config); } - set_source_type(config, container); + SetSourceType(config, container); // guaranteed that all settings are set. - EnvironmentSettings.set_environment_variables(config); + EnvironmentSettings.SetEnvironmentVariables(config); - this.Log().Debug(() => "Configuration: {0}".format_with(config.ToString())); + this.Log().Debug(() => "Configuration: {0}".FormatWith(config.ToString())); if (isConsole && (config.HelpRequested || config.UnsuccessfulParsing)) { @@ -86,8 +86,8 @@ private ICommand find_command(ChocolateyConfiguration config, Container containe Environment.Exit(config.UnsuccessfulParsing ? 1 : 0); } - var token = Assembly.GetExecutingAssembly().get_public_key_token(); - if (string.IsNullOrWhiteSpace(token) || !token.is_equal_to(ApplicationParameters.OfficialChocolateyPublicKey)) + var token = Assembly.GetExecutingAssembly().GetPublicKeyToken(); + if (string.IsNullOrWhiteSpace(token) || !token.IsEqualTo(ApplicationParameters.OfficialChocolateyPublicKey)) { if (!config.AllowUnofficialBuild) { @@ -111,12 +111,12 @@ now be in a bad state. Only official builds are to be trusted. return command; } - private void set_source_type(ChocolateyConfiguration config, Container container) + private void SetSourceType(ChocolateyConfiguration config, Container container) { - var sourceRunner = container.GetAllInstances() - .FirstOrDefault(s => s.SourceType.is_equal_to(config.Sources) || s.SourceType.is_equal_to(config.Sources + "s")); + var sourceRunner = container.GetAllInstances() + .FirstOrDefault(s => s.SourceType.IsEqualTo(config.Sources) || s.SourceType.IsEqualTo(config.Sources + "s")); - var sourceType = SourceTypes.NORMAL; + var sourceType = SourceTypes.Normal; if (sourceRunner != null) { sourceType = sourceRunner.SourceType; @@ -124,62 +124,62 @@ private void set_source_type(ChocolateyConfiguration config, Container container config.SourceType = sourceType; - this.Log().Debug(() => "The source '{0}' evaluated to a '{1}' source type".format_with(config.Sources, sourceType)); + this.Log().Debug(() => "The source '{0}' evaluated to a '{1}' source type".FormatWith(config.Sources, sourceType)); } - public void fail_when_license_is_missing_or_invalid_if_requested(ChocolateyConfiguration config) + public void FailOnMissingOrInvalidLicenseIfFeatureSet(ChocolateyConfiguration config) { if (!config.Features.FailOnInvalidOrMissingLicense || - config.CommandName.trim_safe().is_equal_to("feature") || - config.CommandName.trim_safe().is_equal_to("features") + config.CommandName.TrimSafe().IsEqualTo("feature") || + config.CommandName.TrimSafe().IsEqualTo("features") ) return; if (!config.Information.IsLicensedVersion) throw new ApplicationException("License is missing or invalid."); } - public void run(ChocolateyConfiguration config, Container container, bool isConsole, Action parseArgs) + public void Run(ChocolateyConfiguration config, Container container, bool isConsole, Action parseArgs) { var tasks = container.GetAllInstances(); foreach (var task in tasks) { - task.initialize(); + task.Initialize(); } - fail_when_license_is_missing_or_invalid_if_requested(config); - SecurityProtocol.set_protocol(config, provideWarning: true); - EventManager.publish(new PreRunMessage(config)); + FailOnMissingOrInvalidLicenseIfFeatureSet(config); + HttpsSecurity.Reset(); + EventManager.Publish(new PreRunMessage(config)); try { - var command = find_command(config, container, isConsole, parseArgs); + var command = FindCommand(config, container, isConsole, parseArgs); if (command != null) { if (config.Noop) { if (config.RegularOutput) { - this.Log().Info("_ {0}:{1} - Noop Mode _".format_with(ApplicationParameters.Name, command.GetType().Name)); + this.Log().Info("_ {0}:{1} - Noop Mode _".FormatWith(ApplicationParameters.Name, command.GetType().Name)); } - command.noop(config); + command.DryRun(config); } else { - this.Log().Debug("_ {0}:{1} - Normal Run Mode _".format_with(ApplicationParameters.Name, command.GetType().Name)); - command.run(config); + this.Log().Debug("_ {0}:{1} - Normal Run Mode _".FormatWith(ApplicationParameters.Name, command.GetType().Name)); + command.Run(config); } } } finally { - EventManager.publish(new PostRunMessage(config)); + EventManager.Publish(new PostRunMessage(config)); - foreach (var task in tasks.or_empty_list_if_null()) + foreach (var task in tasks.OrEmpty()) { - task.shutdown(); + task.Shutdown(); } - remove_nuget_cache(container, config); + RemoveNuGetCache(container, config); } } @@ -187,9 +187,9 @@ public void run(ChocolateyConfiguration config, Container container, bool isCons /// if there is a NuGetScratch cache found, kill it with fire /// /// The container. - private void remove_nuget_cache(Container container) + private void RemoveNuGetCache(Container container) { - remove_nuget_cache(container, Config.get_configuration_settings()); + RemoveNuGetCache(container, Config.GetConfigurationSettings()); } /// @@ -197,94 +197,94 @@ private void remove_nuget_cache(Container container) /// /// The container. /// optional Chocolatey configuration to look at cacheLocation - private void remove_nuget_cache(Container container, ChocolateyConfiguration config) + private void RemoveNuGetCache(Container container, ChocolateyConfiguration config) { try { var fileSystem = container.GetInstance(); - var scratch = fileSystem.combine_paths(fileSystem.get_temp_path(), "NuGetScratch"); - fileSystem.delete_directory_if_exists(scratch, recursive: true, overrideAttributes: true, isSilent: true); - var nugetX = fileSystem.combine_paths(fileSystem.get_temp_path(), "x", "nuget"); - fileSystem.delete_directory_if_exists(nugetX, recursive: true, overrideAttributes: true, isSilent: true); + var scratch = fileSystem.CombinePaths(fileSystem.GetTempPath(), "NuGetScratch"); + fileSystem.DeleteDirectoryChecked(scratch, recursive: true, overrideAttributes: true, isSilent: true); + var nugetX = fileSystem.CombinePaths(fileSystem.GetTempPath(), "x", "nuget"); + fileSystem.DeleteDirectoryChecked(nugetX, recursive: true, overrideAttributes: true, isSilent: true); if (config != null && !string.IsNullOrWhiteSpace(config.CacheLocation)) { - scratch = fileSystem.combine_paths(config.CacheLocation, "NuGetScratch"); - fileSystem.delete_directory_if_exists(scratch, recursive: true, overrideAttributes: true, isSilent: true); - nugetX = fileSystem.combine_paths(config.CacheLocation, "x", "nuget"); - fileSystem.delete_directory_if_exists(nugetX, recursive: true, overrideAttributes: true, isSilent: true); + scratch = fileSystem.CombinePaths(config.CacheLocation, "NuGetScratch"); + fileSystem.DeleteDirectoryChecked(scratch, recursive: true, overrideAttributes: true, isSilent: true); + nugetX = fileSystem.CombinePaths(config.CacheLocation, "x", "nuget"); + fileSystem.DeleteDirectoryChecked(nugetX, recursive: true, overrideAttributes: true, isSilent: true); } } catch (Exception ex) { - this.Log().Debug(ChocolateyLoggers.Important, "Not able to cleanup NuGet temp folders. Failure was {0}".format_with(ex.Message)); + this.Log().Debug(ChocolateyLoggers.Important, "Not able to cleanup NuGet temp folders. Failure was {0}".FormatWith(ex.Message)); } } - public IEnumerable list(ChocolateyConfiguration config, Container container, bool isConsole, Action parseArgs) + public IEnumerable List(ChocolateyConfiguration config, Container container, bool isConsole, Action parseArgs) { var tasks = container.GetAllInstances(); foreach (var task in tasks) { - task.initialize(); + task.Initialize(); } - fail_when_license_is_missing_or_invalid_if_requested(config); - SecurityProtocol.set_protocol(config, provideWarning: true); - EventManager.publish(new PreRunMessage(config)); + FailOnMissingOrInvalidLicenseIfFeatureSet(config); + HttpsSecurity.Reset(); + EventManager.Publish(new PreRunMessage(config)); try { - var command = find_command(config, container, isConsole, parseArgs) as IListCommand; + var command = FindCommand(config, container, isConsole, parseArgs) as IListCommand; if (command == null) { if (!string.IsNullOrWhiteSpace(config.CommandName)) { - throw new Exception("The implementation of '{0}' does not support listing '{1}'".format_with(config.CommandName, typeof(T).Name)); + throw new Exception("The implementation of '{0}' does not support listing '{1}'".FormatWith(config.CommandName, typeof(T).Name)); } return new List(); } else { - this.Log().Debug("_ {0}:{1} - Normal List Mode _".format_with(ApplicationParameters.Name, command.GetType().Name)); - return command.list(config); + this.Log().Debug("_ {0}:{1} - Normal List Mode _".FormatWith(ApplicationParameters.Name, command.GetType().Name)); + return command.List(config); } } finally { - EventManager.publish(new PostRunMessage(config)); + EventManager.Publish(new PostRunMessage(config)); - foreach (var task in tasks.or_empty_list_if_null()) + foreach (var task in tasks.OrEmpty()) { - task.shutdown(); + task.Shutdown(); } - remove_nuget_cache(container, config); + RemoveNuGetCache(container, config); } } - public int count(ChocolateyConfiguration config, Container container, bool isConsole, Action parseArgs) + public int Count(ChocolateyConfiguration config, Container container, bool isConsole, Action parseArgs) { - fail_when_license_is_missing_or_invalid_if_requested(config); - SecurityProtocol.set_protocol(config, provideWarning: true); + FailOnMissingOrInvalidLicenseIfFeatureSet(config); + HttpsSecurity.Reset(); - var command = find_command(config, container, isConsole, parseArgs) as IListCommand; + var command = FindCommand(config, container, isConsole, parseArgs) as IListCommand; if (command == null) { if (!string.IsNullOrWhiteSpace(config.CommandName)) { - throw new Exception("The implementation of '{0}' does not support listing.".format_with(config.CommandName)); + throw new Exception("The implementation of '{0}' does not support listing.".FormatWith(config.CommandName)); } return 0; } else { - this.Log().Debug("_ {0}:{1} - Normal Count Mode _".format_with(ApplicationParameters.Name, command.GetType().Name)); - return command.count(config); + this.Log().Debug("_ {0}:{1} - Normal Count Mode _".FormatWith(ApplicationParameters.Name, command.GetType().Name)); + return command.Count(config); } } - public void warn_when_admin_needs_elevation(ChocolateyConfiguration config) + public void WarnIfAdminAndNeedsElevation(ChocolateyConfiguration config) { if (config.HelpRequested) return; @@ -292,7 +292,7 @@ public void warn_when_admin_needs_elevation(ChocolateyConfiguration config) if (!config.Features.ShowNonElevatedWarnings) return; var shouldWarn = (!config.Information.IsProcessElevated && config.Information.IsUserAdministrator) - || (!config.Information.IsUserAdministrator && ApplicationParameters.InstallLocation.is_equal_to(ApplicationParameters.CommonAppDataChocolatey)); + || (!config.Information.IsUserAdministrator && ApplicationParameters.InstallLocation.IsEqualTo(ApplicationParameters.CommonAppDataChocolatey)); if (shouldWarn) { @@ -316,7 +316,7 @@ location. See https://docs.chocolatey.org/en-us/choco/setup#non-administrative-install for details. "); - var selection = InteractivePrompt.prompt_for_confirmation(@" + var selection = InteractivePrompt.PromptForConfirmation(@" Do you want to continue?", new[] { "yes", "no" }, defaultChoice: null, requireAnswer: false, @@ -325,11 +325,33 @@ location. See timeoutInSeconds: timeoutInSeconds ); - if (selection.is_equal_to("no")) + if (selection.IsEqualTo("no")) { Environment.Exit(-1); } } } + +#pragma warning disable IDE1006 + [Obsolete("This overload is deprecated and will be removed in v3.")] + public void fail_when_license_is_missing_or_invalid_if_requested(ChocolateyConfiguration config) + => FailOnMissingOrInvalidLicenseIfFeatureSet(config); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public void run(ChocolateyConfiguration config, Container container, bool isConsole, Action parseArgs) + => Run(config, container, isConsole, parseArgs); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public IEnumerable list(ChocolateyConfiguration config, Container container, bool isConsole, Action parseArgs) + => List(config, container, isConsole, parseArgs); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public int count(ChocolateyConfiguration config, Container container, bool isConsole, Action parseArgs) + => Count(config, container, isConsole, parseArgs); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public void warn_when_admin_needs_elevation(ChocolateyConfiguration config) + => WarnIfAdminAndNeedsElevation(config); +#pragma warning restore IDE1006 } } diff --git a/src/chocolatey/infrastructure.app/services/AutomaticUninstallerService.cs b/src/chocolatey/infrastructure.app/services/AutomaticUninstallerService.cs index 2addfd22ef..db493c2f47 100644 --- a/src/chocolatey/infrastructure.app/services/AutomaticUninstallerService.cs +++ b/src/chocolatey/infrastructure.app/services/AutomaticUninstallerService.cs @@ -38,8 +38,8 @@ public class AutomaticUninstallerService : IAutomaticUninstallerService private readonly IFileSystem _fileSystem; private readonly IRegistryService _registryService; private readonly ICommandExecutor _commandExecutor; - private const int SLEEP_TIME = 2; - private const string SKIP_FILE_NAME = ".skipAutoUninstall"; + private const int SleepTimeInSeconds = 2; + private const string SkipFileName = ".skipAutoUninstall"; public AutomaticUninstallerService(IChocolateyPackageInformationService packageInfoService, IFileSystem fileSystem, IRegistryService registryService, ICommandExecutor commandExecutor) { @@ -52,7 +52,7 @@ public AutomaticUninstallerService(IChocolateyPackageInformationService packageI public bool WaitForCleanup { get; set; } - public void run(PackageResult packageResult, ChocolateyConfiguration config) + public void Run(PackageResult packageResult, ChocolateyConfiguration config) { if (!config.Features.AutoUninstaller) { @@ -63,16 +63,16 @@ public void run(PackageResult packageResult, ChocolateyConfiguration config) var packageLocation = packageResult.InstallLocation; if (!string.IsNullOrWhiteSpace(packageLocation)) { - var skipFiles = _fileSystem.get_files(packageLocation, SKIP_FILE_NAME + "*", SearchOption.AllDirectories).Where(p => !p.to_lower().contains("\\templates\\")); + var skipFiles = _fileSystem.GetFiles(packageLocation, SkipFileName + "*", SearchOption.AllDirectories).Where(p => !p.ToLowerSafe().ContainsSafe("\\templates\\")); if (skipFiles.Count() != 0) { - this.Log().Info(" Skipping auto uninstaller - Package contains a skip file ('{0}').".format_with(SKIP_FILE_NAME)); + this.Log().Info(" Skipping auto uninstaller - Package contains a skip file ('{0}').".FormatWith(SkipFileName)); return; } } - var pkgInfo = _packageInfoService.get_package_information(packageResult.PackageMetadata); + var pkgInfo = _packageInfoService.Get(packageResult.PackageMetadata); if (pkgInfo.RegistrySnapshot == null) { this.Log().Info(" Skipping auto uninstaller - No registry snapshot."); @@ -96,53 +96,53 @@ public void run(PackageResult packageResult, ChocolateyConfiguration config) this.Log().Info(" Running auto uninstaller..."); if (WaitForCleanup) { - this.Log().Debug(" Sleeping for {0} seconds to allow Windows to finish cleaning up.".format_with(SLEEP_TIME)); - Thread.Sleep((int)TimeSpan.FromSeconds(SLEEP_TIME).TotalMilliseconds); + this.Log().Debug(" Sleeping for {0} seconds to allow Windows to finish cleaning up.".FormatWith(SleepTimeInSeconds)); + Thread.Sleep((int)TimeSpan.FromSeconds(SleepTimeInSeconds).TotalMilliseconds); } - foreach (var key in registryKeys.or_empty_list_if_null()) + foreach (var key in registryKeys.OrEmpty()) { - var packageCacheLocation = _fileSystem.combine_paths(_fileSystem.get_full_path(config.CacheLocation), package.Id, package.Version.to_string()); - remove(key, config, packageResult, packageCacheLocation); + var packageCacheLocation = _fileSystem.CombinePaths(_fileSystem.GetFullPath(config.CacheLocation), package.Id, package.Version.ToStringSafe()); + Remove(key, config, packageResult, packageCacheLocation); } } - public void remove(RegistryApplicationKey key, ChocolateyConfiguration config, PackageResult packageResult, string packageCacheLocation) + public void Remove(RegistryApplicationKey key, ChocolateyConfiguration config, PackageResult packageResult, string packageCacheLocation) { var userProvidedUninstallArguments = string.Empty; var userOverrideUninstallArguments = false; var package = packageResult.PackageMetadata; if (package != null) { - if (!PackageUtility.package_is_a_dependency(config, package.Id) || config.ApplyInstallArgumentsToDependencies) + if (!PackageUtility.PackageIdHasDependencySuffix(config, package.Id) || config.ApplyInstallArgumentsToDependencies) { userProvidedUninstallArguments = config.InstallArguments; userOverrideUninstallArguments = config.OverrideArguments; - if (!string.IsNullOrWhiteSpace(userProvidedUninstallArguments)) this.Log().Debug(ChocolateyLoggers.Verbose, " Using user passed {2}uninstaller args for {0}:'{1}'".format_with(package.Id, userProvidedUninstallArguments.escape_curly_braces(), userOverrideUninstallArguments ? "overriding " : string.Empty)); + if (!string.IsNullOrWhiteSpace(userProvidedUninstallArguments)) this.Log().Debug(ChocolateyLoggers.Verbose, " Using user passed {2}uninstaller args for {0}:'{1}'".FormatWith(package.Id, userProvidedUninstallArguments.EscapeCurlyBraces(), userOverrideUninstallArguments ? "overriding " : string.Empty)); } } //todo: #2562 if there is a local package, look to use it in the future if (string.IsNullOrWhiteSpace(key.UninstallString)) { - this.Log().Info(" Skipping auto uninstaller - '{0}' does not have an uninstall string.".format_with(!string.IsNullOrEmpty(key.DisplayName.to_string()) ? key.DisplayName.to_string().escape_curly_braces() : "The application")); + this.Log().Info(" Skipping auto uninstaller - '{0}' does not have an uninstall string.".FormatWith(!string.IsNullOrEmpty(key.DisplayName.ToStringSafe()) ? key.DisplayName.ToStringSafe().EscapeCurlyBraces() : "The application")); return; } - this.Log().Debug(() => " Preparing uninstall key '{0}' for '{1}'".format_with(key.UninstallString.to_string().escape_curly_braces(), key.DisplayName.to_string().escape_curly_braces())); + this.Log().Debug(() => " Preparing uninstall key '{0}' for '{1}'".FormatWith(key.UninstallString.ToStringSafe().EscapeCurlyBraces(), key.DisplayName.ToStringSafe().EscapeCurlyBraces())); - if ((!string.IsNullOrWhiteSpace(key.InstallLocation) && !_fileSystem.directory_exists(key.InstallLocation.to_string().remove_surrounding_quotes())) || !_registryService.installer_value_exists(key.KeyPath, ApplicationParameters.RegistryValueInstallLocation)) + if ((!string.IsNullOrWhiteSpace(key.InstallLocation) && !_fileSystem.DirectoryExists(key.InstallLocation.ToStringSafe().UnquoteSafe())) || !_registryService.InstallerKeyExists(key.KeyPath)) { - this.Log().Info(" Skipping auto uninstaller - '{0}' appears to have been uninstalled already by other means.".format_with(!string.IsNullOrEmpty(key.DisplayName.to_string()) ? key.DisplayName.to_string().escape_curly_braces() : "The application")); - this.Log().Debug(() => " Searched for install path '{0}' - found? {1}".format_with(key.InstallLocation.to_string().escape_curly_braces(), _fileSystem.directory_exists(key.InstallLocation))); - this.Log().Debug(() => " Searched for registry key '{0}' value '{1}' - found? {2}".format_with(key.KeyPath.escape_curly_braces(), ApplicationParameters.RegistryValueInstallLocation, _registryService.installer_value_exists(key.KeyPath, ApplicationParameters.RegistryValueInstallLocation))); + this.Log().Info(" Skipping auto uninstaller - '{0}' appears to have been uninstalled already by other means.".FormatWith(!string.IsNullOrEmpty(key.DisplayName.ToStringSafe()) ? key.DisplayName.ToStringSafe().EscapeCurlyBraces() : "The application")); + this.Log().Debug(() => " Searched for install path '{0}' - found? {1}".FormatWith(key.InstallLocation.ToStringSafe().EscapeCurlyBraces(), _fileSystem.DirectoryExists(key.InstallLocation))); + this.Log().Debug(() => " Searched for registry key '{0}' value '{1}' - found? {2}".FormatWith(key.KeyPath.EscapeCurlyBraces(), ApplicationParameters.RegistryValueInstallLocation, _registryService.InstallerKeyExists(key.KeyPath))); return; } // split on " /" and " -" for quite a bit more accuracy - IList uninstallArgsSplit = key.UninstallString.to_string().Replace(""","\"").Replace("'","'").Split(new[] { " /", " -" }, StringSplitOptions.RemoveEmptyEntries).ToList(); - var uninstallExe = uninstallArgsSplit.DefaultIfEmpty(string.Empty).FirstOrDefault().trim_safe(); + IList uninstallArgsSplit = key.UninstallString.ToStringSafe().Replace(""","\"").Replace("'","'").Split(new[] { " /", " -" }, StringSplitOptions.RemoveEmptyEntries).ToList(); + var uninstallExe = uninstallArgsSplit.DefaultIfEmpty(string.Empty).FirstOrDefault().TrimSafe(); if (uninstallExe.Count(u => u == '"') > 2) { uninstallExe = uninstallExe.Split(new []{" \""}, StringSplitOptions.RemoveEmptyEntries).First(); @@ -157,25 +157,25 @@ public void remove(RegistryApplicationKey key, ChocolateyConfiguration config, P } catch (Exception ex) { - this.Log().Debug("Error splitting the uninstall string:{0} {1}".format_with(Environment.NewLine,ex.to_string())); + this.Log().Debug("Error splitting the uninstall string:{0} {1}".FormatWith(Environment.NewLine,ex.ToStringSafe())); } } - var uninstallArgs = key.UninstallString.to_string().Replace(""", "\"").Replace("'", "'").Replace(uninstallExe.to_string(), string.Empty).trim_safe(); + var uninstallArgs = key.UninstallString.ToStringSafe().Replace(""", "\"").Replace("'", "'").Replace(uninstallExe.ToStringSafe(), string.Empty).TrimSafe(); - uninstallExe = uninstallExe.remove_surrounding_quotes(); - this.Log().Debug(() => " Uninstaller path is '{0}'".format_with(uninstallExe)); + uninstallExe = uninstallExe.UnquoteSafe(); + this.Log().Debug(() => " Uninstaller path is '{0}'".FormatWith(uninstallExe)); - if (uninstallExe.contains("\\") || uninstallExe.contains("/")) + if (uninstallExe.ContainsSafe("\\") || uninstallExe.ContainsSafe("/")) { - if (!_fileSystem.file_exists(uninstallExe)) + if (!_fileSystem.FileExists(uninstallExe)) { - this.Log().Info(" Skipping auto uninstaller - The uninstaller file no longer exists. \"{0}\"".format_with(uninstallExe)); + this.Log().Info(" Skipping auto uninstaller - The uninstaller file no longer exists. \"{0}\"".FormatWith(uninstallExe)); return; } } - IInstaller installer = get_installer_type(key, uninstallExe, uninstallArgs); - this.Log().Debug(() => " Installer type is '{0}'".format_with(installer.GetType().Name)); + IInstaller installer = GetInstallerType(key, uninstallExe, uninstallArgs); + this.Log().Debug(() => " Installer type is '{0}'".FormatWith(installer.GetType().Name)); if (key.InstallerType == InstallerType.Msi) { @@ -189,29 +189,29 @@ public void remove(RegistryApplicationKey key, ChocolateyConfiguration config, P if (!key.HasQuietUninstall) { //todo: #2563 ultimately we should merge keys - uninstallArgs += " " + installer.build_uninstall_command_arguments(); + uninstallArgs += " " + installer.BuildUninstallCommandArguments(); } if (!string.IsNullOrWhiteSpace(userProvidedUninstallArguments)) { if (userOverrideUninstallArguments) { - this.Log().Debug(() => " Replacing original uninstall arguments of '{0}' with '{1}'".format_with(uninstallArgs.escape_curly_braces(),userProvidedUninstallArguments.escape_curly_braces())); + this.Log().Debug(() => " Replacing original uninstall arguments of '{0}' with '{1}'".FormatWith(uninstallArgs.EscapeCurlyBraces(),userProvidedUninstallArguments.EscapeCurlyBraces())); uninstallArgs = userProvidedUninstallArguments; } else { - this.Log().Debug(() => " Appending original uninstall arguments with '{0}'".format_with(userProvidedUninstallArguments.escape_curly_braces())); + this.Log().Debug(() => " Appending original uninstall arguments with '{0}'".FormatWith(userProvidedUninstallArguments.EscapeCurlyBraces())); uninstallArgs += " " + userProvidedUninstallArguments; } } - this.Log().Debug(() => " Setting up uninstall logging directory at {0}".format_with(packageCacheLocation.escape_curly_braces())); - _fileSystem.create_directory_if_not_exists(_fileSystem.get_directory_name(packageCacheLocation)); - uninstallArgs = uninstallArgs.Replace(InstallTokens.PACKAGE_LOCATION, packageCacheLocation); - uninstallArgs = uninstallArgs.Replace(InstallTokens.TEMP_LOCATION, packageCacheLocation); + this.Log().Debug(() => " Setting up uninstall logging directory at {0}".FormatWith(packageCacheLocation.EscapeCurlyBraces())); + _fileSystem.EnsureDirectoryExists(_fileSystem.GetDirectoryName(packageCacheLocation)); + uninstallArgs = uninstallArgs.Replace(InstallTokens.PackageLocation, packageCacheLocation); + uninstallArgs = uninstallArgs.Replace(InstallTokens.TempLocation, packageCacheLocation); - this.Log().Debug(() => " Args are '{0}'".format_with(uninstallArgs.escape_curly_braces())); + this.Log().Debug(() => " Args are '{0}'".FormatWith(uninstallArgs.EscapeCurlyBraces())); if (!key.HasQuietUninstall && installer.GetType() == typeof(CustomInstaller)) { @@ -228,7 +228,7 @@ Automatic Uninstaller due to licensed enhancements and Package var timeout = config.PromptForConfirmation ? 0 : 30; - var selection = InteractivePrompt.prompt_for_confirmation( + var selection = InteractivePrompt.PromptForConfirmation( "Uninstall may not be silent (could not detect). Proceed?", new[] { "yes", "no" }, defaultChoice: "no", @@ -237,46 +237,46 @@ Automatic Uninstaller due to licensed enhancements and Package shortPrompt: true, timeoutInSeconds: timeout ); - if (selection.is_equal_to("yes")) skipUninstaller = false; + if (selection.IsEqualTo("yes")) skipUninstaller = false; if (skipUninstaller) { this.Log().Info(" Skipping auto uninstaller - Installer type was not detected and no silent uninstall key exists."); - this.Log().Warn("If the application was not removed with a chocolateyUninstall.ps1,{0} please remove it from Programs and Features manually.".format_with(Environment.NewLine)); + this.Log().Warn("If the application was not removed with a chocolateyUninstall.ps1,{0} please remove it from Programs and Features manually.".FormatWith(Environment.NewLine)); return; } } - var exitCode = _commandExecutor.execute( + var exitCode = _commandExecutor.Execute( uninstallExe, - uninstallArgs.trim_safe(), + uninstallArgs.TrimSafe(), config.CommandExecutionTimeoutSeconds, (s, e) => { if (e == null || string.IsNullOrWhiteSpace(e.Data)) return; - this.Log().Info(() => " [AutoUninstaller] {0}".format_with(e.Data.escape_curly_braces())); + this.Log().Info(() => " [AutoUninstaller] {0}".FormatWith(e.Data.EscapeCurlyBraces())); }, (s, e) => { if (e == null || string.IsNullOrWhiteSpace(e.Data)) return; - this.Log().Error(() => " [AutoUninstaller] {0}".format_with(e.Data.escape_curly_braces())); + this.Log().Error(() => " [AutoUninstaller] {0}".FormatWith(e.Data.EscapeCurlyBraces())); }, updateProcessPath: false); if (!installer.ValidUninstallExitCodes.Contains(exitCode)) { Environment.ExitCode = exitCode; - string logMessage = " Auto uninstaller failed. Please remove machine installation manually.{0} Exit code was {1}".format_with(Environment.NewLine, exitCode); - this.Log().Error(() => logMessage.escape_curly_braces()); + string logMessage = " Auto uninstaller failed. Please remove machine installation manually.{0} Exit code was {1}".FormatWith(Environment.NewLine, exitCode); + this.Log().Error(() => logMessage.EscapeCurlyBraces()); packageResult.Messages.Add(new ResultMessage(config.Features.FailOnAutoUninstaller ? ResultType.Error : ResultType.Warn, logMessage)); } else { - this.Log().Info(() => " Auto uninstaller has successfully uninstalled {0} or detected previous uninstall.".format_with(packageResult.PackageMetadata.Id)); + this.Log().Info(() => " Auto uninstaller has successfully uninstalled {0} or detected previous uninstall.".FormatWith(packageResult.PackageMetadata.Id)); } } - public virtual IInstaller get_installer_type(RegistryApplicationKey key, string uninstallExe, string uninstallArgs) + public virtual IInstaller GetInstallerType(RegistryApplicationKey key, string uninstallExe, string uninstallArgs) { IInstaller installer = new CustomInstaller(); @@ -298,5 +298,19 @@ public virtual IInstaller get_installer_type(RegistryApplicationKey key, string return installer; } + +#pragma warning disable IDE1006 + [Obsolete("This overload is deprecated and will be removed in v3.")] + public void run(PackageResult packageResult, ChocolateyConfiguration config) + => Run(packageResult, config); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public void remove(RegistryApplicationKey key, ChocolateyConfiguration config, PackageResult packageResult, string packageCacheLocation) + => Remove(key, config, packageResult, packageCacheLocation); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public virtual IInstaller get_installer_type(RegistryApplicationKey key, string uninstallExe, string uninstallArgs) + => GetInstallerType(key, uninstallExe, uninstallArgs); +#pragma warning restore IDE1006 } } diff --git a/src/chocolatey/infrastructure.app/services/ChocolateyConfigSettingsService.cs b/src/chocolatey/infrastructure.app/services/ChocolateyConfigSettingsService.cs index 5e2825c0c1..3cc63103d1 100644 --- a/src/chocolatey/infrastructure.app/services/ChocolateyConfigSettingsService.cs +++ b/src/chocolatey/infrastructure.app/services/ChocolateyConfigSettingsService.cs @@ -31,14 +31,14 @@ public class ChocolateyConfigSettingsService : IChocolateyConfigSettingsService private readonly HashSet _knownFeatures = new HashSet(); private readonly Lazy _configFileSettings; private readonly IXmlService _xmlService; - private const string NO_CHANGE_MESSAGE = "Nothing to change. Config already set."; + private const string NoChangeMessage = "Nothing to change. Config already set."; public ChocolateyConfigSettingsService() { - add_known_features_from_static_class(typeof(ApplicationParameters.Features)); + AddKnownFeaturesFromStaticClass(typeof(ApplicationParameters.Features)); } - private ConfigFileSettings configFileSettings + private ConfigFileSettings ConfigFileSettings { get { return _configFileSettings.Value; } } @@ -47,53 +47,53 @@ public ChocolateyConfigSettingsService(IXmlService xmlService) : this() { _xmlService = xmlService; - _configFileSettings = new Lazy(() => _xmlService.deserialize(ApplicationParameters.GlobalConfigFileLocation)); + _configFileSettings = new Lazy(() => _xmlService.Deserialize(ApplicationParameters.GlobalConfigFileLocation)); } - public void noop(ChocolateyConfiguration configuration) + public void DryRun(ChocolateyConfiguration configuration) { this.Log().Info("Would have made a change to the configuration."); } - public virtual bool skip_source(ConfigFileSourceSetting source, ChocolateyConfiguration configuration) + public virtual bool SkipSource(ConfigFileSourceSetting source, ChocolateyConfiguration configuration) { return false; } - public virtual IEnumerable source_list(ChocolateyConfiguration configuration) + public virtual IEnumerable ListSources(ChocolateyConfiguration configuration) { var list = new List(); - foreach (var source in configFileSettings.Sources) + foreach (var source in ConfigFileSettings.Sources.OrEmpty().OrderBy(s => s.Id)) { - if (skip_source(source, configuration)) continue; + if (SkipSource(source, configuration)) continue; if (!configuration.QuietOutput) { if (configuration.RegularOutput) { - this.Log().Info(() => "{0}{1} - {2} {3}| Priority {4}|Bypass Proxy - {5}|Self-Service - {6}|Admin Only - {7}.".format_with( + this.Log().Info(() => "{0}{1} - {2} {3}| Priority {4}|Bypass Proxy - {5}|Self-Service - {6}|Admin Only - {7}.".FormatWith( source.Id, source.Disabled ? " [Disabled]" : string.Empty, source.Value, (string.IsNullOrWhiteSpace(source.UserName) && string.IsNullOrWhiteSpace(source.Certificate)) ? string.Empty : "(Authenticated)", source.Priority, - source.BypassProxy.to_string(), - source.AllowSelfService.to_string(), - source.VisibleToAdminsOnly.to_string() + source.BypassProxy.ToStringSafe(), + source.AllowSelfService.ToStringSafe(), + source.VisibleToAdminsOnly.ToStringSafe() )); } else { - this.Log().Info(() => "{0}|{1}|{2}|{3}|{4}|{5}|{6}|{7}|{8}".format_with( - source.Id.quote_if_pipe_found(), + this.Log().Info(() => "{0}|{1}|{2}|{3}|{4}|{5}|{6}|{7}|{8}".FormatWith( + source.Id.QuoteIfContainsPipe(), source.Value, - source.Disabled.to_string(), - source.UserName.quote_if_pipe_found(), + source.Disabled.ToStringSafe(), + source.UserName.QuoteIfContainsPipe(), source.Certificate, source.Priority, - source.BypassProxy.to_string(), - source.AllowSelfService.to_string(), - source.VisibleToAdminsOnly.to_string() + source.BypassProxy.ToStringSafe(), + source.AllowSelfService.ToStringSafe(), + source.VisibleToAdminsOnly.ToStringSafe() )); } } @@ -112,9 +112,9 @@ public virtual IEnumerable source_list(ChocolateyConfiguration return list; } - public void source_add(ChocolateyConfiguration configuration) + public void AddSource(ChocolateyConfiguration configuration) { - var source = configFileSettings.Sources.FirstOrDefault(p => p.Id.is_equal_to(configuration.SourceCommand.Name)); + var source = ConfigFileSettings.Sources.FirstOrDefault(p => p.Id.IsEqualTo(configuration.SourceCommand.Name)); if (source == null) { source = new ConfigFileSourceSetting @@ -130,27 +130,27 @@ public void source_add(ChocolateyConfiguration configuration) AllowSelfService = configuration.SourceCommand.AllowSelfService, VisibleToAdminsOnly = configuration.SourceCommand.VisibleToAdminsOnly }; - configFileSettings.Sources.Add(source); + ConfigFileSettings.Sources.Add(source); - _xmlService.serialize(configFileSettings, ApplicationParameters.GlobalConfigFileLocation); - if (!configuration.QuietOutput) this.Log().Warn(() => "Added {0} - {1} (Priority {2})".format_with(source.Id, source.Value, source.Priority)); + _xmlService.Serialize(ConfigFileSettings, ApplicationParameters.GlobalConfigFileLocation); + if (!configuration.QuietOutput) this.Log().Warn(() => "Added {0} - {1} (Priority {2})".FormatWith(source.Id, source.Value, source.Priority)); } else { var currentPassword = string.IsNullOrWhiteSpace(source.Password) ? null : NugetEncryptionUtility.DecryptString(source.Password); var currentCertificatePassword = string.IsNullOrWhiteSpace(source.CertificatePassword) ? null : NugetEncryptionUtility.DecryptString(source.CertificatePassword); - if (configuration.Sources.is_equal_to(source.Value) && + if (configuration.Sources.IsEqualTo(source.Value) && configuration.SourceCommand.Priority == source.Priority && - configuration.SourceCommand.Username.is_equal_to(source.UserName) && - configuration.SourceCommand.Password.is_equal_to(currentPassword) && - configuration.SourceCommand.CertificatePassword.is_equal_to(currentCertificatePassword) && - configuration.SourceCommand.Certificate.is_equal_to(source.Certificate) && + configuration.SourceCommand.Username.IsEqualTo(source.UserName) && + configuration.SourceCommand.Password.IsEqualTo(currentPassword) && + configuration.SourceCommand.CertificatePassword.IsEqualTo(currentCertificatePassword) && + configuration.SourceCommand.Certificate.IsEqualTo(source.Certificate) && configuration.SourceCommand.BypassProxy == source.BypassProxy && configuration.SourceCommand.AllowSelfService == source.AllowSelfService && configuration.SourceCommand.VisibleToAdminsOnly == source.VisibleToAdminsOnly ) { - if (!configuration.QuietOutput) this.Log().Warn(NO_CHANGE_MESSAGE); + if (!configuration.QuietOutput) this.Log().Warn(NoChangeMessage); } else { @@ -164,138 +164,160 @@ public void source_add(ChocolateyConfiguration configuration) source.AllowSelfService = configuration.SourceCommand.AllowSelfService; source.VisibleToAdminsOnly = configuration.SourceCommand.VisibleToAdminsOnly; - _xmlService.serialize(configFileSettings, ApplicationParameters.GlobalConfigFileLocation); - if (!configuration.QuietOutput) this.Log().Warn(() => "Updated {0} - {1} (Priority {2})".format_with(source.Id, source.Value, source.Priority)); + _xmlService.Serialize(ConfigFileSettings, ApplicationParameters.GlobalConfigFileLocation); + if (!configuration.QuietOutput) this.Log().Warn(() => "Updated {0} - {1} (Priority {2})".FormatWith(source.Id, source.Value, source.Priority)); } } } - public void source_remove(ChocolateyConfiguration configuration) + public void RemoveSource(ChocolateyConfiguration configuration) { - var source = configFileSettings.Sources.FirstOrDefault(p => p.Id.is_equal_to(configuration.SourceCommand.Name)); + var source = ConfigFileSettings.Sources.FirstOrDefault(p => p.Id.IsEqualTo(configuration.SourceCommand.Name)); if (source != null) { - configFileSettings.Sources.Remove(source); - _xmlService.serialize(configFileSettings, ApplicationParameters.GlobalConfigFileLocation); + ConfigFileSettings.Sources.Remove(source); + _xmlService.Serialize(ConfigFileSettings, ApplicationParameters.GlobalConfigFileLocation); - if (!configuration.QuietOutput) this.Log().Warn(() => "Removed {0}".format_with(source.Id)); + if (!configuration.QuietOutput) this.Log().Warn(() => "Removed {0}".FormatWith(source.Id)); } else { - if (!configuration.QuietOutput) this.Log().Warn(NO_CHANGE_MESSAGE); + if (!configuration.QuietOutput) this.Log().Warn(NoChangeMessage); } } - public void source_disable(ChocolateyConfiguration configuration) + public void DisableSource(ChocolateyConfiguration configuration) { - var source = configFileSettings.Sources.FirstOrDefault(p => p.Id.is_equal_to(configuration.SourceCommand.Name)); + var source = ConfigFileSettings.Sources.FirstOrDefault(p => p.Id.IsEqualTo(configuration.SourceCommand.Name)); if (source != null && !source.Disabled) { source.Disabled = true; - _xmlService.serialize(configFileSettings, ApplicationParameters.GlobalConfigFileLocation); - if (!configuration.QuietOutput) this.Log().Warn(() => "Disabled {0}".format_with(source.Id)); + _xmlService.Serialize(ConfigFileSettings, ApplicationParameters.GlobalConfigFileLocation); + if (!configuration.QuietOutput) this.Log().Warn(() => "Disabled {0}".FormatWith(source.Id)); } else { - if (!configuration.QuietOutput) this.Log().Warn(NO_CHANGE_MESSAGE); + if (!configuration.QuietOutput) this.Log().Warn(NoChangeMessage); } } - public void source_enable(ChocolateyConfiguration configuration) + public void EnableSource(ChocolateyConfiguration configuration) { - var source = configFileSettings.Sources.FirstOrDefault(p => p.Id.is_equal_to(configuration.SourceCommand.Name)); + var source = ConfigFileSettings.Sources.FirstOrDefault(p => p.Id.IsEqualTo(configuration.SourceCommand.Name)); if (source != null && source.Disabled) { source.Disabled = false; - _xmlService.serialize(configFileSettings, ApplicationParameters.GlobalConfigFileLocation); - if (!configuration.QuietOutput) this.Log().Warn(() => "Enabled {0}".format_with(source.Id)); + _xmlService.Serialize(ConfigFileSettings, ApplicationParameters.GlobalConfigFileLocation); + if (!configuration.QuietOutput) this.Log().Warn(() => "Enabled {0}".FormatWith(source.Id)); } else { - if (!configuration.QuietOutput) this.Log().Warn(NO_CHANGE_MESSAGE); + if (!configuration.QuietOutput) this.Log().Warn(NoChangeMessage); } } - public void feature_list(ChocolateyConfiguration configuration) + public void ListFeatures(ChocolateyConfiguration configuration) { - foreach (var feature in configFileSettings.Features) + foreach (var feature in ConfigFileSettings.Features.OrEmpty().OrderBy(f => f.Name)) { if (configuration.RegularOutput) { - this.Log().Info(() => "{0} {1} - {2}".format_with(feature.Enabled ? "[x]" : "[ ]", feature.Name, feature.Description)); + this.Log().Info(() => "{0} {1} - {2}".FormatWith(feature.Enabled ? "[x]" : "[ ]", feature.Name, feature.Description)); } else { - this.Log().Info(() => "{0}|{1}|{2}".format_with(feature.Name, !feature.Enabled ? "Disabled" : "Enabled", feature.Description)); + this.Log().Info(() => "{0}|{1}|{2}".FormatWith(feature.Name, !feature.Enabled ? "Disabled" : "Enabled", feature.Description)); } } } - public void feature_disable(ChocolateyConfiguration configuration) + public void GetFeature(ChocolateyConfiguration configuration) + { + var feature = GetFeatureValue(configuration.FeatureCommand.Name); + if (feature == null) + { + throw new ApplicationException("No feature value by the name '{0}'".FormatWith(configuration.FeatureCommand.Name)); + } + + this.Log().Info("{0}".FormatWith(feature.Enabled ? "Enabled" : "Disabled")); + } + + public ConfigFileFeatureSetting GetFeatureValue(string featureName) { - var feature = configFileSettings.Features.FirstOrDefault(p => p.Name.is_equal_to(configuration.FeatureCommand.Name)); + var feature = ConfigFileSettings.Features.FirstOrDefault(f => f.Name.IsEqualTo(featureName)); if (feature == null) { - throw new ApplicationException("Feature '{0}' not found".format_with(configuration.FeatureCommand.Name)); + return null; } - validate_supported_feature(feature); + return feature; + } + + public void DisableFeature(ChocolateyConfiguration configuration) + { + var feature = ConfigFileSettings.Features.FirstOrDefault(p => p.Name.IsEqualTo(configuration.FeatureCommand.Name)); + if (feature == null) + { + throw new ApplicationException("Feature '{0}' not found".FormatWith(configuration.FeatureCommand.Name)); + } + + ValidateSupportedFeature(feature); if (feature.Enabled || !feature.SetExplicitly) { if (!feature.Enabled && !feature.SetExplicitly) { - this.Log().Info(() => "{0} was disabled by default. Explicitly setting value.".format_with(feature.Name)); + this.Log().Info(() => "{0} was disabled by default. Explicitly setting value.".FormatWith(feature.Name)); } feature.Enabled = false; feature.SetExplicitly = true; - _xmlService.serialize(configFileSettings, ApplicationParameters.GlobalConfigFileLocation); - this.Log().Warn(() => "Disabled {0}".format_with(feature.Name)); + _xmlService.Serialize(ConfigFileSettings, ApplicationParameters.GlobalConfigFileLocation); + this.Log().Warn(() => "Disabled {0}".FormatWith(feature.Name)); } else { - this.Log().Warn(NO_CHANGE_MESSAGE); + this.Log().Warn(NoChangeMessage); } } - public void feature_enable(ChocolateyConfiguration configuration) + public void EnableFeature(ChocolateyConfiguration configuration) { - var feature = configFileSettings.Features.FirstOrDefault(p => p.Name.is_equal_to(configuration.FeatureCommand.Name)); + var feature = ConfigFileSettings.Features.FirstOrDefault(p => p.Name.IsEqualTo(configuration.FeatureCommand.Name)); if (feature == null) { - throw new ApplicationException("Feature '{0}' not found".format_with(configuration.FeatureCommand.Name)); + throw new ApplicationException("Feature '{0}' not found".FormatWith(configuration.FeatureCommand.Name)); } - validate_supported_feature(feature); + ValidateSupportedFeature(feature); if (!feature.Enabled || !feature.SetExplicitly) { if (feature.Enabled && !feature.SetExplicitly) { - this.Log().Info(() => "{0} was enabled by default. Explicitly setting value.".format_with(feature.Name)); + this.Log().Info(() => "{0} was enabled by default. Explicitly setting value.".FormatWith(feature.Name)); } feature.Enabled = true; feature.SetExplicitly = true; - _xmlService.serialize(configFileSettings, ApplicationParameters.GlobalConfigFileLocation); - this.Log().Warn(() => "Enabled {0}".format_with(feature.Name)); + _xmlService.Serialize(ConfigFileSettings, ApplicationParameters.GlobalConfigFileLocation); + this.Log().Warn(() => "Enabled {0}".FormatWith(feature.Name)); } else { - this.Log().Warn(NO_CHANGE_MESSAGE); + this.Log().Warn(NoChangeMessage); } } - public string get_api_key(ChocolateyConfiguration configuration, Action keyAction) + public string GetApiKey(ChocolateyConfiguration configuration, Action keyAction) { string apiKeyValue = null; if (!string.IsNullOrWhiteSpace(configuration.Sources)) { - var apiKey = configFileSettings.ApiKeys.FirstOrDefault(p => p.Source.TrimEnd('/').is_equal_to(configuration.Sources.TrimEnd('/'))); + var apiKey = ConfigFileSettings.ApiKeys.FirstOrDefault(p => p.Source.TrimEnd('/').IsEqualTo(configuration.Sources.TrimEnd('/'))); if (apiKey != null) { - apiKeyValue = NugetEncryptionUtility.DecryptString(apiKey.Key).to_string(); + apiKeyValue = NugetEncryptionUtility.DecryptString(apiKey.Key).ToStringSafe(); if (keyAction != null) { @@ -305,9 +327,9 @@ public string get_api_key(ChocolateyConfiguration configuration, Action a.Source)) { - var keyValue = NugetEncryptionUtility.DecryptString(apiKey.Key).to_string(); + var keyValue = NugetEncryptionUtility.DecryptString(apiKey.Key).ToStringSafe(); if (keyAction != null) { keyAction.Invoke(new ConfigFileApiKeySetting { Key = keyValue, Source = apiKey.Source }); @@ -318,86 +340,86 @@ public string get_api_key(ChocolateyConfiguration configuration, Action p.Source.is_equal_to(configuration.Sources)); + var apiKey = ConfigFileSettings.ApiKeys.FirstOrDefault(p => p.Source.IsEqualTo(configuration.Sources)); if (apiKey == null) { - configFileSettings.ApiKeys.Add(new ConfigFileApiKeySetting + ConfigFileSettings.ApiKeys.Add(new ConfigFileApiKeySetting { Source = configuration.Sources, Key = NugetEncryptionUtility.EncryptString(configuration.ApiKeyCommand.Key), }); - _xmlService.serialize(configFileSettings, ApplicationParameters.GlobalConfigFileLocation); + _xmlService.Serialize(ConfigFileSettings, ApplicationParameters.GlobalConfigFileLocation); - this.Log().Info(() => "Added API key for {0}".format_with(configuration.Sources)); + this.Log().Info(() => "Added API key for {0}".FormatWith(configuration.Sources)); } else { - if (!NugetEncryptionUtility.DecryptString(apiKey.Key).to_string().is_equal_to(configuration.ApiKeyCommand.Key)) + if (!NugetEncryptionUtility.DecryptString(apiKey.Key).ToStringSafe().IsEqualTo(configuration.ApiKeyCommand.Key)) { apiKey.Key = NugetEncryptionUtility.EncryptString(configuration.ApiKeyCommand.Key); - _xmlService.serialize(configFileSettings, ApplicationParameters.GlobalConfigFileLocation); - this.Log().Info(() => "Updated API key for {0}".format_with(configuration.Sources)); + _xmlService.Serialize(ConfigFileSettings, ApplicationParameters.GlobalConfigFileLocation); + this.Log().Info(() => "Updated API key for {0}".FormatWith(configuration.Sources)); } - else this.Log().Warn(NO_CHANGE_MESSAGE); + else this.Log().Warn(NoChangeMessage); } } - public void remove_api_key(ChocolateyConfiguration configuration) + public void RemoveApiKey(ChocolateyConfiguration configuration) { - var apiKey = configFileSettings.ApiKeys.FirstOrDefault(p => p.Source.is_equal_to(configuration.Sources)); + var apiKey = ConfigFileSettings.ApiKeys.FirstOrDefault(p => p.Source.IsEqualTo(configuration.Sources)); if (apiKey != null) { - configFileSettings.ApiKeys.RemoveWhere(x => x.Source.is_equal_to(configuration.Sources)); + ConfigFileSettings.ApiKeys.RemoveWhere(x => x.Source.IsEqualTo(configuration.Sources)); - _xmlService.serialize(configFileSettings, ApplicationParameters.GlobalConfigFileLocation); + _xmlService.Serialize(ConfigFileSettings, ApplicationParameters.GlobalConfigFileLocation); - this.Log().Info(() => "Removed API key for {0}".format_with(configuration.Sources)); + this.Log().Info(() => "Removed API key for {0}".FormatWith(configuration.Sources)); } else { - this.Log().Info(() => "API key was not found for {0}".format_with(configuration.Sources)); + this.Log().Info(() => "API key was not found for {0}".FormatWith(configuration.Sources)); } } - public void config_list(ChocolateyConfiguration configuration) + public void ListConfig(ChocolateyConfiguration configuration) { - foreach (var config in configFileSettings.ConfigSettings) + foreach (var config in ConfigFileSettings.ConfigSettings.OrEmpty().OrderBy(c => c.Key)) { if (configuration.RegularOutput) { - this.Log().Info(() => "{0} = {1} | {2}".format_with(config.Key, config.Value, config.Description)); + this.Log().Info(() => "{0} = {1} | {2}".FormatWith(config.Key, config.Value, config.Description)); } else { - this.Log().Info(() => "{0}|{1}|{2}".format_with(config.Key, config.Value, config.Description)); + this.Log().Info(() => "{0}|{1}|{2}".FormatWith(config.Key, config.Value, config.Description)); } } } - public void config_get(ChocolateyConfiguration configuration) + public void GetConfig(ChocolateyConfiguration configuration) { - var config = config_get(configuration.ConfigCommand.Name); - if (config == null) throw new ApplicationException("No configuration value by the name '{0}'".format_with(configuration.ConfigCommand.Name)); - this.Log().Info("{0}".format_with(config.Value)); + var config = GetConfigValue(configuration.ConfigCommand.Name); + if (config == null) throw new ApplicationException("No configuration value by the name '{0}'".FormatWith(configuration.ConfigCommand.Name)); + this.Log().Info("{0}".FormatWith(config.Value)); } - public ConfigFileConfigSetting config_get(string configKeyName) + public ConfigFileConfigSetting GetConfigValue(string configKeyName) { - var config = configFileSettings.ConfigSettings.FirstOrDefault(p => p.Key.is_equal_to(configKeyName)); + var config = ConfigFileSettings.ConfigSettings.FirstOrDefault(p => p.Key.IsEqualTo(configKeyName)); if (config == null) return null; return config; } - public void config_set(ChocolateyConfiguration configuration) + public void SetConfig(ChocolateyConfiguration configuration) { - var encryptValue = configuration.ConfigCommand.Name.contains("password"); - var config = config_get(configuration.ConfigCommand.Name); + var encryptValue = configuration.ConfigCommand.Name.ContainsSafe("password"); + var config = GetConfigValue(configuration.ConfigCommand.Name); var configValue = encryptValue ? NugetEncryptionUtility.EncryptString(configuration.ConfigCommand.ConfigValue) : configuration.ConfigCommand.ConfigValue; @@ -410,11 +432,11 @@ public void config_set(ChocolateyConfiguration configuration) Value = configValue, }; - configFileSettings.ConfigSettings.Add(setting); + ConfigFileSettings.ConfigSettings.Add(setting); - _xmlService.serialize(configFileSettings, ApplicationParameters.GlobalConfigFileLocation); + _xmlService.Serialize(ConfigFileSettings, ApplicationParameters.GlobalConfigFileLocation); - this.Log().Warn(() => "Added {0} = {1}".format_with(setting.Key, setting.Value)); + this.Log().Warn(() => "Added {0} = {1}".FormatWith(setting.Key, setting.Value)); } else { @@ -422,37 +444,37 @@ public void config_set(ChocolateyConfiguration configuration) ? NugetEncryptionUtility.DecryptString(config.Value) : config.Value; - if (configuration.ConfigCommand.ConfigValue.is_equal_to(currentValue.to_string())) + if (configuration.ConfigCommand.ConfigValue.IsEqualTo(currentValue.ToStringSafe())) { - this.Log().Warn(NO_CHANGE_MESSAGE); + this.Log().Warn(NoChangeMessage); } else { config.Value = configValue; - _xmlService.serialize(configFileSettings, ApplicationParameters.GlobalConfigFileLocation); + _xmlService.Serialize(ConfigFileSettings, ApplicationParameters.GlobalConfigFileLocation); - this.Log().Warn(() => "Updated {0} = {1}".format_with(config.Key, config.Value)); + this.Log().Warn(() => "Updated {0} = {1}".FormatWith(config.Key, config.Value)); } } } - public void config_unset(ChocolateyConfiguration configuration) + public void UnsetConfig(ChocolateyConfiguration configuration) { - var config = config_get(configuration.ConfigCommand.Name); + var config = GetConfigValue(configuration.ConfigCommand.Name); if (config == null || string.IsNullOrEmpty(config.Value)) { - this.Log().Warn(NO_CHANGE_MESSAGE); + this.Log().Warn(NoChangeMessage); } else { config.Value = ""; - _xmlService.serialize(configFileSettings, ApplicationParameters.GlobalConfigFileLocation); + _xmlService.Serialize(ConfigFileSettings, ApplicationParameters.GlobalConfigFileLocation); - this.Log().Warn(() => "Unset {0}".format_with(config.Key)); + this.Log().Warn(() => "Unset {0}".FormatWith(config.Key)); } } - protected void add_known_features_from_static_class(Type classType) + protected void AddKnownFeaturesFromStaticClass(Type classType) { var fieldInfos = classType.GetFields(BindingFlags.Public | BindingFlags.Static | BindingFlags.GetField); @@ -463,30 +485,116 @@ protected void add_known_features_from_static_class(Type classType) var value = (string)fi.GetValue(null); if (!string.IsNullOrEmpty(value)) { - add_known_feature(value); + AddKnownFeature(value); } } catch { - typeof(ChocolateyConfigSettingsService).Log().Debug("Unable to get value for known feature name for variable '{0}'!".format_with(fi.Name)); + typeof(ChocolateyConfigSettingsService).Log().Debug("Unable to get value for known feature name for variable '{0}'!".FormatWith(fi.Name)); } } } - protected void add_known_feature(string name) + protected void AddKnownFeature(string name) { - if (!_knownFeatures.Contains(name.to_lower())) + if (!_knownFeatures.Contains(name.ToLowerSafe())) { - _knownFeatures.Add(name.to_lower()); + _knownFeatures.Add(name.ToLowerSafe()); } } - protected void validate_supported_feature(ConfigFileFeatureSetting feature) + protected void ValidateSupportedFeature(ConfigFileFeatureSetting feature) { - if (!_knownFeatures.Contains(feature.Name.to_lower())) + if (!_knownFeatures.Contains(feature.Name.ToLowerSafe())) { - throw new ApplicationException("Feature '{0}' is not supported.".format_with(feature.Name)); + throw new ApplicationException("Feature '{0}' is not supported.".FormatWith(feature.Name)); } } + +#pragma warning disable IDE1006 + [Obsolete("This overload is deprecated and will be removed in v3.")] + public void noop(ChocolateyConfiguration configuration) + => DryRun(configuration); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public virtual bool skip_source(ConfigFileSourceSetting source, ChocolateyConfiguration configuration) + => SkipSource(source, configuration); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public virtual IEnumerable source_list(ChocolateyConfiguration configuration) + => ListSources(configuration); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public void source_add(ChocolateyConfiguration configuration) + => AddSource(configuration); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public void source_remove(ChocolateyConfiguration configuration) + => RemoveSource(configuration); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public void source_disable(ChocolateyConfiguration configuration) + => DisableSource(configuration); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public void source_enable(ChocolateyConfiguration configuration) + => EnableSource(configuration); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public void feature_list(ChocolateyConfiguration configuration) + => ListFeatures(configuration); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public void feature_disable(ChocolateyConfiguration configuration) + => DisableFeature(configuration); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public void feature_enable(ChocolateyConfiguration configuration) + => EnableFeature(configuration); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public string get_api_key(ChocolateyConfiguration configuration, Action keyAction) + => GetApiKey(configuration, keyAction); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public void set_api_key(ChocolateyConfiguration configuration) + => SetApiKey(configuration); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public void remove_api_key(ChocolateyConfiguration configuration) + => RemoveApiKey(configuration); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public void config_list(ChocolateyConfiguration configuration) + => ListConfig(configuration); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public void config_get(ChocolateyConfiguration configuration) + => GetConfig(configuration); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public ConfigFileConfigSetting config_get(string configKeyName) + => GetConfigValue(configKeyName); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public void config_set(ChocolateyConfiguration configuration) + => SetConfig(configuration); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public void config_unset(ChocolateyConfiguration configuration) + => UnsetConfig(configuration); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + protected void add_known_features_from_static_class(Type classType) + => AddKnownFeaturesFromStaticClass(classType); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + protected void add_known_feature(string name) + => AddKnownFeature(name); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + protected void validate_supported_feature(ConfigFileFeatureSetting feature) + => ValidateSupportedFeature(feature); +#pragma warning disable IDE1006 } } diff --git a/src/chocolatey/infrastructure.app/services/ChocolateyPackageInformationService.cs b/src/chocolatey/infrastructure.app/services/ChocolateyPackageInformationService.cs index d40bd93d0b..4450823e60 100644 --- a/src/chocolatey/infrastructure.app/services/ChocolateyPackageInformationService.cs +++ b/src/chocolatey/infrastructure.app/services/ChocolateyPackageInformationService.cs @@ -35,15 +35,15 @@ public class ChocolateyPackageInformationService : IChocolateyPackageInformation private readonly IRegistryService _registryService; private readonly IFilesService _filesService; private readonly ChocolateyConfiguration _config; - private const string REGISTRY_SNAPSHOT_FILE = ".registry"; - private const string REGISTRY_SNAPSHOT_BAD_FILE = ".registry.bad"; - private const string FILES_SNAPSHOT_FILE = ".files"; - private const string SILENT_UNINSTALLER_FILE = ".silentUninstaller"; - private const string SIDE_BY_SIDE_FILE = ".sxs"; - private const string PIN_FILE = ".pin"; - private const string ARGS_FILE = ".arguments"; - private const string EXTRA_FILE = ".extra"; - private const string VERSION_OVERRIDE_FILE = ".version"; + private const string RegistrySnapshotFile = ".registry"; + private const string RegistrySnapshotBadFile = ".registry.bad"; + private const string FilesSnapshotFile = ".files"; + private const string SilentUninstallerFile = ".silentUninstaller"; + private const string SideBySideFile = ".sxs"; + private const string PinFile = ".pin"; + private const string ArgsFile = ".arguments"; + private const string ExtraFile = ".extra"; + private const string VersionOverrideFile = ".version"; // We need to store the package identifiers we have warned about // to prevent duplicated outputs. @@ -54,7 +54,7 @@ public ChocolateyPackageInformationService(IFileSystem fileSystem, IRegistryServ _fileSystem = fileSystem; _registryService = registryService; _filesService = filesService; - _config = Config.get_configuration_settings(); + _config = Config.GetConfigurationSettings(); } public ChocolateyPackageInformationService(IFileSystem fileSystem, IRegistryService registryService, IFilesService filesService, ChocolateyConfiguration config) @@ -65,7 +65,7 @@ public ChocolateyPackageInformationService(IFileSystem fileSystem, IRegistryServ _config = config; } - public ChocolateyPackageInformation get_package_information(IPackageMetadata package) + public ChocolateyPackageInformation Get(IPackageMetadata package) { var packageInformation = new ChocolateyPackageInformation(package); if (package == null) @@ -74,8 +74,9 @@ public ChocolateyPackageInformation get_package_information(IPackageMetadata pac return packageInformation; } - var pkgStorePath = _fileSystem.combine_paths(ApplicationParameters.ChocolateyPackageInfoStoreLocation, "{0}.{1}".format_with(package.Id, package.Version.to_string())); - if (!_fileSystem.directory_exists(pkgStorePath)) + var pkgStorePath = GetStorePath(_fileSystem, package.Id, package.Version); + + if (!_fileSystem.DirectoryExists(pkgStorePath)) { return packageInformation; } @@ -93,17 +94,17 @@ focus exclusively in the string values not surrounded by CData. Once NOTE: It will not be possible to rename the file in Windows Explorer. Instead, you can use the following PowerShell command: Move-Item .\.registry.bad .\.registry -".format_with(_fileSystem.combine_paths(pkgStorePath, REGISTRY_SNAPSHOT_BAD_FILE)); +".FormatWith(_fileSystem.CombinePaths(pkgStorePath, RegistrySnapshotBadFile)); try { - if (_fileSystem.file_exists(_fileSystem.combine_paths(pkgStorePath, REGISTRY_SNAPSHOT_BAD_FILE))) + if (_fileSystem.FileExists(_fileSystem.CombinePaths(pkgStorePath, RegistrySnapshotBadFile))) { if (_config.RegularOutput) this.Log().Warn(deserializationErrorMessage); } else { - packageInformation.RegistrySnapshot = _registryService.read_from_file(_fileSystem.combine_paths(pkgStorePath, REGISTRY_SNAPSHOT_FILE)); + packageInformation.RegistrySnapshot = _registryService.ReadRegistrySnapshot(_fileSystem.CombinePaths(pkgStorePath, RegistrySnapshotFile)); } } catch (Exception e) @@ -112,27 +113,27 @@ focus exclusively in the string values not surrounded by CData. Once has errored attempting to read it. This file will be renamed to '{1}' The error: {2} - ".format_with(_fileSystem.combine_paths(pkgStorePath, REGISTRY_SNAPSHOT_FILE), _fileSystem.combine_paths(pkgStorePath, REGISTRY_SNAPSHOT_BAD_FILE), e.ToString())); + ".FormatWith(_fileSystem.CombinePaths(pkgStorePath, RegistrySnapshotFile), _fileSystem.CombinePaths(pkgStorePath, RegistrySnapshotBadFile), e.ToString())); - FaultTolerance.try_catch_with_logging_exception( + FaultTolerance.TryCatchWithLoggingException( () => { if (_config.RegularOutput) this.Log().Warn(deserializationErrorMessage); // rename the bad registry file so that it isn't processed again - _fileSystem.move_file(_fileSystem.combine_paths(pkgStorePath, REGISTRY_SNAPSHOT_FILE), _fileSystem.combine_paths(pkgStorePath, REGISTRY_SNAPSHOT_BAD_FILE)); + _fileSystem.MoveFile(_fileSystem.CombinePaths(pkgStorePath, RegistrySnapshotFile), _fileSystem.CombinePaths(pkgStorePath, RegistrySnapshotBadFile)); }, - "Unable to read registry snapshot file for {0} (located at {1})".format_with(package.Id, _fileSystem.combine_paths(pkgStorePath, REGISTRY_SNAPSHOT_FILE)), + "Unable to read registry snapshot file for {0} (located at {1})".FormatWith(package.Id, _fileSystem.CombinePaths(pkgStorePath, RegistrySnapshotFile)), throwError: false, logWarningInsteadOfError: true, isSilent: true ); } - FaultTolerance.try_catch_with_logging_exception( + FaultTolerance.TryCatchWithLoggingException( () => { - packageInformation.FilesSnapshot = _filesService.read_from_file(_fileSystem.combine_paths(pkgStorePath, FILES_SNAPSHOT_FILE)); + packageInformation.FilesSnapshot = _filesService.ReadPackageSnapshot(_fileSystem.CombinePaths(pkgStorePath, FilesSnapshotFile)); }, "Unable to read files snapshot file", throwError: false, @@ -140,21 +141,21 @@ has errored attempting to read it. This file will be renamed to isSilent:true ); - packageInformation.HasSilentUninstall = _fileSystem.file_exists(_fileSystem.combine_paths(pkgStorePath, SILENT_UNINSTALLER_FILE)); - packageInformation.IsPinned = _fileSystem.file_exists(_fileSystem.combine_paths(pkgStorePath, PIN_FILE)); - var argsFile = _fileSystem.combine_paths(pkgStorePath, ARGS_FILE); - if (_fileSystem.file_exists(argsFile)) packageInformation.Arguments = _fileSystem.read_file(argsFile); - var extraInfoFile = _fileSystem.combine_paths(pkgStorePath, EXTRA_FILE); - if (_fileSystem.file_exists(extraInfoFile)) packageInformation.ExtraInformation = _fileSystem.read_file(extraInfoFile); + packageInformation.HasSilentUninstall = _fileSystem.FileExists(_fileSystem.CombinePaths(pkgStorePath, SilentUninstallerFile)); + packageInformation.IsPinned = _fileSystem.FileExists(_fileSystem.CombinePaths(pkgStorePath, PinFile)); + var argsFile = _fileSystem.CombinePaths(pkgStorePath, ArgsFile); + if (_fileSystem.FileExists(argsFile)) packageInformation.Arguments = _fileSystem.ReadFile(argsFile); + var extraInfoFile = _fileSystem.CombinePaths(pkgStorePath, ExtraFile); + if (_fileSystem.FileExists(extraInfoFile)) packageInformation.ExtraInformation = _fileSystem.ReadFile(extraInfoFile); - var versionOverrideFile = _fileSystem.combine_paths(pkgStorePath, VERSION_OVERRIDE_FILE); - if (_fileSystem.file_exists(versionOverrideFile)) + var versionOverrideFile = _fileSystem.CombinePaths(pkgStorePath, VersionOverrideFile); + if (_fileSystem.FileExists(versionOverrideFile)) { - FaultTolerance.try_catch_with_logging_exception( + FaultTolerance.TryCatchWithLoggingException( () => { - packageInformation.VersionOverride = new NuGetVersion(_fileSystem.read_file(versionOverrideFile).trim_safe()); + packageInformation.VersionOverride = new NuGetVersion(_fileSystem.ReadFile(versionOverrideFile).TrimSafe()); }, "Unable to read version override file", throwError: false, @@ -165,10 +166,10 @@ has errored attempting to read it. This file will be renamed to return packageInformation; } - public void save_package_information(ChocolateyPackageInformation packageInformation) + public void Save(ChocolateyPackageInformation packageInformation) { - _fileSystem.create_directory_if_not_exists(ApplicationParameters.ChocolateyPackageInfoStoreLocation); - _fileSystem.ensure_file_attribute_set(ApplicationParameters.ChocolateyPackageInfoStoreLocation, FileAttributes.Hidden); + _fileSystem.EnsureDirectoryExists(ApplicationParameters.ChocolateyPackageInfoStoreLocation); + _fileSystem.EnsureFileAttributeSet(ApplicationParameters.ChocolateyPackageInfoStoreLocation, FileAttributes.Hidden); if (packageInformation.Package == null) { @@ -176,20 +177,21 @@ public void save_package_information(ChocolateyPackageInformation packageInforma return; } - var pkgStorePath = _fileSystem.combine_paths(ApplicationParameters.ChocolateyPackageInfoStoreLocation, "{0}.{1}".format_with(packageInformation.Package.Id, packageInformation.Package.Version.to_string())); - _fileSystem.create_directory_if_not_exists(pkgStorePath); + var pkgStorePath = GetStorePath(_fileSystem, packageInformation.Package.Id, packageInformation.Package.Version); + + _fileSystem.EnsureDirectoryExists(pkgStorePath); if (packageInformation.RegistrySnapshot != null) { - _registryService.save_to_file(packageInformation.RegistrySnapshot, _fileSystem.combine_paths(pkgStorePath, REGISTRY_SNAPSHOT_FILE)); + _registryService.SaveRegistrySnapshot(packageInformation.RegistrySnapshot, _fileSystem.CombinePaths(pkgStorePath, RegistrySnapshotFile)); } if (packageInformation.FilesSnapshot != null) { - FaultTolerance.try_catch_with_logging_exception( + FaultTolerance.TryCatchWithLoggingException( () => { - _filesService.save_to_file(packageInformation.FilesSnapshot, _fileSystem.combine_paths(pkgStorePath, FILES_SNAPSHOT_FILE)); + _filesService.SavePackageSnapshot(packageInformation.FilesSnapshot, _fileSystem.CombinePaths(pkgStorePath, FilesSnapshotFile)); }, "Unable to save files snapshot", throwError: false, @@ -199,60 +201,120 @@ public void save_package_information(ChocolateyPackageInformation packageInforma if (!string.IsNullOrWhiteSpace(packageInformation.Arguments)) { - var argsFile = _fileSystem.combine_paths(pkgStorePath, ARGS_FILE); - if (_fileSystem.file_exists(argsFile)) _fileSystem.delete_file(argsFile); - _fileSystem.write_file(argsFile, packageInformation.Arguments); + var argsFile = _fileSystem.CombinePaths(pkgStorePath, ArgsFile); + if (_fileSystem.FileExists(argsFile)) _fileSystem.DeleteFile(argsFile); + _fileSystem.WriteFile(argsFile, packageInformation.Arguments); } else { - _fileSystem.delete_file(_fileSystem.combine_paths(pkgStorePath, ARGS_FILE)); + _fileSystem.DeleteFile(_fileSystem.CombinePaths(pkgStorePath, ArgsFile)); } if (!string.IsNullOrWhiteSpace(packageInformation.ExtraInformation)) { - var extraFile = _fileSystem.combine_paths(pkgStorePath, EXTRA_FILE); - if (_fileSystem.file_exists(extraFile)) _fileSystem.delete_file(extraFile); - _fileSystem.write_file(extraFile, packageInformation.ExtraInformation); + var extraFile = _fileSystem.CombinePaths(pkgStorePath, ExtraFile); + if (_fileSystem.FileExists(extraFile)) _fileSystem.DeleteFile(extraFile); + _fileSystem.WriteFile(extraFile, packageInformation.ExtraInformation); } else { - _fileSystem.delete_file(_fileSystem.combine_paths(pkgStorePath, EXTRA_FILE)); + _fileSystem.DeleteFile(_fileSystem.CombinePaths(pkgStorePath, ExtraFile)); } if (packageInformation.VersionOverride != null) { - var versionOverrideFile = _fileSystem.combine_paths(pkgStorePath, VERSION_OVERRIDE_FILE); - if (_fileSystem.file_exists(versionOverrideFile)) _fileSystem.delete_file(versionOverrideFile); - _fileSystem.write_file(versionOverrideFile, packageInformation.VersionOverride.to_string()); + var versionOverrideFile = _fileSystem.CombinePaths(pkgStorePath, VersionOverrideFile); + if (_fileSystem.FileExists(versionOverrideFile)) _fileSystem.DeleteFile(versionOverrideFile); + _fileSystem.WriteFile(versionOverrideFile, packageInformation.VersionOverride.ToStringSafe()); } else { - _fileSystem.delete_file(_fileSystem.combine_paths(pkgStorePath, VERSION_OVERRIDE_FILE)); + _fileSystem.DeleteFile(_fileSystem.CombinePaths(pkgStorePath, VersionOverrideFile)); } if (packageInformation.HasSilentUninstall) { - _fileSystem.write_file(_fileSystem.combine_paths(pkgStorePath, SILENT_UNINSTALLER_FILE), string.Empty, Encoding.ASCII); + _fileSystem.WriteFile(_fileSystem.CombinePaths(pkgStorePath, SilentUninstallerFile), string.Empty, Encoding.ASCII); } // Legacy side-by-side installation data cleanup - _fileSystem.delete_file(_fileSystem.combine_paths(pkgStorePath, SIDE_BY_SIDE_FILE)); + _fileSystem.DeleteFile(_fileSystem.CombinePaths(pkgStorePath, SideBySideFile)); if (packageInformation.IsPinned) { - _fileSystem.write_file(_fileSystem.combine_paths(pkgStorePath, PIN_FILE), string.Empty, Encoding.ASCII); + _fileSystem.WriteFile(_fileSystem.CombinePaths(pkgStorePath, PinFile), string.Empty, Encoding.ASCII); } else { - _fileSystem.delete_file(_fileSystem.combine_paths(pkgStorePath, PIN_FILE)); + _fileSystem.DeleteFile(_fileSystem.CombinePaths(pkgStorePath, PinFile)); } } - public void remove_package_information(IPackageMetadata package) + public void Remove(IPackageMetadata package) { - var pkgStorePath = _fileSystem.combine_paths(ApplicationParameters.ChocolateyPackageInfoStoreLocation, "{0}.{1}".format_with(package.Id, package.Version.to_string())); - if (_config.RegularOutput) this.Log().Info("Removing Package Information for {0}".format_with(pkgStorePath)); - _fileSystem.delete_directory_if_exists(pkgStorePath, recursive: true); + var pkgStorePath = GetStorePath(_fileSystem, package.Id, package.Version); + if (_config.RegularOutput) this.Log().Info("Removing Package Information for {0}".FormatWith(pkgStorePath)); + _fileSystem.DeleteDirectoryChecked(pkgStorePath, recursive: true); + } + + private static string GetStorePath(IFileSystem fileSystem, string id, NuGetVersion version) + { + var preferredStorePath = fileSystem.CombinePaths(ApplicationParameters.ChocolateyPackageInfoStoreLocation, "{0}.{1}".FormatWith(id, version.ToNormalizedStringChecked())); + + if (fileSystem.DirectoryExists(preferredStorePath)) + { + return preferredStorePath; + } + + var pkgStorePath = fileSystem.CombinePaths(ApplicationParameters.ChocolateyPackageInfoStoreLocation, "{0}.{1}".FormatWith(id, version.ToStringSafe())); + + if (fileSystem.DirectoryExists(pkgStorePath)) + { + return pkgStorePath; + } + + // Legacy handling for package version that was installed originally as 4.0.0.0 + + var versionFull = version.IsPrerelease + ? "{0}-{1}".FormatWith(version.Version.ToStringSafe(), version.Release) + : version.Version.ToStringSafe(); + pkgStorePath = fileSystem.CombinePaths(ApplicationParameters.ChocolateyPackageInfoStoreLocation, "{0}.{1}".FormatWith(id, versionFull)); + + if (fileSystem.DirectoryExists(pkgStorePath)) + { + return pkgStorePath; + } + + // Legacy handling for package versions that was installed originally as "4.2" + + if (version.Version.Revision == 0 && version.Version.Build == 0) + { + versionFull = version.IsPrerelease + ? "{0}.{1}-{2}".FormatWith(version.Major, version.Minor, version.Release) + : "{0}.{1}".FormatWith(version.Major, version.Minor); + pkgStorePath = fileSystem.CombinePaths(ApplicationParameters.ChocolateyPackageInfoStoreLocation, "{0}.{1}".FormatWith(id, versionFull)); + + if (fileSystem.DirectoryExists(pkgStorePath)) + { + return pkgStorePath; + } + } + + return preferredStorePath; } + +#pragma warning disable IDE1006 + [Obsolete("This overload is deprecated and will be removed in v3.")] + public ChocolateyPackageInformation get_package_information(IPackageMetadata package) + => Get(package); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public void save_package_information(ChocolateyPackageInformation packageInformation) + => Save(packageInformation); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public void remove_package_information(IPackageMetadata package) + => Remove(package); +#pragma warning restore IDE1006 } } diff --git a/src/chocolatey/infrastructure.app/services/ChocolateyPackageService.cs b/src/chocolatey/infrastructure.app/services/ChocolateyPackageService.cs index ad9811e288..21912f20ac 100644 --- a/src/chocolatey/infrastructure.app/services/ChocolateyPackageService.cs +++ b/src/chocolatey/infrastructure.app/services/ChocolateyPackageService.cs @@ -19,9 +19,11 @@ namespace chocolatey.infrastructure.app.services using System; using System.Collections.Concurrent; using System.Collections.Generic; + using System.ComponentModel.Design; using System.IO; using System.Linq; using System.Text; + using chocolatey.infrastructure.app.registration; using commandline; using configuration; using domain; @@ -37,6 +39,7 @@ namespace chocolatey.infrastructure.app.services using NuGet.Versioning; using platforms; using results; + using SimpleInjector; using tolerance; using IFileSystem = filesystem.IFileSystem; @@ -44,7 +47,6 @@ public class ChocolateyPackageService : IChocolateyPackageService { private readonly INugetService _nugetService; private readonly IPowershellService _powershellService; - private readonly IEnumerable _sourceRunners; private readonly IShimGenerationService _shimgenService; private readonly IFileSystem _fileSystem; private readonly IRegistryService _registryService; @@ -53,6 +55,7 @@ public class ChocolateyPackageService : IChocolateyPackageService private readonly IAutomaticUninstallerService _autoUninstallerService; private readonly IXmlService _xmlService; private readonly IConfigTransformService _configTransformService; + private readonly IContainerResolver _containerResolver; private readonly IDictionary _pendingLocks = new Dictionary(); private readonly IList _proBusinessMessages = new List { @@ -94,7 +97,7 @@ system admins into something amazing! Singlehandedly solve your https://chocolatey.org/compare" }; - private const string PRO_BUSINESS_LIST_MESSAGE = @" + private const string ProBusinessListMessage = @" Did you know Pro / Business automatically syncs with Programs and Features? Learn more about Package Synchronizer at https://chocolatey.org/compare"; @@ -106,16 +109,21 @@ Did you know Pro / Business automatically syncs with Programs and // 3010 - restart required private readonly List _rebootExitCodes = new List { 1641, 3010 }; - public ChocolateyPackageService(INugetService nugetService, IPowershellService powershellService, - IEnumerable sourceRunners, IShimGenerationService shimgenService, - IFileSystem fileSystem, IRegistryService registryService, - IChocolateyPackageInformationService packageInfoService, IFilesService filesService, - IAutomaticUninstallerService autoUninstallerService, IXmlService xmlService, - IConfigTransformService configTransformService) + public ChocolateyPackageService( + INugetService nugetService, + IPowershellService powershellService, + IShimGenerationService shimgenService, + IFileSystem fileSystem, + IRegistryService registryService, + IChocolateyPackageInformationService packageInfoService, + IFilesService filesService, + IAutomaticUninstallerService autoUninstallerService, + IXmlService xmlService, + IConfigTransformService configTransformService, + IContainerResolver containerResolver) { _nugetService = nugetService; _powershellService = powershellService; - _sourceRunners = sourceRunners; _shimgenService = shimgenService; _fileSystem = fileSystem; _registryService = registryService; @@ -124,50 +132,120 @@ public ChocolateyPackageService(INugetService nugetService, IPowershellService p _autoUninstallerService = autoUninstallerService; _xmlService = xmlService; _configTransformService = configTransformService; + _containerResolver = containerResolver; } - public virtual void ensure_source_app_installed(ChocolateyConfiguration config) + public virtual int Count(ChocolateyConfiguration config) { - perform_source_runner_action(config, r => r.ensure_source_app_installed(config, (packageResult, configuration) => handle_package_result(packageResult, configuration, CommandNameType.install))); + if (config.SourceType.IsEqualTo(SourceTypes.Normal)) + { + return _nugetService.Count(config); + } + + return PerformSourceRunnerFunction( + config, + runner => runner.Count(config), + throwOnException: true); } - public virtual int count_run(ChocolateyConfiguration config) + private void PerformSourceRunnerAction(ChocolateyConfiguration config, Action action, bool throwOnException = false) + where TSourceRunner : class, IAlternativeSourceRunner { - return perform_source_runner_function(config, r => r.count_run(config)); + var alternativeSourceRunners = _containerResolver.ResolveAll(); + PerformSourceRunnerAction(config, action, alternativeSourceRunners, throwOnException); } - private void perform_source_runner_action(ChocolateyConfiguration config, Action action) + private void PerformSourceRunnerAction(ChocolateyConfiguration config, Action action, IEnumerable alternativeSourceRunners, bool throwOnException = false) + where TSourceRunner : class, IAlternativeSourceRunner { - var runner = get_source_runner(config.SourceType); + var runner = GetSourceRunner(config.SourceType, alternativeSourceRunners); if (runner != null && action != null) { + if (runner is IBootstrappableSourceRunner bootstrapper) + { + bootstrapper.EnsureSourceAppInstalled(config, (packageResult, configuration) => HandlePackageResult(packageResult, configuration, CommandNameType.Install)); + } + action.Invoke(runner); } else { - this.Log().Warn("No runner was found that implements source type '{0}' or action was missing".format_with(config.SourceType)); + if (throwOnException) + { + throw new NotSupportedException("No runner was found that implements source type '{0}' or action was missing".FormatWith(config.SourceType)); + } + else + { + this.Log().Warn("No runner was found that implements source type '{0}' or action was missing".FormatWith(config.SourceType)); + } } } - private T perform_source_runner_function(ChocolateyConfiguration config, Func function) + private TResult PerformSourceRunnerFunction(ChocolateyConfiguration config, Func function, bool throwOnException = false) + where TSourceRunner : class, IAlternativeSourceRunner + { + var alternativeSourceRunners = _containerResolver.ResolveAll(); + return PerformSourceRunnerFunction(config, function, alternativeSourceRunners, throwOnException); + } + + private TResult PerformSourceRunnerFunction(ChocolateyConfiguration config, Func function, IEnumerable alternativeSourceRunners, bool throwOnException = false) + where TSourceRunner : class, IAlternativeSourceRunner { - var runner = get_source_runner(config.SourceType); + var runner = GetSourceRunner(config.SourceType, alternativeSourceRunners); if (runner != null && function != null) { + if (runner is IBootstrappableSourceRunner bootstrapper) + { + // NOTE: Here we are passing the original config into the HandlePackageResult method, rather than what comes out of the Action, since + // that configuration could be wildly different from what was passed in, and we want to continue with what was in play before + // installing the required source application. + bootstrapper.EnsureSourceAppInstalled(config, (packageResult, configuration) => HandlePackageResult(packageResult, config, CommandNameType.Install)); + } + return function.Invoke(runner); } - this.Log().Warn("No runner was found that implements source type '{0}' or function was missing.".format_with(config.SourceType)); - return default(T); + if (throwOnException) + { + throw new NotSupportedException("No runner was found that implements source type '{0}' or, it does not support requested functionality.".FormatWith(config.SourceType)); + } + else + { + this.Log().Warn("No runner was found that implements source type '{0}' or, it does not support requested functionality.".FormatWith(config.SourceType)); + } + + return default; } - public void list_noop(ChocolateyConfiguration config) + public void ListDryRun(ChocolateyConfiguration config) { - perform_source_runner_action(config, r => r.list_noop(config)); - randomly_notify_about_pro_business(config, PRO_BUSINESS_LIST_MESSAGE); + if (string.IsNullOrWhiteSpace(config.Sources) && !config.ListCommand.LocalOnly) + { + this.Log().Error(ChocolateyLoggers.Important, @"Unable to search for packages when there are no sources enabled for + packages and none were passed as arguments."); + Environment.ExitCode = 1; + return; + } + + config.Noop = true; + + if (config.ListCommand.LocalOnly && !config.SourceType.IsEqualTo(SourceTypes.Normal)) + { + PerformSourceRunnerAction(config, runner => runner.ListDryRun(config)); + } + else if (config.SourceType.IsEqualTo(SourceTypes.Normal)) + { + _nugetService.ListDryRun(config); + } + else + { + PerformSourceRunnerAction(config, runner => runner.SearchDryRun(config)); + } + + RandomlyNotifyAboutLicensedFeatures(config, ProBusinessListMessage); } - public virtual IEnumerable list_run(ChocolateyConfiguration config) + public virtual IEnumerable List(ChocolateyConfiguration config) { if (string.IsNullOrWhiteSpace(config.Sources) && !config.ListCommand.LocalOnly) { @@ -181,9 +259,30 @@ public virtual IEnumerable list_run(ChocolateyConfiguration confi var packages = new List(); - foreach (PackageResult package in perform_source_runner_function(config, r => r.list_run(config))) + IEnumerable results; + + if (config.ListCommand.LocalOnly && !config.SourceType.IsEqualTo(SourceTypes.Normal)) { - if (config.SourceType.is_equal_to(SourceTypes.NORMAL)) + results = PerformSourceRunnerFunction>(config, runner => runner.List(config)); + } + else if (config.SourceType.IsEqualTo(SourceTypes.Normal)) + { + results = _nugetService.List(config).OrEmpty(); + } + else + { + results = PerformSourceRunnerFunction>(config, runner => runner.Search(config)); + } + + if (results is null) + { + var message = config.ListCommand.LocalOnly ? "The '{0}' source does not support listing of packages".FormatWith(config.SourceType) : "The '{0}' source does not support searching for packages".FormatWith(config.SourceType); + throw new NotSupportedException(message); + } + + foreach (PackageResult package in results) + { + if (config.SourceType.IsEqualTo(SourceTypes.Normal)) { if (!config.ListCommand.IncludeRegistryPrograms) { @@ -201,33 +300,33 @@ public virtual IEnumerable list_run(ChocolateyConfiguration confi { if (config.ListCommand.LocalOnly && config.ListCommand.IncludeRegistryPrograms) { - foreach (var installed in report_registry_programs(config, packages)) + foreach (var installed in ReportRegistryPrograms(config, packages)) { yield return installed; } } } - randomly_notify_about_pro_business(config, PRO_BUSINESS_LIST_MESSAGE); + RandomlyNotifyAboutLicensedFeatures(config, ProBusinessListMessage); } - private IEnumerable report_registry_programs(ChocolateyConfiguration config, IEnumerable list) + private IEnumerable ReportRegistryPrograms(ChocolateyConfiguration config, IEnumerable list) { - var itemsToRemoveFromMachine = list.Select(package => _packageInfoService.get_package_information(package.PackageMetadata)).Where(p => p.RegistrySnapshot != null).ToList(); + var itemsToRemoveFromMachine = list.Select(package => _packageInfoService.Get(package.PackageMetadata)).Where(p => p.RegistrySnapshot != null).ToList(); var count = 0; - var machineInstalled = _registryService.get_installer_keys().RegistryKeys.Where( - p => p.is_in_programs_and_features() && - !itemsToRemoveFromMachine.Any(pkg => pkg.RegistrySnapshot.RegistryKeys.Any(k => k.DisplayName.is_equal_to(p.DisplayName))) && - !p.KeyPath.contains("choco-")).OrderBy(p => p.DisplayName).Distinct(); + var machineInstalled = _registryService.GetInstallerKeys().RegistryKeys.Where( + p => p.IsInProgramsAndFeatures() && + !itemsToRemoveFromMachine.Any(pkg => pkg.RegistrySnapshot.RegistryKeys.Any(k => k.DisplayName.IsEqualTo(p.DisplayName))) && + !p.KeyPath.ContainsSafe("choco-")).OrderBy(p => p.DisplayName).Distinct(); this.Log().Info(() => ""); foreach (var key in machineInstalled) { if (config.RegularOutput) { - this.Log().Info("{0}|{1}".format_with(key.DisplayName, key.DisplayVersion)); - if (config.Verbose) this.Log().Info(" InstallLocation: {0}{1} Uninstall:{2}".format_with(key.InstallLocation.to_string().escape_curly_braces(), Environment.NewLine, key.UninstallString.to_string().escape_curly_braces())); + this.Log().Info("{0}|{1}".FormatWith(key.DisplayName, key.DisplayVersion)); + if (config.Verbose) this.Log().Info(" InstallLocation: {0}{1} Uninstall:{2}".FormatWith(key.InstallLocation.ToStringSafe().EscapeCurlyBraces(), Environment.NewLine, key.UninstallString.ToStringSafe().EscapeCurlyBraces())); } count++; @@ -236,75 +335,81 @@ private IEnumerable report_registry_programs(ChocolateyConfigurat if (config.RegularOutput) { - this.Log().Warn(() => @"{0} applications not managed with Chocolatey.".format_with(count)); + this.Log().Warn(() => @"{0} applications not managed with Chocolatey.".FormatWith(count)); } } - public void pack_noop(ChocolateyConfiguration config) + public void PackDryRun(ChocolateyConfiguration config) { - if (!config.SourceType.is_equal_to(SourceTypes.NORMAL)) + if (!config.SourceType.IsEqualTo(SourceTypes.Normal)) { this.Log().Warn(ChocolateyLoggers.Important, "This source doesn't provide a facility for packaging."); return; } - _nugetService.pack_noop(config); - randomly_notify_about_pro_business(config); + _nugetService.PackDryRun(config); + RandomlyNotifyAboutLicensedFeatures(config); } - public virtual void pack_run(ChocolateyConfiguration config) + public virtual void Pack(ChocolateyConfiguration config) { - if (!config.SourceType.is_equal_to(SourceTypes.NORMAL)) + if (!config.SourceType.IsEqualTo(SourceTypes.Normal)) { this.Log().Warn(ChocolateyLoggers.Important, "This source doesn't provide a facility for packaging."); return; } - _nugetService.pack_run(config); - randomly_notify_about_pro_business(config); + _nugetService.Pack(config); + RandomlyNotifyAboutLicensedFeatures(config); } - public void push_noop(ChocolateyConfiguration config) + public void PushDryRun(ChocolateyConfiguration config) { - if (!config.SourceType.is_equal_to(SourceTypes.NORMAL)) + if (!config.SourceType.IsEqualTo(SourceTypes.Normal)) { this.Log().Warn(ChocolateyLoggers.Important, "This source doesn't provide a facility for pushing."); return; } - _nugetService.push_noop(config); - randomly_notify_about_pro_business(config); + _nugetService.PushDryRun(config); + RandomlyNotifyAboutLicensedFeatures(config); } - public virtual void push_run(ChocolateyConfiguration config) + public virtual void Push(ChocolateyConfiguration config) { - if (!config.SourceType.is_equal_to(SourceTypes.NORMAL)) + if (!config.SourceType.IsEqualTo(SourceTypes.Normal)) { this.Log().Warn(ChocolateyLoggers.Important, "This source doesn't provide a facility for pushing."); return; } - _nugetService.push_run(config); - randomly_notify_about_pro_business(config); + _nugetService.Push(config); + RandomlyNotifyAboutLicensedFeatures(config); } - public void install_noop(ChocolateyConfiguration config) + public void InstallDryRun(ChocolateyConfiguration config) { - validate_package_names(config); + ValidatePackageNames(config); + + var installSourceRunners = _containerResolver.ResolveAll(); // each package can specify its own configuration values - foreach (var packageConfig in set_config_from_package_names_and_packages_config(config, new ConcurrentDictionary()).or_empty_list_if_null()) + foreach (var packageConfig in GetConfigFromInputAndPackageConfigInput(config, new ConcurrentDictionary(), installSourceRunners).OrEmpty()) { - Action action = null; - if (packageConfig.SourceType.is_equal_to(SourceTypes.NORMAL)) + config.Noop = true; + + if (packageConfig.SourceType.IsEqualTo(SourceTypes.Normal)) { - action = (pkg,configuration) => _powershellService.install_noop(pkg); + Action action = (pkg, configuration) => _powershellService.InstallDryRun(pkg); + _nugetService.InstallDryRun(packageConfig, action); + } + else + { + PerformSourceRunnerAction(config, runner => runner.InstallDryRun(packageConfig, null), installSourceRunners); } - - perform_source_runner_action(packageConfig, r => r.install_noop(packageConfig, action)); } - randomly_notify_about_pro_business(config); + RandomlyNotifyAboutLicensedFeatures(config); } /// @@ -313,7 +418,7 @@ public void install_noop(ChocolateyConfiguration config) /// The configuration. /// The message to send. /// We want it random enough not to be annoying, but informative enough for awareness. - public void randomly_notify_about_pro_business(ChocolateyConfiguration config, string message = null) + public void RandomlyNotifyAboutLicensedFeatures(ChocolateyConfiguration config, string message = null) { if (!config.Information.IsLicensedVersion && config.RegularOutput) { @@ -336,16 +441,16 @@ public void randomly_notify_about_pro_business(ChocolateyConfiguration config, s } } - public virtual void handle_package_result(PackageResult packageResult, ChocolateyConfiguration config, CommandNameType commandName) + public virtual void HandlePackageResult(PackageResult packageResult, ChocolateyConfiguration config, CommandNameType commandName) { - EnvironmentSettings.reset_environment_variables(config); - set_pending(packageResult, config); + EnvironmentSettings.ResetEnvironmentVariables(config); + MarkPackagePending(packageResult, config); this.Log().Info(packageResult.ExitCode == 0 - ? "{0} package files {1} completed. Performing other installation steps.".format_with(packageResult.Name, commandName.to_string()) - : "{0} package files {1} failed with exit code {2}. Performing other installation steps.".format_with(packageResult.Name, commandName.to_string(), packageResult.ExitCode)); + ? "{0} package files {1} completed. Performing other installation steps.".FormatWith(packageResult.Name, commandName.ToStringSafe()) + : "{0} package files {1} failed with exit code {2}. Performing other installation steps.".FormatWith(packageResult.Name, commandName.ToStringSafe(), packageResult.ExitCode)); - var pkgInfo = get_package_information(packageResult, config); + var pkgInfo = GetPackageInformation(packageResult, config); // initialize this here so it can be used for the install location later bool powerShellRan = false; @@ -354,17 +459,17 @@ public virtual void handle_package_result(PackageResult packageResult, Chocolate { if (!config.SkipPackageInstallProvider) { - var installersBefore = _registryService.get_installer_keys(); - var environmentBefore = get_environment_before(config, allowLogging: false); + var installersBefore = _registryService.GetInstallerKeys(); + var environmentBefore = GetInitialEnvironment(config, allowLogging: false); - powerShellRan = _powershellService.install(config, packageResult); + powerShellRan = _powershellService.Install(config, packageResult); if (powerShellRan) { // we don't care about the exit code - if (config.Information.PlatformType == PlatformType.Windows) CommandExecutor.execute_static(_shutdownExe, "/a", config.CommandExecutionTimeoutSeconds, _fileSystem.get_current_directory(), (s, e) => { }, (s, e) => { }, false, false); + if (config.Information.PlatformType == PlatformType.Windows) CommandExecutor.ExecuteStatic(_shutdownExe, "/a", config.CommandExecutionTimeoutSeconds, _fileSystem.GetCurrentDirectory(), (s, e) => { }, (s, e) => { }, false, false); } - var installersDifferences = _registryService.get_installer_key_differences(installersBefore, _registryService.get_installer_keys()); + var installersDifferences = _registryService.GetInstallerKeysChanged(installersBefore, _registryService.GetInstallerKeys()); if (installersDifferences.RegistryKeys.Count != 0) { //todo: #2567 - note keys passed in @@ -374,54 +479,54 @@ public virtual void handle_package_result(PackageResult packageResult, Chocolate if (key != null && key.HasQuietUninstall) { pkgInfo.HasSilentUninstall = true; - this.Log().Info(" {0} can be automatically uninstalled.".format_with(packageResult.Name)); + this.Log().Info(" {0} can be automatically uninstalled.".FormatWith(packageResult.Name)); } else if (key != null) { - this.Log().Info(" {0} may be able to be automatically uninstalled.".format_with(packageResult.Name)); + this.Log().Info(" {0} may be able to be automatically uninstalled.".FormatWith(packageResult.Name)); } } IEnumerable environmentChanges; IEnumerable environmentRemovals; - get_log_environment_changes(config, environmentBefore, out environmentChanges, out environmentRemovals); + LogEnvironmentChanges(config, environmentBefore, out environmentChanges, out environmentRemovals); //todo: #564 record this with package info } - _filesService.ensure_compatible_file_attributes(packageResult, config); - _configTransformService.run(packageResult, config); + _filesService.EnsureCompatibleFileAttributes(packageResult, config); + _configTransformService.Run(packageResult, config); - pkgInfo.FilesSnapshot = _filesService.capture_package_files(packageResult, config); + pkgInfo.FilesSnapshot = _filesService.CaptureSnapshot(packageResult, config); var is32Bit = !config.Information.Is64BitProcess || config.ForceX86; - create_ignore_files_for_executables(packageResult.InstallLocation, !is32Bit); + CreateExecutableIgnoreFiles(packageResult.InstallLocation, !is32Bit); - if (packageResult.Success) _shimgenService.install(config, packageResult); + if (packageResult.Success) _shimgenService.Install(config, packageResult); } else { if (config.Information.PlatformType != PlatformType.Windows) this.Log().Info(ChocolateyLoggers.Important, () => " Skipping PowerShell and shimgen portions of the install due to non-Windows."); if (packageResult.Success) { - _configTransformService.run(packageResult, config); - pkgInfo.FilesSnapshot = _filesService.capture_package_files(packageResult, config); + _configTransformService.Run(packageResult, config); + pkgInfo.FilesSnapshot = _filesService.CaptureSnapshot(packageResult, config); } } if (packageResult.Success) { - handle_extension_packages(config, packageResult); - handle_template_packages(config, packageResult); - handle_hook_packages(config, packageResult); - pkgInfo.Arguments = capture_arguments(config, packageResult); + HandleExtensionPackages(config, packageResult); + HandleTemplatePackages(config, packageResult); + HandleHookPackages(config, packageResult); + pkgInfo.Arguments = CaptureArguments(config, packageResult); pkgInfo.IsPinned = config.PinPackage; } var toolsLocation = Environment.GetEnvironmentVariable(ApplicationParameters.Environment.ChocolateyToolsLocation); if (!string.IsNullOrWhiteSpace(toolsLocation) && string.IsNullOrWhiteSpace(Environment.GetEnvironmentVariable(ApplicationParameters.Environment.ChocolateyPackageInstallLocation))) { - toolsLocation = _fileSystem.combine_paths(toolsLocation, packageResult.Name); - if (_fileSystem.directory_exists(toolsLocation)) + toolsLocation = _fileSystem.CombinePaths(toolsLocation, packageResult.Name); + if (_fileSystem.DirectoryExists(toolsLocation)) { Environment.SetEnvironmentVariable(ApplicationParameters.Environment.ChocolateyPackageInstallLocation, toolsLocation, EnvironmentVariableTarget.Process); } @@ -438,11 +543,11 @@ public virtual void handle_package_result(PackageResult packageResult, Chocolate if (key != null) Environment.SetEnvironmentVariable(ApplicationParameters.Environment.ChocolateyPackageInstallLocation, key.InstallLocation, EnvironmentVariableTarget.Process); } - update_package_information(pkgInfo); - ensure_bad_package_path_is_clean(config, packageResult); - EventManager.publish(new HandlePackageResultCompletedMessage(packageResult, config, commandName)); + UpdatePackageInformation(pkgInfo); + EnsureBadPackagesPathIsClean(config, packageResult); + EventManager.Publish(new HandlePackageResultCompletedMessage(packageResult, config, commandName)); - remove_pending(packageResult, config); + UnmarkPackagePending(packageResult, config); if (_rebootExitCodes.Contains(packageResult.ExitCode)) { @@ -450,7 +555,7 @@ public virtual void handle_package_result(PackageResult packageResult, Chocolate { Environment.ExitCode = ApplicationParameters.ExitCodes.ErrorInstallSuspend; this.Log().Warn(ChocolateyLoggers.Important, @"Chocolatey has detected a pending reboot after installing/upgrading -package '{0}' - stopping further execution".format_with(packageResult.Name)); +package '{0}' - stopping further execution".FormatWith(packageResult.Name)); throw new ApplicationException("Reboot required before continuing. Reboot and run the same command again."); } @@ -458,30 +563,30 @@ public virtual void handle_package_result(PackageResult packageResult, Chocolate if (!packageResult.Success) { - this.Log().Error(ChocolateyLoggers.Important, "The {0} of {1} was NOT successful.".format_with(commandName.to_string(), packageResult.Name)); - handle_unsuccessful_operation(config, packageResult, movePackageToFailureLocation: true, attemptRollback: true); + this.Log().Error(ChocolateyLoggers.Important, "The {0} of {1} was NOT successful.".FormatWith(commandName.ToStringSafe(), packageResult.Name)); + HandleFailedOperation(config, packageResult, movePackageToFailureLocation: true, attemptRollback: true); if (config.Features.StopOnFirstPackageFailure) { - throw new ApplicationException("Stopping further execution as {0} has failed {1}.".format_with(packageResult.Name, commandName.to_string())); + throw new ApplicationException("Stopping further execution as {0} has failed {1}.".FormatWith(packageResult.Name, commandName.ToStringSafe())); } return; } - remove_rollback_if_exists(packageResult); + RemoveBackupIfExists(packageResult); - this.Log().Info(ChocolateyLoggers.Important, " The {0} of {1} was successful.".format_with(commandName.to_string(), packageResult.Name)); + this.Log().Info(ChocolateyLoggers.Important, " The {0} of {1} was successful.".FormatWith(commandName.ToStringSafe(), packageResult.Name)); var installLocation = Environment.GetEnvironmentVariable(ApplicationParameters.Environment.ChocolateyPackageInstallLocation); var installerDetected = Environment.GetEnvironmentVariable(ApplicationParameters.Environment.ChocolateyPackageInstallerType); if (!string.IsNullOrWhiteSpace(installLocation)) { - this.Log().Info(ChocolateyLoggers.Important, " Software installed to '{0}'".format_with(installLocation.escape_curly_braces())); + this.Log().Info(ChocolateyLoggers.Important, " Software installed to '{0}'".FormatWith(installLocation.EscapeCurlyBraces())); } else if (!string.IsNullOrWhiteSpace(installerDetected)) { - this.Log().Info(ChocolateyLoggers.Important, @" Software installed as '{0}', install location is likely default.".format_with(installerDetected)); + this.Log().Info(ChocolateyLoggers.Important, @" Software installed as '{0}', install location is likely default.".FormatWith(installerDetected)); } else { @@ -490,12 +595,12 @@ public virtual void handle_package_result(PackageResult packageResult, Chocolate } } - private void create_ignore_files_for_executables(string installLocation, bool is64Bit) + private void CreateExecutableIgnoreFiles(string installLocation, bool is64Bit) { // If we are using a 64 bit architecture, we want to ignore exe's targeting x86 // This is done by adding a .ignore file into the package folder for each exe to ignore - var exeFiles32Bit = (_fileSystem.directory_exists(_fileSystem.combine_paths(installLocation, "tools\\x86")) ? _fileSystem.get_files(_fileSystem.combine_paths(installLocation, "tools\\x86"), pattern: "*.exe", option: SearchOption.AllDirectories) : new List()).ToArray(); - var exeFiles64Bit = (_fileSystem.directory_exists(_fileSystem.combine_paths(installLocation, "tools\\x64")) ? _fileSystem.get_files(_fileSystem.combine_paths(installLocation, "tools\\x64"), pattern: "*.exe", option: SearchOption.AllDirectories) : new List()).ToArray(); + var exeFiles32Bit = (_fileSystem.DirectoryExists(_fileSystem.CombinePaths(installLocation, "tools\\x86")) ? _fileSystem.GetFiles(_fileSystem.CombinePaths(installLocation, "tools\\x86"), pattern: "*.exe", option: SearchOption.AllDirectories) : new List()).ToArray(); + var exeFiles64Bit = (_fileSystem.DirectoryExists(_fileSystem.CombinePaths(installLocation, "tools\\x64")) ? _fileSystem.GetFiles(_fileSystem.CombinePaths(installLocation, "tools\\x64"), pattern: "*.exe", option: SearchOption.AllDirectories) : new List()).ToArray(); // If 64bit, and there are only 32bit files, we should shim the 32bit versions, // therefore, don't ignore anything @@ -504,25 +609,25 @@ private void create_ignore_files_for_executables(string installLocation, bool is return; } - foreach (var exeFile in is64Bit ? exeFiles32Bit.or_empty_list_if_null() : exeFiles64Bit.or_empty_list_if_null()) + foreach (var exeFile in is64Bit ? exeFiles32Bit.OrEmpty() : exeFiles64Bit.OrEmpty()) { - _fileSystem.create_file(exeFile + ".ignore"); + _fileSystem.CreateFile(exeFile + ".ignore"); } } - protected virtual ChocolateyPackageInformation get_package_information(PackageResult packageResult, ChocolateyConfiguration config) + protected virtual ChocolateyPackageInformation GetPackageInformation(PackageResult packageResult, ChocolateyConfiguration config) { - var pkgInfo = _packageInfoService.get_package_information(packageResult.PackageMetadata); + var pkgInfo = _packageInfoService.Get(packageResult.PackageMetadata); return pkgInfo; } - protected virtual void update_package_information(ChocolateyPackageInformation pkgInfo) + protected virtual void UpdatePackageInformation(ChocolateyPackageInformation pkgInfo) { - _packageInfoService.save_package_information(pkgInfo); + _packageInfoService.Save(pkgInfo); } - private string capture_arguments(ChocolateyConfiguration config, PackageResult packageResult) + private string CaptureArguments(ChocolateyConfiguration config, PackageResult packageResult) { var arguments = new StringBuilder(); @@ -535,11 +640,11 @@ private string capture_arguments(ChocolateyConfiguration config, PackageResult p if (config.IgnoreDependencies) arguments.Append(" --ignore-dependencies"); if (config.ForceX86) arguments.Append(" --forcex86"); - if (!string.IsNullOrWhiteSpace(config.InstallArguments)) arguments.Append(" --install-arguments=\"'{0}'\"".format_with(config.InstallArguments)); + if (!string.IsNullOrWhiteSpace(config.InstallArguments)) arguments.Append(" --install-arguments=\"'{0}'\"".FormatWith(config.InstallArguments)); if (config.OverrideArguments) arguments.Append(" --override-arguments"); if (config.ApplyInstallArgumentsToDependencies) arguments.Append(" --apply-install-arguments-to-dependencies"); - if (!string.IsNullOrWhiteSpace(config.PackageParameters)) arguments.Append(" --package-parameters=\"'{0}'\"".format_with(config.PackageParameters)); + if (!string.IsNullOrWhiteSpace(config.PackageParameters)) arguments.Append(" --package-parameters=\"'{0}'\"".FormatWith(config.PackageParameters)); if (config.ApplyPackageParametersToDependencies) arguments.Append(" --apply-package-parameters-to-dependencies"); if (config.AllowDowngrade) arguments.Append(" --allow-downgrade"); @@ -548,10 +653,10 @@ private string capture_arguments(ChocolateyConfiguration config, PackageResult p //if (config.SkipPackageInstallProvider) arguments.Append(" --skip-automation-scripts"); //if (config.UpgradeCommand.FailOnUnfound) arguments.Append(" --fail-on-unfound"); - if (!string.IsNullOrWhiteSpace(config.SourceCommand.Username)) arguments.Append(" --user=\"'{0}'\"".format_with(config.SourceCommand.Username)); - if (!string.IsNullOrWhiteSpace(config.SourceCommand.Password)) arguments.Append(" --password=\"'{0}'\"".format_with(config.SourceCommand.Password)); - if (!string.IsNullOrWhiteSpace(config.SourceCommand.Certificate)) arguments.Append(" --cert=\"'{0}'\"".format_with(config.SourceCommand.Certificate)); - if (!string.IsNullOrWhiteSpace(config.SourceCommand.CertificatePassword)) arguments.Append(" --certpassword=\"'{0}'\"".format_with(config.SourceCommand.CertificatePassword)); + if (!string.IsNullOrWhiteSpace(config.SourceCommand.Username)) arguments.Append(" --user=\"'{0}'\"".FormatWith(config.SourceCommand.Username)); + if (!string.IsNullOrWhiteSpace(config.SourceCommand.Password)) arguments.Append(" --password=\"'{0}'\"".FormatWith(config.SourceCommand.Password)); + if (!string.IsNullOrWhiteSpace(config.SourceCommand.Certificate)) arguments.Append(" --cert=\"'{0}'\"".FormatWith(config.SourceCommand.Certificate)); + if (!string.IsNullOrWhiteSpace(config.SourceCommand.CertificatePassword)) arguments.Append(" --certpassword=\"'{0}'\"".FormatWith(config.SourceCommand.CertificatePassword)); // this should likely be limited //if (!config.Features.ChecksumFiles) arguments.Append(" --ignore-checksums"); @@ -562,22 +667,22 @@ private string capture_arguments(ChocolateyConfiguration config, PackageResult p //global options if (config.CommandExecutionTimeoutSeconds != ApplicationParameters.DefaultWaitForExitInSeconds) { - arguments.Append(" --execution-timeout=\"'{0}'\"".format_with(config.CommandExecutionTimeoutSeconds)); + arguments.Append(" --execution-timeout=\"'{0}'\"".FormatWith(config.CommandExecutionTimeoutSeconds)); } - if (!string.IsNullOrWhiteSpace(config.CacheLocation)) arguments.Append(" --cache-location=\"'{0}'\"".format_with(config.CacheLocation)); + if (!string.IsNullOrWhiteSpace(config.CacheLocation)) arguments.Append(" --cache-location=\"'{0}'\"".FormatWith(config.CacheLocation)); if (config.Features.FailOnStandardError) arguments.Append(" --fail-on-standard-error"); if (!config.Features.UsePowerShellHost) arguments.Append(" --use-system-powershell"); - return NugetEncryptionUtility.EncryptString(arguments.to_string()); + return NugetEncryptionUtility.EncryptString(arguments.ToStringSafe()); } - public virtual ConcurrentDictionary install_run(ChocolateyConfiguration config) + public virtual ConcurrentDictionary Install(ChocolateyConfiguration config) { - validate_package_names(config); + ValidatePackageNames(config); - this.Log().Info(is_packages_config_file(config.PackageNames) ? @"Installing from config file:" : @"Installing the following packages:"); - this.Log().Info(ChocolateyLoggers.Important, @"{0}".format_with(config.PackageNames)); + this.Log().Info(IsPackagesConfigFile(config.PackageNames) ? @"Installing from config file:" : @"Installing the following packages:"); + this.Log().Info(ChocolateyLoggers.Important, @"{0}".FormatWith(config.PackageNames)); var packageInstalls = new ConcurrentDictionary(); @@ -591,20 +696,32 @@ public virtual ConcurrentDictionary install_run(Chocolate this.Log().Info(@"By installing, you accept licenses for the packages."); - get_environment_before(config, allowLogging: true); + GetInitialEnvironment(config, allowLogging: true); + + var installSourceRunners = _containerResolver.ResolveAll(); try { - foreach (var packageConfig in set_config_from_package_names_and_packages_config(config, packageInstalls).or_empty_list_if_null()) + foreach (var packageConfig in GetConfigFromInputAndPackageConfigInput(config, packageInstalls, installSourceRunners).OrEmpty()) { - Action action = null; - if (packageConfig.SourceType.is_equal_to(SourceTypes.NORMAL)) + ConcurrentDictionary results; + + if (packageConfig.SourceType.IsEqualTo(SourceTypes.Normal)) + { + var action = new Action((packageResult, configuration) => HandlePackageResult(packageResult, configuration, CommandNameType.Install)); + var beforeModifyAction = new Action((packageResult, configuration) => BeforeModifyAction(packageResult, configuration)); + + results = _nugetService.Install(packageConfig, action, beforeModifyAction); + } + else { - action = (packageResult, configuration) => handle_package_result(packageResult, configuration, CommandNameType.install); + results = PerformSourceRunnerFunction>(packageConfig, runner => runner.Install(packageConfig, null)); } - var beforeModifyAction = new Action((packageResult, configuration) => before_package_modify(packageResult, configuration)); - var results = perform_source_runner_function(packageConfig, r => r.install_run(packageConfig, action, beforeModifyAction)); + if (results is null) + { + throw new NotSupportedException("The '{0}' source does not support installing packages".FormatWith(config.SourceType)); + } foreach (var result in results) { @@ -614,28 +731,28 @@ public virtual ConcurrentDictionary install_run(Chocolate } finally { - var installFailures = report_action_summary(packageInstalls, "installed"); + var installFailures = ReportActionSummary(packageInstalls, "installed"); if (installFailures != 0 && Environment.ExitCode == 0) { Environment.ExitCode = 1; } - randomly_notify_about_pro_business(config); + RandomlyNotifyAboutLicensedFeatures(config); } return packageInstalls; } - public void outdated_noop(ChocolateyConfiguration config) + public void OutdatedDryRun(ChocolateyConfiguration config) { this.Log().Info(@" Would have determined packages that are out of date based on what is installed and what versions are available for upgrade."); } - public virtual void outdated_run(ChocolateyConfiguration config) + public virtual void Outdated(ChocolateyConfiguration config) { - if (!config.SourceType.is_equal_to(SourceTypes.NORMAL)) + if (!config.SourceType.IsEqualTo(SourceTypes.Normal)) { this.Log().Warn(ChocolateyLoggers.Important, "This source doesn't provide a facility for outdated."); return; @@ -650,26 +767,26 @@ Output is package name | current version | available version | pinned? var output = config.RegularOutput; config.RegularOutput = false; - var outdatedPackages = _nugetService.get_outdated(config); + var outdatedPackages = _nugetService.GetOutdated(config); config.RegularOutput = output; var outdatedPackageCount = outdatedPackages.Count(p => p.Value.Success && !p.Value.Inconclusive); if (config.RegularOutput) { var upgradeWarnings = outdatedPackages.Count(p => p.Value.Warning); - this.Log().Warn(() => @"{0}{1} has determined {2} package(s) are outdated. {3}".format_with( + this.Log().Warn(() => @"{0}{1} has determined {2} package(s) are outdated. {3}".FormatWith( Environment.NewLine, ApplicationParameters.Name, outdatedPackageCount, - upgradeWarnings == 0 ? string.Empty : "{0} {1} package(s) had warnings.".format_with(Environment.NewLine, upgradeWarnings) + upgradeWarnings == 0 ? string.Empty : "{0} {1} package(s) had warnings.".FormatWith(Environment.NewLine, upgradeWarnings) )); if (upgradeWarnings != 0) { this.Log().Warn(ChocolateyLoggers.Important, "Warnings:"); - foreach (var warning in outdatedPackages.Where(p => p.Value.Warning).or_empty_list_if_null()) + foreach (var warning in outdatedPackages.Where(p => p.Value.Warning).OrEmpty()) { - this.Log().Warn(ChocolateyLoggers.Important, " - {0}".format_with(warning.Value.Name)); + this.Log().Warn(ChocolateyLoggers.Important, " - {0}".FormatWith(warning.Value.Name)); } } } @@ -680,17 +797,17 @@ Output is package name | current version | available version | pinned? Environment.ExitCode = 2; } - randomly_notify_about_pro_business(config); + RandomlyNotifyAboutLicensedFeatures(config); } - private IEnumerable set_config_from_package_names_and_packages_config(ChocolateyConfiguration config, ConcurrentDictionary packageInstalls) + private IEnumerable GetConfigFromInputAndPackageConfigInput(ChocolateyConfiguration config, ConcurrentDictionary packageInstalls, IEnumerable alternativeSourceRunners) { // if there are any .config files, split those off of the config. Then return the config without those package names. - foreach (var packageConfigFile in config.PackageNames.Split(new[] { ApplicationParameters.PackageNamesSeparator }, StringSplitOptions.RemoveEmptyEntries).or_empty_list_if_null().Where(p => p.EndsWith(".config")).ToList()) + foreach (var packageConfigFile in config.PackageNames.Split(new[] { ApplicationParameters.PackageNamesSeparator }, StringSplitOptions.RemoveEmptyEntries).OrEmpty().Where(p => p.EndsWith(".config")).ToList()) { config.PackageNames = config.PackageNames.Replace(packageConfigFile, string.Empty); - foreach (var packageConfig in get_packages_from_config(packageConfigFile, config, packageInstalls).or_empty_list_if_null()) + foreach (var packageConfig in GetPackagesFromConfigFile(packageConfigFile, config, packageInstalls, alternativeSourceRunners).OrEmpty()) { yield return packageConfig; } @@ -699,23 +816,18 @@ private IEnumerable set_config_from_package_names_and_p yield return config; } - private bool contains_packages_config_file(string packageNames) - { - return packageNames.to_string().Split(new[] { ApplicationParameters.PackageNamesSeparator }, StringSplitOptions.RemoveEmptyEntries).or_empty_list_if_null().Any(p => p.EndsWith(".config", StringComparison.OrdinalIgnoreCase)); - } - - private bool is_packages_config_file(string packageNames) + private bool IsPackagesConfigFile(string packageNames) { - return packageNames.to_string().EndsWith(".config", StringComparison.OrdinalIgnoreCase) && !packageNames.to_string().contains(";"); + return packageNames.ToStringSafe().EndsWith(".config", StringComparison.OrdinalIgnoreCase) && !packageNames.ToStringSafe().ContainsSafe(";"); } - private IEnumerable get_packages_from_config(string packageConfigFile, ChocolateyConfiguration config, ConcurrentDictionary packageInstalls) + private IEnumerable GetPackagesFromConfigFile(string packageConfigFile, ChocolateyConfiguration config, ConcurrentDictionary packageInstalls, IEnumerable alternativeSourceRunners) { IList packageConfigs = new List(); - if (!_fileSystem.file_exists(_fileSystem.get_full_path(packageConfigFile))) + if (!_fileSystem.FileExists(_fileSystem.GetFullPath(packageConfigFile))) { - var logMessage = "'{0}' could not be found in the location specified.".format_with(packageConfigFile); + var logMessage = "'{0}' could not be found in the location specified.".FormatWith(packageConfigFile); this.Log().Error(ChocolateyLoggers.Important, logMessage); var results = packageInstalls.GetOrAdd(packageConfigFile, new PackageResult(packageConfigFile, null, null)); results.Messages.Add(new ResultMessage(ResultType.Error, logMessage)); @@ -723,13 +835,13 @@ private IEnumerable get_packages_from_config(string pac return packageConfigs; } - var settings = _xmlService.deserialize(_fileSystem.get_full_path(packageConfigFile)); + var settings = _xmlService.Deserialize(_fileSystem.GetFullPath(packageConfigFile)); this.Log().Info(@"Installing the following packages:"); - foreach (var pkgSettings in settings.Packages.or_empty_list_if_null()) + foreach (var pkgSettings in settings.Packages.OrEmpty()) { if (!pkgSettings.Disabled) { - var packageConfig = config.deep_copy(); + var packageConfig = config.DeepCopy(); packageConfig.PackageNames = pkgSettings.Id; packageConfig.Sources = string.IsNullOrWhiteSpace(pkgSettings.Source) ? packageConfig.Sources : pkgSettings.Source; packageConfig.Version = pkgSettings.Version; @@ -740,7 +852,7 @@ private IEnumerable get_packages_from_config(string pac if (pkgSettings.ApplyInstallArgumentsToDependencies) packageConfig.ApplyInstallArgumentsToDependencies = true; if (pkgSettings.ApplyPackageParametersToDependencies) packageConfig.ApplyPackageParametersToDependencies = true; - if (!string.IsNullOrWhiteSpace(pkgSettings.Source) && has_source_type(pkgSettings.Source)) + if (!string.IsNullOrWhiteSpace(pkgSettings.Source) && HasSourceType(pkgSettings.Source, alternativeSourceRunners)) { packageConfig.SourceType = pkgSettings.Source; } @@ -788,40 +900,49 @@ private IEnumerable get_packages_from_config(string pac if (pkgSettings.UseSystemPowershell) packageConfig.Features.UsePowerShellHost = false; if (pkgSettings.NoProgress) packageConfig.Features.ShowDownloadProgress = false; - this.Log().Info(ChocolateyLoggers.Important, @"{0}".format_with(packageConfig.PackageNames)); + this.Log().Info(ChocolateyLoggers.Important, @"{0}".FormatWith(packageConfig.PackageNames)); packageConfigs.Add(packageConfig); - this.Log().Debug(() => "Package Configuration Start:{0}{1}{0}Package Configuration End".format_with(System.Environment.NewLine, packageConfig.ToString())); + this.Log().Debug(() => "Package Configuration Start:{0}{1}{0}Package Configuration End".FormatWith(System.Environment.NewLine, packageConfig.ToString())); } } return packageConfigs; } - public void upgrade_noop(ChocolateyConfiguration config) + public void UpgradeDryRun(ChocolateyConfiguration config) { - validate_package_names(config); + ValidatePackageNames(config); + + var upgradeSourceRunners = _containerResolver.ResolveAll(); + + config.Noop = true; - Action action = null; - if (config.SourceType.is_equal_to(SourceTypes.NORMAL)) + ConcurrentDictionary noopUpgrades; + + if (config.SourceType.IsEqualTo(SourceTypes.Normal)) + { + Action action = (pkg, configuration) => _powershellService.InstallDryRun(pkg); + noopUpgrades = _nugetService.UpgradeDryRun(config, action); + } + else { - action = (pkg, configuration) => _powershellService.install_noop(pkg); + noopUpgrades = PerformSourceRunnerFunction(config, runner => runner.UpgradeDryRun(config, null), upgradeSourceRunners); } - var noopUpgrades = perform_source_runner_function(config, r => r.upgrade_noop(config, action)); if (config.RegularOutput) { - var noopFailures = report_action_summary(noopUpgrades, "can upgrade"); + var noopFailures = ReportActionSummary(noopUpgrades, "can upgrade"); } - randomly_notify_about_pro_business(config); + RandomlyNotifyAboutLicensedFeatures(config); } - public virtual ConcurrentDictionary upgrade_run(ChocolateyConfiguration config) + public virtual ConcurrentDictionary Upgrade(ChocolateyConfiguration config) { - validate_package_names(config); + ValidatePackageNames(config); this.Log().Info(@"Upgrading the following packages:"); - this.Log().Info(ChocolateyLoggers.Important, @"{0}".format_with(config.PackageNames)); + this.Log().Info(ChocolateyLoggers.Important, @"{0}".FormatWith(config.PackageNames)); if (string.IsNullOrWhiteSpace(config.Sources)) { @@ -833,7 +954,7 @@ public virtual ConcurrentDictionary upgrade_run(Chocolate this.Log().Info(@"By upgrading, you accept licenses for the packages."); - foreach (var packageConfigFile in config.PackageNames.Split(new[] { ApplicationParameters.PackageNamesSeparator }, StringSplitOptions.RemoveEmptyEntries).or_empty_list_if_null().Where(p => p.EndsWith(".config")).ToList()) + foreach (var packageConfigFile in config.PackageNames.Split(new[] { ApplicationParameters.PackageNamesSeparator }, StringSplitOptions.RemoveEmptyEntries).OrEmpty().Where(p => p.EndsWith(".config")).ToList()) { throw new ApplicationException("A packages.config file is only used with installs."); } @@ -842,16 +963,26 @@ public virtual ConcurrentDictionary upgrade_run(Chocolate try { - Action action = null; - if (config.SourceType.is_equal_to(SourceTypes.NORMAL)) + GetInitialEnvironment(config, allowLogging: true); + + ConcurrentDictionary results; + + if (config.SourceType.IsEqualTo(SourceTypes.Normal)) { - action = (packageResult, configuration) => handle_package_result(packageResult, configuration, CommandNameType.upgrade); - } + var action = new Action((packageResult, configuration) => HandlePackageResult(packageResult, configuration, CommandNameType.Upgrade)); + var beforeUpgradeAction = new Action((packageResult, configuration) => BeforeModifyAction(packageResult, configuration)); - get_environment_before(config, allowLogging: true); + results = _nugetService.Upgrade(config, action, beforeUpgradeAction); + } + else + { + results = PerformSourceRunnerFunction>(config, runner => runner.Upgrade(config, null)); + } - var beforeUpgradeAction = new Action((packageResult, configuration) => before_package_modify(packageResult, configuration)); - var results = perform_source_runner_function(config, r => r.upgrade_run(config, action, beforeUpgradeAction)); + if (results is null) + { + throw new NotSupportedException("The '{0}' source does not support upgrading packages".FormatWith(config.SourceType)); + } foreach (var result in results) { @@ -860,23 +991,23 @@ public virtual ConcurrentDictionary upgrade_run(Chocolate } finally { - var upgradeFailures = report_action_summary(packageUpgrades, "upgraded"); + var upgradeFailures = ReportActionSummary(packageUpgrades, "upgraded"); if (upgradeFailures != 0 && Environment.ExitCode == 0) { Environment.ExitCode = 1; } - randomly_notify_about_pro_business(config); + RandomlyNotifyAboutLicensedFeatures(config); } return packageUpgrades; } - private void before_package_modify(PackageResult packageResult, ChocolateyConfiguration config) + private void BeforeModifyAction(PackageResult packageResult, ChocolateyConfiguration config) { if (!config.SkipPackageInstallProvider && config.Information.PlatformType == PlatformType.Windows) { - _powershellService.before_modify(config, packageResult); + _powershellService.BeforeModify(config, packageResult); } else { @@ -884,28 +1015,35 @@ private void before_package_modify(PackageResult packageResult, ChocolateyConfig } } - public void uninstall_noop(ChocolateyConfiguration config) + public void UninstallDryRun(ChocolateyConfiguration config) { - Action action = null; - if (config.SourceType.is_equal_to(SourceTypes.NORMAL)) + var uninstallSourceRunners = _containerResolver.ResolveAll(); + + config.Noop = true; + + if (config.SourceType.IsEqualTo(SourceTypes.Normal)) { - action = (pkg, configuration) => + Action action = (pkg, configuration) => { - _powershellService.before_modify_noop(pkg); - _powershellService.uninstall_noop(pkg); + _powershellService.BeforeModifyDryRun(pkg); + _powershellService.UninstallDryRun(pkg); }; + _nugetService.UninstallDryRun(config, action); + } + else + { + PerformSourceRunnerAction(config, runner => runner.UninstallDryRun(config, null), uninstallSourceRunners); } - perform_source_runner_action(config, r => r.uninstall_noop(config, action)); - randomly_notify_about_pro_business(config); + RandomlyNotifyAboutLicensedFeatures(config); } - public virtual ConcurrentDictionary uninstall_run(ChocolateyConfiguration config) + public virtual ConcurrentDictionary Uninstall(ChocolateyConfiguration config) { this.Log().Info(@"Uninstalling the following packages:"); - this.Log().Info(ChocolateyLoggers.Important, @"{0}".format_with(config.PackageNames)); + this.Log().Info(ChocolateyLoggers.Important, @"{0}".FormatWith(config.PackageNames)); - if (config.PackageNames.Split(new[] { ApplicationParameters.PackageNamesSeparator }, StringSplitOptions.RemoveEmptyEntries).or_empty_list_if_null().Any(p => p.EndsWith(".config"))) + if (config.PackageNames.Split(new[] { ApplicationParameters.PackageNamesSeparator }, StringSplitOptions.RemoveEmptyEntries).OrEmpty().Any(p => p.EndsWith(".config"))) { throw new ApplicationException("A packages.config file is only used with installs."); } @@ -914,15 +1052,26 @@ public virtual ConcurrentDictionary uninstall_run(Chocola try { - Action action = null; - if (config.SourceType.is_equal_to(SourceTypes.NORMAL)) + var environmentBefore = GetInitialEnvironment(config); + + ConcurrentDictionary results; + + if (config.SourceType.IsEqualTo(SourceTypes.Normal)) + { + var action = new Action(HandlePackageUninstall); + var beforeUninstallAction = new Action(BeforeModifyAction); + + results = _nugetService.Uninstall(config, action, beforeUninstallAction); + } + else { - action = handle_package_uninstall; + results = PerformSourceRunnerFunction>(config, runner => runner.Uninstall(config, null)); } - var environmentBefore = get_environment_before(config); - var beforeUninstallAction = new Action(before_package_modify); - var results = perform_source_runner_function(config, r => r.uninstall_run(config, action, beforeUninstallAction)); + if (results is null) + { + throw new NotSupportedException("The '{0}' source does not support uninstalling packages".FormatWith(config.SourceType)); + } foreach (var result in results) { @@ -932,11 +1081,11 @@ public virtual ConcurrentDictionary uninstall_run(Chocola // not handled in the uninstall handler IEnumerable environmentChanges; IEnumerable environmentRemovals; - get_log_environment_changes(config, environmentBefore, out environmentChanges, out environmentRemovals); + LogEnvironmentChanges(config, environmentBefore, out environmentChanges, out environmentRemovals); } finally { - var uninstallFailures = report_action_summary(packageUninstalls, "uninstalled"); + var uninstallFailures = ReportActionSummary(packageUninstalls, "uninstalled"); if (uninstallFailures != 0 && Environment.ExitCode == 0) { Environment.ExitCode = 1; @@ -962,13 +1111,13 @@ this option only as a last resort. "); } - randomly_notify_about_pro_business(config); + RandomlyNotifyAboutLicensedFeatures(config); } return packageUninstalls; } - private void validate_package_names(ChocolateyConfiguration config) + private void ValidatePackageNames(ChocolateyConfiguration config) { foreach (var packageName in config.PackageNames.Split(';')) { @@ -976,18 +1125,18 @@ private void validate_package_names(ChocolateyConfiguration config) { if (Uri.TryCreate(packageName, UriKind.Absolute, out var uri) && (uri.IsFile || uri.IsUnc)) { - throw_invalid_path_used(uri.LocalPath, uri.IsUnc, config.CommandName); + ThrowInvalidPathError(uri.LocalPath, uri.IsUnc, config.CommandName); } - else if (_fileSystem.file_exists(packageName)) + else if (_fileSystem.FileExists(packageName)) { - var fullPath = _fileSystem.get_full_path(packageName); + var fullPath = _fileSystem.GetFullPath(packageName); if (!string.IsNullOrWhiteSpace(fullPath) && Uri.TryCreate(fullPath, UriKind.Absolute, out uri)) { - throw_invalid_path_used(uri.LocalPath, uri.IsUnc, config.CommandName); + ThrowInvalidPathError(uri.LocalPath, uri.IsUnc, config.CommandName); } - throw_invalid_path_used(fullPath, isUncPath: false, commandName: config.CommandName); + ThrowInvalidPathError(fullPath, isUncPath: false, commandName: config.CommandName); } else { @@ -1003,7 +1152,7 @@ private void validate_package_names(ChocolateyConfiguration config) } } - private void throw_invalid_path_used(string packageName, bool isUncPath, string commandName) + private void ThrowInvalidPathError(string packageName, bool isUncPath, string commandName) { var sb = new StringBuilder("Package name cannot be a path to a file "); @@ -1012,7 +1161,7 @@ private void throw_invalid_path_used(string packageName, bool isUncPath, string sb.AppendLine("on a UNC location.") .AppendLine() .Append("To ") - .Append(commandName) + .Append(commandName.ToLowerSafe()) .AppendLine(" a file in a UNC location, you may use:"); } else @@ -1020,23 +1169,23 @@ private void throw_invalid_path_used(string packageName, bool isUncPath, string sb.AppendLine("on a remote, or local file system.") .AppendLine() .Append("To ") - .Append(commandName) + .Append(commandName.ToLowerSafe()) .AppendLine(" a local, or remote file, you may use:"); } - build_install_example(packageName, sb, commandName); + BuildInstallExample(packageName, sb, commandName.ToLowerSafe()); throw new ApplicationException(sb.AppendLine().ToString()); } - private void build_install_example(string packageName, StringBuilder sb, string commandName) + private void BuildInstallExample(string packageName, StringBuilder sb, string commandName) { - var fileName = _fileSystem.get_file_name_without_extension(packageName); + var fileName = _fileSystem.GetFilenameWithoutExtension(packageName); var version = string.Empty; // We need to get the directory name in this way in case it is a UNC path. // Using normal way to get the directory name may trim out parts of the necessary path. - var length = packageName.Length - _fileSystem.get_file_name(packageName).Length - 1; + var length = packageName.Length - _fileSystem.GetFileName(packageName).Length - 1; var directory = length > 0 ? packageName.Substring(0, length) : string.Empty; if (fileName.Contains('.')) @@ -1048,7 +1197,7 @@ private void build_install_example(string packageName, StringBuilder sb, string { if (NuGetVersion.TryParse(originalFileName.Substring(fileName.Length + 1), out var nugetVersion)) { - version = nugetVersion.to_normalized_string(); + version = nugetVersion.ToNormalizedStringChecked(); break; } @@ -1072,7 +1221,7 @@ private void build_install_example(string packageName, StringBuilder sb, string sb.Append(" choco ") .Append(commandName) .Append(' ') - .Append(fileName.wrap_spaces_in_quotes()); + .Append(fileName.QuoteIfContainsSpaces()); if (!string.IsNullOrWhiteSpace(version)) { @@ -1090,31 +1239,31 @@ private void build_install_example(string packageName, StringBuilder sb, string } } - private int report_action_summary(ConcurrentDictionary packageResults, string actionName) + private int ReportActionSummary(ConcurrentDictionary packageResults, string actionName) { - var successes = packageResults.or_empty_list_if_null().Where(p => p.Value.Success && !p.Value.Inconclusive); + var successes = packageResults.OrEmpty().Where(p => p.Value.Success && !p.Value.Inconclusive).OrderBy(p => p.Value.Name); var failures = packageResults.Count(p => !p.Value.Success); var warnings = packageResults.Count(p => p.Value.Warning); var rebootPackages = packageResults.Count(p => new[] { 1641, 3010 }.Contains(p.Value.ExitCode)); this.Log().Warn( - () => @"{0}{1} {2} {3}/{4} packages. {5}{0} See the log for details ({6}).".format_with( + () => @"{0}{1} {2} {3}/{4} packages. {5}{0} See the log for details ({6}).".FormatWith( Environment.NewLine, ApplicationParameters.Name, actionName, successes.Count(), packageResults.Count, (failures > 0) ? failures + " packages failed." : string.Empty, - _fileSystem.combine_paths(ApplicationParameters.LoggingLocation, ApplicationParameters.LoggingFile) + _fileSystem.CombinePaths(ApplicationParameters.LoggingLocation, ApplicationParameters.LoggingFile) )); // summarize results when more than 5 if (packageResults.Count >= 5 && successes.Count() != 0) { this.Log().Info(""); - this.Log().Warn("{0}{1}:".format_with(actionName.Substring(0, 1).ToUpper(), actionName.Substring(1))); - foreach (var packageResult in successes.or_empty_list_if_null()) + this.Log().Warn("{0}{1}:".FormatWith(actionName.Substring(0, 1).ToUpper(), actionName.Substring(1))); + foreach (var packageResult in successes.OrEmpty()) { - this.Log().Info(" - {0} v{1}".format_with(packageResult.Value.Name, packageResult.Value.Version)); + this.Log().Info(" - {0} v{1}".FormatWith(packageResult.Value.Name, packageResult.Value.Version)); } } @@ -1122,10 +1271,10 @@ private int report_action_summary(ConcurrentDictionary pa { this.Log().Info(""); this.Log().Warn("Warnings:"); - foreach (var warning in packageResults.Where(p => p.Value.Warning).or_empty_list_if_null()) + foreach (var warning in packageResults.Where(p => p.Value.Warning).OrderBy(p => p.Value.Name).OrEmpty()) { var warningMessage = warning.Value.Messages.FirstOrDefault(m => m.MessageType == ResultType.Warn); - this.Log().Warn(" - {0}{1}".format_with(warning.Value.Name, warningMessage != null ? " - {0}".format_with(warningMessage.Message) : string.Empty)); + this.Log().Warn(" - {0}{1}".FormatWith(warning.Value.Name, warningMessage != null ? " - {0}".FormatWith(warningMessage.Message) : string.Empty)); } } @@ -1133,9 +1282,9 @@ private int report_action_summary(ConcurrentDictionary pa { this.Log().Info(""); this.Log().Warn("Packages requiring reboot:"); - foreach (var reboot in packageResults.Where(p => new[] { 1641, 3010 }.Contains(p.Value.ExitCode)).or_empty_list_if_null()) + foreach (var reboot in packageResults.Where(p => new[] { 1641, 3010 }.Contains(p.Value.ExitCode)).OrderBy(p => p.Value.Name).OrEmpty()) { - this.Log().Warn(" - {0}{1}".format_with(reboot.Value.Name, reboot.Value.ExitCode != 0 ? " (exit code {0})".format_with(reboot.Value.ExitCode) : string.Empty)); + this.Log().Warn(" - {0}{1}".FormatWith(reboot.Value.Name, reboot.Value.ExitCode != 0 ? " (exit code {0})".FormatWith(reboot.Value.ExitCode) : string.Empty)); } this.Log().Warn(ChocolateyLoggers.Important, @" The recent package changes indicate a reboot is necessary. @@ -1146,14 +1295,14 @@ The recent package changes indicate a reboot is necessary. { this.Log().Info(""); this.Log().Error("Failures"); - foreach (var failure in packageResults.Where(p => !p.Value.Success).or_empty_list_if_null()) + foreach (var failure in packageResults.Where(p => !p.Value.Success).OrderBy(p => p.Value.Name).OrEmpty()) { var errorMessage = failure.Value.Messages.FirstOrDefault(m => m.MessageType == ResultType.Error); this.Log().Error( - " - {0}{1}{2}".format_with( + " - {0}{1}{2}".FormatWith( failure.Value.Name, - failure.Value.ExitCode != 0 ? " (exited {0})".format_with(failure.Value.ExitCode) : string.Empty, - errorMessage != null ? " - {0}".format_with(errorMessage.Message) : string.Empty + failure.Value.ExitCode != 0 ? " (exited {0})".FormatWith(failure.Value.ExitCode) : string.Empty, + errorMessage != null ? " - {0}".FormatWith(errorMessage.Message) : string.Empty )); } } @@ -1161,30 +1310,30 @@ The recent package changes indicate a reboot is necessary. return failures; } - public virtual void handle_package_uninstall(PackageResult packageResult, ChocolateyConfiguration config) + public virtual void HandlePackageUninstall(PackageResult packageResult, ChocolateyConfiguration config) { - if (!_fileSystem.directory_exists(packageResult.InstallLocation)) + if (!_fileSystem.DirectoryExists(packageResult.InstallLocation)) { - packageResult.InstallLocation += ".{0}".format_with(packageResult.PackageMetadata.Version.to_string()); + packageResult.InstallLocation += ".{0}".FormatWith(packageResult.PackageMetadata.Version.ToStringSafe()); } //These items only apply to windows systems. if (config.Information.PlatformType == PlatformType.Windows) { - _shimgenService.uninstall(config, packageResult); + _shimgenService.Uninstall(config, packageResult); if (!config.SkipPackageInstallProvider) { - _powershellService.uninstall(config, packageResult); + _powershellService.Uninstall(config, packageResult); } if (packageResult.Success) { - _autoUninstallerService.run(packageResult, config); + _autoUninstallerService.Run(packageResult, config); } // we don't care about the exit code - CommandExecutor.execute_static(_shutdownExe, "/a", config.CommandExecutionTimeoutSeconds, _fileSystem.get_current_directory(), (s, e) => { }, (s, e) => { }, false, false); + CommandExecutor.ExecuteStatic(_shutdownExe, "/a", config.CommandExecutionTimeoutSeconds, _fileSystem.GetCurrentDirectory(), (s, e) => { }, (s, e) => { }, false, false); } else { @@ -1194,12 +1343,14 @@ public virtual void handle_package_uninstall(PackageResult packageResult, Chocol if (packageResult.Success) { //todo: #2568 v2 clean up package information store for things no longer installed (call it compact?) - uninstall_cleanup(config, packageResult); + UninstallCleanup(config, packageResult); } else { - this.Log().Error(ChocolateyLoggers.Important, "{0} {1} not successful.".format_with(packageResult.Name, "uninstall")); - handle_unsuccessful_operation(config, packageResult, movePackageToFailureLocation: false, attemptRollback: false); + var oldPrompt = config.PromptForConfirmation; + + this.Log().Error(ChocolateyLoggers.Important, "{0} {1} not successful.".FormatWith(packageResult.Name, "uninstall")); + HandleFailedOperation(config, packageResult, movePackageToFailureLocation: true, attemptRollback: true); } if (_rebootExitCodes.Contains(packageResult.ExitCode)) @@ -1208,7 +1359,7 @@ public virtual void handle_package_uninstall(PackageResult packageResult, Chocol { Environment.ExitCode = ApplicationParameters.ExitCodes.ErrorInstallSuspend; this.Log().Warn(ChocolateyLoggers.Important, @"Chocolatey has detected a pending reboot after uninstalling -package '{0}' - stopping further execution".format_with(packageResult.Name)); +package '{0}' - stopping further execution".FormatWith(packageResult.Name)); throw new ApplicationException("Reboot required before continuing. Reboot and run the same command again."); } @@ -1217,71 +1368,72 @@ public virtual void handle_package_uninstall(PackageResult packageResult, Chocol if (!packageResult.Success) { // throw an error so that NuGet Service doesn't attempt to continue with package removal - throw new ApplicationException("{0} {1} not successful.".format_with(packageResult.Name, "uninstall")); + throw new ApplicationException("{0} {1} not successful.".FormatWith(packageResult.Name, "uninstall")); } } - private void uninstall_cleanup(ChocolateyConfiguration config, PackageResult packageResult) + private void UninstallCleanup(ChocolateyConfiguration config, PackageResult packageResult) { - if (config.Features.RemovePackageInformationOnUninstall) _packageInfoService.remove_package_information(packageResult.PackageMetadata); + if (config.Features.RemovePackageInformationOnUninstall) _packageInfoService.Remove(packageResult.PackageMetadata); - ensure_bad_package_path_is_clean(config, packageResult); - remove_rollback_if_exists(packageResult); - handle_extension_packages(config, packageResult); - handle_template_packages(config, packageResult); - handle_hook_packages(config, packageResult); + EnsureBadPackagesPathIsClean(config, packageResult); + RemoveBackupIfExists(packageResult); + HandleExtensionPackages(config, packageResult); + HandleTemplatePackages(config, packageResult); + HandleHookPackages(config, packageResult); if (config.Force) { var packageDirectory = packageResult.InstallLocation; - if (string.IsNullOrWhiteSpace(packageDirectory) || !_fileSystem.directory_exists(packageDirectory)) return; + if (string.IsNullOrWhiteSpace(packageDirectory) || !_fileSystem.DirectoryExists(packageDirectory)) return; - if (packageDirectory.is_equal_to(ApplicationParameters.InstallLocation) || packageDirectory.is_equal_to(ApplicationParameters.PackagesLocation)) + if (packageDirectory.IsEqualTo(ApplicationParameters.InstallLocation) || packageDirectory.IsEqualTo(ApplicationParameters.PackagesLocation)) { packageResult.Messages.Add( new ResultMessage( ResultType.Error, - "Install location is not specific enough, cannot force remove directory:{0} Erroneous install location captured as '{1}'".format_with(Environment.NewLine, packageResult.InstallLocation) + "Install location is not specific enough, cannot force remove directory:{0} Erroneous install location captured as '{1}'".FormatWith(Environment.NewLine, packageResult.InstallLocation) ) ); return; } - FaultTolerance.try_catch_with_logging_exception( - () => _fileSystem.delete_directory_if_exists(packageDirectory, recursive: true), - "Attempted to remove '{0}' but had an error".format_with(packageDirectory), + FaultTolerance.TryCatchWithLoggingException( + () => _fileSystem.DeleteDirectoryChecked(packageDirectory, recursive: true), + "Attempted to remove '{0}' but had an error".FormatWith(packageDirectory), logWarningInsteadOfError: true); } } - private void handle_extension_packages(ChocolateyConfiguration config, PackageResult packageResult) + // This should probably be split into install(/upgrade)/uninstall methods with shared logic placed in helper method(s). + private void HandleExtensionPackages(ChocolateyConfiguration config, PackageResult packageResult) { if (packageResult == null) return; - if (!packageResult.Name.to_lower().EndsWith(".extension") && !packageResult.Name.to_lower().EndsWith(".extensions")) return; + if (!packageResult.Name.ToLowerSafe().EndsWith(".extension") && !packageResult.Name.ToLowerSafe().EndsWith(".extensions")) return; - _fileSystem.create_directory_if_not_exists(ApplicationParameters.ExtensionsLocation); - var extensionsFolderName = packageResult.Name.to_lower().Replace(".extensions", string.Empty).Replace(".extension", string.Empty); - var packageExtensionsInstallDirectory = _fileSystem.combine_paths(ApplicationParameters.ExtensionsLocation, extensionsFolderName); + _fileSystem.EnsureDirectoryExists(ApplicationParameters.ExtensionsLocation); + var extensionsFolderName = packageResult.Name.ToLowerSafe().Replace(".extensions", string.Empty).Replace(".extension", string.Empty); + var packageExtensionsInstallDirectory = _fileSystem.CombinePaths(ApplicationParameters.ExtensionsLocation, extensionsFolderName); - remove_extension_folder(packageExtensionsInstallDirectory); + RemoveExtensionFolder(packageExtensionsInstallDirectory); // don't name your package *.extension.extension - remove_extension_folder(packageExtensionsInstallDirectory + ".extension"); - remove_extension_folder(packageExtensionsInstallDirectory + ".extensions"); + RemoveExtensionFolder(packageExtensionsInstallDirectory + ".extension"); + RemoveExtensionFolder(packageExtensionsInstallDirectory + ".extensions"); - if (!config.CommandName.is_equal_to(CommandNameType.uninstall.to_string())) + if (!config.CommandName.IsEqualTo(CommandNameType.Uninstall.ToStringSafe())) { if (packageResult.InstallLocation == null) return; - _fileSystem.create_directory_if_not_exists(packageExtensionsInstallDirectory); - var extensionsFolder = _fileSystem.combine_paths(packageResult.InstallLocation, "extensions"); - var extensionFolderToCopy = _fileSystem.directory_exists(extensionsFolder) ? extensionsFolder : packageResult.InstallLocation; + _fileSystem.EnsureDirectoryExists(packageExtensionsInstallDirectory); + var extensionsFolder = _fileSystem.CombinePaths(packageResult.InstallLocation, "extensions"); + var extensionFolderToCopy = _fileSystem.DirectoryExists(extensionsFolder) ? extensionsFolder : packageResult.InstallLocation; - FaultTolerance.try_catch_with_logging_exception( - () => _fileSystem.copy_directory(extensionFolderToCopy, packageExtensionsInstallDirectory, overwriteExisting: true), - "Attempted to copy{0} '{1}'{0} to '{2}'{0} but had an error".format_with(Environment.NewLine, extensionFolderToCopy, packageExtensionsInstallDirectory)); + FaultTolerance.TryCatchWithLoggingException( + () => _fileSystem.CopyDirectory(extensionFolderToCopy, packageExtensionsInstallDirectory, overwriteExisting: true), + "Attempted to copy{0} '{1}'{0} to '{2}'{0} but had an error".FormatWith(Environment.NewLine, extensionFolderToCopy, packageExtensionsInstallDirectory)); - string logMessage = " Installed/updated {0} extensions.".format_with(extensionsFolderName); + string logMessage = " Installed/updated {0} extensions.".FormatWith(extensionsFolderName); this.Log().Warn(logMessage); packageResult.Messages.Add(new ResultMessage(ResultType.Note, logMessage)); @@ -1289,84 +1441,85 @@ private void handle_extension_packages(ChocolateyConfiguration config, PackageRe } else { - string logMessage = " Uninstalled {0} extensions.".format_with(extensionsFolderName); + string logMessage = " Uninstalled {0} extensions.".FormatWith(extensionsFolderName); this.Log().Warn(logMessage); packageResult.Messages.Add(new ResultMessage(ResultType.Note, logMessage)); } } - private void remove_extension_folder(string packageExtensionsDirectory) + private void RemoveExtensionFolder(string packageExtensionsDirectory) { - if (!_fileSystem.directory_exists(packageExtensionsDirectory)) return; + if (!_fileSystem.DirectoryExists(packageExtensionsDirectory)) return; // remove old dll files files - foreach (var oldDllFile in _fileSystem.get_files(packageExtensionsDirectory, "*.dll.old", SearchOption.AllDirectories).or_empty_list_if_null()) + foreach (var oldDllFile in _fileSystem.GetFiles(packageExtensionsDirectory, "*.dll.old", SearchOption.AllDirectories).OrEmpty()) { - FaultTolerance.try_catch_with_logging_exception( - () => _fileSystem.delete_file(oldDllFile), - "Attempted to remove '{0}' but had an error".format_with(oldDllFile), + FaultTolerance.TryCatchWithLoggingException( + () => _fileSystem.DeleteFile(oldDllFile), + "Attempted to remove '{0}' but had an error".FormatWith(oldDllFile), throwError: false, logWarningInsteadOfError: true); } // rename possibly locked dll files - foreach (var dllFile in _fileSystem.get_files(packageExtensionsDirectory, "*.dll", SearchOption.AllDirectories).or_empty_list_if_null()) + foreach (var dllFile in _fileSystem.GetFiles(packageExtensionsDirectory, "*.dll", SearchOption.AllDirectories).OrEmpty()) { - FaultTolerance.try_catch_with_logging_exception( - () => _fileSystem.move_file(dllFile, dllFile + ".old"), - "Attempted to rename '{0}' but had an error".format_with(dllFile)); + FaultTolerance.TryCatchWithLoggingException( + () => _fileSystem.MoveFile(dllFile, dllFile + ".old"), + "Attempted to rename '{0}' but had an error".FormatWith(dllFile)); } - FaultTolerance.try_catch_with_logging_exception( + FaultTolerance.TryCatchWithLoggingException( () => { - foreach (var file in _fileSystem.get_files(packageExtensionsDirectory, "*.*", SearchOption.AllDirectories).or_empty_list_if_null().Where(f => !f.EndsWith(".dll.old"))) + foreach (var file in _fileSystem.GetFiles(packageExtensionsDirectory, "*.*", SearchOption.AllDirectories).OrEmpty().Where(f => !f.EndsWith(".dll.old"))) { - FaultTolerance.try_catch_with_logging_exception( - () => _fileSystem.delete_file(file), - "Attempted to remove '{0}' but had an error".format_with(file), + FaultTolerance.TryCatchWithLoggingException( + () => _fileSystem.DeleteFile(file), + "Attempted to remove '{0}' but had an error".FormatWith(file), throwError: false, logWarningInsteadOfError: true); } }, - "Attempted to remove '{0}' but had an error".format_with(packageExtensionsDirectory), + "Attempted to remove '{0}' but had an error".FormatWith(packageExtensionsDirectory), throwError: false, logWarningInsteadOfError: true); } - private void handle_template_packages(ChocolateyConfiguration config, PackageResult packageResult) + // This should probably be split into install(/upgrade)/uninstall methods with shared logic placed in helper method(s). + private void HandleTemplatePackages(ChocolateyConfiguration config, PackageResult packageResult) { if (packageResult == null) return; - if (!packageResult.Name.to_lower().EndsWith(".template")) return; + if (!packageResult.Name.ToLowerSafe().EndsWith(".template")) return; - _fileSystem.create_directory_if_not_exists(ApplicationParameters.TemplatesLocation); - var templateFolderName = packageResult.Name.to_lower().Replace(".template", string.Empty); - var installTemplatePath = _fileSystem.combine_paths(ApplicationParameters.TemplatesLocation, templateFolderName); + _fileSystem.EnsureDirectoryExists(ApplicationParameters.TemplatesLocation); + var templateFolderName = packageResult.Name.ToLowerSafe().Replace(".template", string.Empty); + var installTemplatePath = _fileSystem.CombinePaths(ApplicationParameters.TemplatesLocation, templateFolderName); - FaultTolerance.try_catch_with_logging_exception( - () => _fileSystem.delete_directory_if_exists(installTemplatePath, recursive: true), - "Attempted to remove '{0}' but had an error".format_with(installTemplatePath)); + FaultTolerance.TryCatchWithLoggingException( + () => _fileSystem.DeleteDirectoryChecked(installTemplatePath, recursive: true), + "Attempted to remove '{0}' but had an error".FormatWith(installTemplatePath)); - if (!config.CommandName.is_equal_to(CommandNameType.uninstall.to_string())) + if (!config.CommandName.IsEqualTo(CommandNameType.Uninstall.ToStringSafe())) { if (packageResult.InstallLocation == null) return; - _fileSystem.create_directory_if_not_exists(installTemplatePath); - var templatesPath = _fileSystem.combine_paths(packageResult.InstallLocation, "templates"); - var templatesFolderToCopy = _fileSystem.directory_exists(templatesPath) ? templatesPath : packageResult.InstallLocation; + _fileSystem.EnsureDirectoryExists(installTemplatePath); + var templatesPath = _fileSystem.CombinePaths(packageResult.InstallLocation, "templates"); + var templatesFolderToCopy = _fileSystem.DirectoryExists(templatesPath) ? templatesPath : packageResult.InstallLocation; - FaultTolerance.try_catch_with_logging_exception( + FaultTolerance.TryCatchWithLoggingException( () => { - _fileSystem.copy_directory(templatesFolderToCopy, installTemplatePath, overwriteExisting: true); - foreach (var nuspecFile in _fileSystem.get_files(installTemplatePath, "*.nuspec.template").or_empty_list_if_null()) + _fileSystem.CopyDirectory(templatesFolderToCopy, installTemplatePath, overwriteExisting: true); + foreach (var nuspecFile in _fileSystem.GetFiles(installTemplatePath, "*.nuspec.template").OrEmpty()) { - _fileSystem.move_file(nuspecFile, nuspecFile.Replace(".nuspec.template", ".nuspec")); + _fileSystem.MoveFile(nuspecFile, nuspecFile.Replace(".nuspec.template", ".nuspec")); } }, - "Attempted to copy{0} '{1}'{0} to '{2}'{0} but had an error".format_with(Environment.NewLine, templatesFolderToCopy, installTemplatePath)); + "Attempted to copy{0} '{1}'{0} to '{2}'{0} but had an error".FormatWith(Environment.NewLine, templatesFolderToCopy, installTemplatePath)); - string logMessage = " Installed/updated {0} template.".format_with(templateFolderName); + string logMessage = " Installed/updated {0} template.".FormatWith(templateFolderName); this.Log().Warn(logMessage); packageResult.Messages.Add(new ResultMessage(ResultType.Note, logMessage)); @@ -1374,29 +1527,29 @@ private void handle_template_packages(ChocolateyConfiguration config, PackageRes } else { - string logMessage = " Uninstalled {0} template.".format_with(templateFolderName); + string logMessage = " Uninstalled {0} template.".FormatWith(templateFolderName); this.Log().Warn(logMessage); packageResult.Messages.Add(new ResultMessage(ResultType.Note, logMessage)); } } - private void ensure_bad_package_path_is_clean(ChocolateyConfiguration config, PackageResult packageResult) + private void EnsureBadPackagesPathIsClean(ChocolateyConfiguration config, PackageResult packageResult) { if (packageResult.InstallLocation == null) return; - FaultTolerance.try_catch_with_logging_exception( + FaultTolerance.TryCatchWithLoggingException( () => { string badPackageInstallPath = packageResult.InstallLocation.Replace(ApplicationParameters.PackagesLocation, ApplicationParameters.PackageFailuresLocation); - if (_fileSystem.directory_exists(badPackageInstallPath)) + if (_fileSystem.DirectoryExists(badPackageInstallPath)) { - _fileSystem.delete_directory(badPackageInstallPath, recursive: true); + _fileSystem.DeleteDirectory(badPackageInstallPath, recursive: true); } }, "Attempted to delete bad package install path if existing. Had an error"); } - private void handle_unsuccessful_operation(ChocolateyConfiguration config, PackageResult packageResult, bool movePackageToFailureLocation, bool attemptRollback) + private void HandleFailedOperation(ChocolateyConfiguration config, PackageResult packageResult, bool movePackageToFailureLocation, bool attemptRollback) { if (Environment.ExitCode == 0) Environment.ExitCode = 1; @@ -1408,7 +1561,7 @@ private void handle_unsuccessful_operation(ChocolateyConfiguration config, Packa if (attemptRollback || movePackageToFailureLocation) { var packageDirectory = packageResult.InstallLocation; - if (packageDirectory.is_equal_to(ApplicationParameters.InstallLocation) || packageDirectory.is_equal_to(ApplicationParameters.PackagesLocation)) + if (packageDirectory.IsEqualTo(ApplicationParameters.InstallLocation) || packageDirectory.IsEqualTo(ApplicationParameters.PackagesLocation)) { this.Log().Error(ChocolateyLoggers.Important, @" Package location is not specific enough, cannot move bad package or @@ -1418,53 +1571,67 @@ rollback the previous version. Erroneous install location captured as ATTENTION: You must take manual action to remove {1} from {2}. It will show incorrectly as installed until you do. To remove, you can simply delete the folder in question. -".format_with(packageResult.InstallLocation, packageResult.Name, ApplicationParameters.PackagesLocation)); +".FormatWith(packageResult.InstallLocation, packageResult.Name, ApplicationParameters.PackagesLocation)); } else { - if (movePackageToFailureLocation) move_bad_package_to_failure_location(packageResult); + if (movePackageToFailureLocation) MovePackageToFailedPackagesLocation(packageResult); - if (attemptRollback) rollback_previous_version(config, packageResult); + if (attemptRollback) RestorePreviousPackageVersion(config, packageResult); } } } - private bool has_source_type(string source) + private bool HasSourceType(string sourceType, IEnumerable alternativeSourceRunners) { - return _sourceRunners.Any(s => s.SourceType == source || s.SourceType == source + "s"); + return alternativeSourceRunners.Any(s => s.SourceType == sourceType || s.SourceType == sourceType + "s"); } - private void move_bad_package_to_failure_location(PackageResult packageResult) + private void MovePackageToFailedPackagesLocation(PackageResult packageResult) { - _fileSystem.create_directory_if_not_exists(ApplicationParameters.PackageFailuresLocation); + _fileSystem.EnsureDirectoryExists(ApplicationParameters.PackageFailuresLocation); - if (!string.IsNullOrWhiteSpace(packageResult.InstallLocation) && _fileSystem.directory_exists(packageResult.InstallLocation)) + if (!string.IsNullOrWhiteSpace(packageResult.InstallLocation) && _fileSystem.DirectoryExists(packageResult.InstallLocation)) { - FaultTolerance.try_catch_with_logging_exception( - () => _fileSystem.move_directory(packageResult.InstallLocation, packageResult.InstallLocation.Replace(ApplicationParameters.PackagesLocation, ApplicationParameters.PackageFailuresLocation)), - "Could not move the bad package to the failure directory. It will show as installed.{0} {1}{0} The error".format_with(Environment.NewLine, packageResult.InstallLocation)); + var normalizedVersion = new NuGetVersion(packageResult.Version).ToNormalizedStringChecked(); + var failuresFolder = _fileSystem.CombinePaths(ApplicationParameters.PackageFailuresLocation, packageResult.Name, normalizedVersion); + + if (_filesService.MovePackageUsingBackupStrategy(packageResult.InstallLocation, failuresFolder, restoreSource: false)) + { + this.Log().Error("Could not move the bad package to the failure directory. It may show as installed.{0} {1}{0}", Environment.NewLine, packageResult.InstallLocation); + } } } - private void rollback_previous_version(ChocolateyConfiguration config, PackageResult packageResult) + private void RestorePreviousPackageVersion(ChocolateyConfiguration config, PackageResult packageResult) { if (packageResult.InstallLocation == null) return; - var rollbackDirectory = packageResult.InstallLocation.Replace(ApplicationParameters.PackagesLocation, ApplicationParameters.PackageBackupLocation); - if (!_fileSystem.directory_exists(rollbackDirectory)) + var normalizedVersion = new NuGetVersion(packageResult.Version).ToNormalizedStringChecked(); + + var rollbackDirectory = _fileSystem.CombinePaths(ApplicationParameters.PackageBackupLocation, packageResult.Name, normalizedVersion); + + if (!_fileSystem.DirectoryExists(rollbackDirectory)) { //search for folder - var possibleRollbacks = _fileSystem.get_directories(ApplicationParameters.PackageBackupLocation, packageResult.Name + "*"); + var path = _fileSystem.CombinePaths(ApplicationParameters.PackageBackupLocation, packageResult.Name); + var possibleRollbacks = _fileSystem.GetDirectories(path, normalizedVersion); + + if (possibleRollbacks == null || possibleRollbacks.Count() == 0) + { + possibleRollbacks = _fileSystem.GetDirectories(path, "*"); + } + if (possibleRollbacks != null && possibleRollbacks.Count() != 0) { rollbackDirectory = possibleRollbacks.OrderByDescending(p => p).DefaultIfEmpty(string.Empty).FirstOrDefault(); } } - rollbackDirectory = _fileSystem.get_full_path(rollbackDirectory); + rollbackDirectory = _fileSystem.GetFullPath(rollbackDirectory); - if (string.IsNullOrWhiteSpace(rollbackDirectory) || !_fileSystem.directory_exists(rollbackDirectory)) return; - if (!rollbackDirectory.StartsWith(ApplicationParameters.PackageBackupLocation) || rollbackDirectory.is_equal_to(ApplicationParameters.PackageBackupLocation)) return; + if (string.IsNullOrWhiteSpace(rollbackDirectory) || !_fileSystem.DirectoryExists(rollbackDirectory)) return; + if (!rollbackDirectory.StartsWith(ApplicationParameters.PackageBackupLocation) || rollbackDirectory.IsEqualTo(ApplicationParameters.PackageBackupLocation)) return; this.Log().Debug("Attempting rollback"); @@ -1481,72 +1648,73 @@ private void rollback_previous_version(ChocolateyConfiguration config, PackageRe if (shouldPrompt) { - var selection = InteractivePrompt.prompt_for_confirmation( - " Unsuccessful operation for {0}.{1} Rollback to previous version (package files only)?".format_with(packageResult.Name, Environment.NewLine), + var selection = InteractivePrompt.PromptForConfirmation( + " Unsuccessful operation for {0}.{1} Rollback to previous version (package files only)?".FormatWith(packageResult.Name, Environment.NewLine), new[] { "yes", "no" }, defaultChoice: null, requireAnswer: true, allowShortAnswer: true, shortPrompt: true ); - if (selection.is_equal_to("no")) rollback = false; + if (selection.IsEqualTo("no")) rollback = false; } if (rollback) { - _fileSystem.move_directory(rollbackDirectory, rollbackDirectory.Replace(ApplicationParameters.PackageBackupLocation, ApplicationParameters.PackagesLocation)); + var destination = _fileSystem.CombinePaths(ApplicationParameters.PackagesLocation, packageResult.Identity.Id); + _filesService.MovePackageUsingBackupStrategy(rollbackDirectory, destination, restoreSource: false); } - remove_rollback_if_exists(packageResult); + RemoveBackupIfExists(packageResult); } - private void remove_rollback_if_exists(PackageResult packageResult) + private void RemoveBackupIfExists(PackageResult packageResult) { - _nugetService.remove_rollback_directory_if_exists(packageResult.Name); + _nugetService.EnsureBackupDirectoryRemoved(packageResult.Name); } - public virtual void set_pending(PackageResult packageResult, ChocolateyConfiguration config) + public virtual void MarkPackagePending(PackageResult packageResult, ChocolateyConfiguration config) { var packageDirectory = packageResult.InstallLocation; if (string.IsNullOrWhiteSpace(packageDirectory)) return; - if (packageDirectory.is_equal_to(ApplicationParameters.InstallLocation) || packageDirectory.is_equal_to(ApplicationParameters.PackagesLocation)) + if (packageDirectory.IsEqualTo(ApplicationParameters.InstallLocation) || packageDirectory.IsEqualTo(ApplicationParameters.PackagesLocation)) { packageResult.Messages.Add( new ResultMessage( ResultType.Error, - "Install location is not specific enough, cannot run set package to pending:{0} Erroneous install location captured as '{1}'".format_with(Environment.NewLine, packageResult.InstallLocation) + "Install location is not specific enough, cannot run set package to pending:{0} Erroneous install location captured as '{1}'".FormatWith(Environment.NewLine, packageResult.InstallLocation) ) ); return; } - var pendingFile = _fileSystem.combine_paths(packageDirectory, ApplicationParameters.PackagePendingFileName); - _fileSystem.write_file(pendingFile, "{0}".format_with(packageResult.Name)); + var pendingFile = _fileSystem.CombinePaths(packageDirectory, ApplicationParameters.PackagePendingFileName); + _fileSystem.WriteFile(pendingFile, "{0}".FormatWith(packageResult.Name)); if (ApplicationParameters.LockTransactionalInstallFiles) { - _pendingLocks.Add(packageResult.Name.to_lower(), _fileSystem.open_file_exclusive(pendingFile)); + _pendingLocks.Add(packageResult.Name.ToLowerSafe(), _fileSystem.OpenFileExclusive(pendingFile)); } } - public virtual void remove_pending(PackageResult packageResult, ChocolateyConfiguration config) + public virtual void UnmarkPackagePending(PackageResult packageResult, ChocolateyConfiguration config) { var packageDirectory = packageResult.InstallLocation; if (string.IsNullOrWhiteSpace(packageDirectory)) return; - if (packageDirectory.is_equal_to(ApplicationParameters.InstallLocation) || packageDirectory.is_equal_to(ApplicationParameters.PackagesLocation)) + if (packageDirectory.IsEqualTo(ApplicationParameters.InstallLocation) || packageDirectory.IsEqualTo(ApplicationParameters.PackagesLocation)) { packageResult.Messages.Add( new ResultMessage( ResultType.Error, - "Install location is not specific enough, cannot run set package to pending:{0} Erroneous install location captured as '{1}'".format_with(Environment.NewLine, packageResult.InstallLocation) + "Install location is not specific enough, cannot run set package to pending:{0} Erroneous install location captured as '{1}'".FormatWith(Environment.NewLine, packageResult.InstallLocation) ) ); return; } - var pendingFile = _fileSystem.combine_paths(packageDirectory, ApplicationParameters.PackagePendingFileName); - var lockName = packageResult.Name.to_lower(); + var pendingFile = _fileSystem.CombinePaths(packageDirectory, ApplicationParameters.PackagePendingFileName); + var lockName = packageResult.Name.ToLowerSafe(); if (_pendingLocks.ContainsKey(lockName)) { var fileLock = _pendingLocks[lockName]; @@ -1555,29 +1723,29 @@ public virtual void remove_pending(PackageResult packageResult, ChocolateyConfig fileLock.Dispose(); } - if (packageResult.Success && _fileSystem.file_exists(pendingFile)) _fileSystem.delete_file(pendingFile); + if (packageResult.Success && _fileSystem.FileExists(pendingFile)) _fileSystem.DeleteFile(pendingFile); } - private IEnumerable get_environment_before(ChocolateyConfiguration config, bool allowLogging = true) + private IEnumerable GetInitialEnvironment(ChocolateyConfiguration config, bool allowLogging = true) { if (config.Information.PlatformType != PlatformType.Windows) return Enumerable.Empty(); - var environmentBefore = _registryService.get_environment_values(); + var environmentBefore = _registryService.GetEnvironmentValues(); if (allowLogging && config.Features.LogEnvironmentValues) { this.Log().Debug("Current environment values (may contain sensitive data):"); - foreach (var environmentValue in environmentBefore.or_empty_list_if_null()) + foreach (var environmentValue in environmentBefore.OrEmpty()) { - this.Log().Debug(@" * '{0}'='{1}' ('{2}')".format_with( - environmentValue.Name.escape_curly_braces(), - environmentValue.Value.escape_curly_braces(), - environmentValue.ParentKeyName.to_lower().Contains("hkey_current_user") ? "User" : "Machine")); + this.Log().Debug(@" * '{0}'='{1}' ('{2}')".FormatWith( + environmentValue.Name.EscapeCurlyBraces(), + environmentValue.Value.EscapeCurlyBraces(), + environmentValue.ParentKeyName.ToLowerSafe().Contains("hkey_current_user") ? "User" : "Machine")); } } return environmentBefore; } - private void get_log_environment_changes(ChocolateyConfiguration config, IEnumerable environmentBefore, out IEnumerable environmentChanges, out IEnumerable environmentRemovals) + private void LogEnvironmentChanges(ChocolateyConfiguration config, IEnumerable environmentBefore, out IEnumerable environmentChanges, out IEnumerable environmentRemovals) { if (config.Information.PlatformType != PlatformType.Windows) { @@ -1587,9 +1755,9 @@ private void get_log_environment_changes(ChocolateyConfiguration config, IEnumer return; } - var environmentAfer = _registryService.get_environment_values(); - environmentChanges = _registryService.get_added_changed_environment_differences(environmentBefore, environmentAfer); - environmentRemovals = _registryService.get_removed_environment_differences(environmentBefore, environmentAfer); + var environmentAfer = _registryService.GetEnvironmentValues(); + environmentChanges = _registryService.GetNewAndModifiedEnvironmentValues(environmentBefore, environmentAfer); + environmentRemovals = _registryService.GetRemovedEnvironmentValues(environmentBefore, environmentAfer); var hasEnvironmentChanges = environmentChanges.Count() != 0; var hasEnvironmentRemovals = environmentRemovals.Count() != 0; if (hasEnvironmentChanges || hasEnvironmentRemovals) @@ -1607,12 +1775,12 @@ private void get_log_environment_changes(ChocolateyConfiguration config, IEnumer if (hasEnvironmentChanges) { this.Log().Debug(@"The following values have been added/changed (may contain sensitive data):"); - foreach (var difference in environmentChanges.or_empty_list_if_null()) + foreach (var difference in environmentChanges.OrEmpty()) { - this.Log().Debug(@" * {0}='{1}' ({2})".format_with( - difference.Name.escape_curly_braces(), - config.Features.LogEnvironmentValues ? difference.Value.escape_curly_braces() : "[REDACTED]", - difference.ParentKeyName.to_lower().Contains("hkey_current_user") ? "User" : "Machine" + this.Log().Debug(@" * {0}='{1}' ({2})".FormatWith( + difference.Name.EscapeCurlyBraces(), + config.Features.LogEnvironmentValues ? difference.Value.EscapeCurlyBraces() : "[REDACTED]", + difference.ParentKeyName.ToLowerSafe().Contains("hkey_current_user") ? "User" : "Machine" )); } } @@ -1620,57 +1788,57 @@ private void get_log_environment_changes(ChocolateyConfiguration config, IEnumer if (hasEnvironmentRemovals) { this.Log().Debug(@"The following values have been removed:"); - foreach (var difference in environmentRemovals.or_empty_list_if_null()) + foreach (var difference in environmentRemovals.OrEmpty()) { - this.Log().Debug(@" * {0}='{1}' ({2})".format_with( - difference.Name.escape_curly_braces(), - config.Features.LogEnvironmentValues ? difference.Value.escape_curly_braces() : "[REDACTED]", - difference.ParentKeyName.to_lower().Contains("hkey_current_user") ? "User" : "Machine" + this.Log().Debug(@" * {0}='{1}' ({2})".FormatWith( + difference.Name.EscapeCurlyBraces(), + config.Features.LogEnvironmentValues ? difference.Value.EscapeCurlyBraces() : "[REDACTED]", + difference.ParentKeyName.ToLowerSafe().Contains("hkey_current_user") ? "User" : "Machine" )); } } } } - private ISourceRunner get_source_runner(string sourceType) + private TSourceRunner GetSourceRunner(string sourceType, IEnumerable alternativeSourceRunners) + where TSourceRunner : class, IAlternativeSourceRunner { - // We add the trailing s to the check in case of windows feature which can be specified both with and without - // the s. - return _sourceRunners.FirstOrDefault(s => s.SourceType == sourceType || s.SourceType == sourceType + "s"); + return alternativeSourceRunners.FirstOrDefault(s => s.SourceType == sourceType || s.SourceType == sourceType + "s"); } - private void handle_hook_packages(ChocolateyConfiguration config, PackageResult packageResult) + // This should probably be split into install(/upgrade)/uninstall methods with shared logic placed in helper method(s). + private void HandleHookPackages(ChocolateyConfiguration config, PackageResult packageResult) { if (packageResult == null) return; - if (!packageResult.Name.to_lower().EndsWith(ApplicationParameters.HookPackageIdExtension)) return; + if (!packageResult.Name.ToLowerSafe().EndsWith(ApplicationParameters.HookPackageIdExtension)) return; - _fileSystem.create_directory_if_not_exists(ApplicationParameters.HooksLocation); - var hookFolderName = packageResult.Name.to_lower().Replace(ApplicationParameters.HookPackageIdExtension, string.Empty); - var installHookPath = _fileSystem.combine_paths(ApplicationParameters.HooksLocation, hookFolderName); + _fileSystem.EnsureDirectoryExists(ApplicationParameters.HooksLocation); + var hookFolderName = packageResult.Name.ToLowerSafe().Replace(ApplicationParameters.HookPackageIdExtension, string.Empty); + var installHookPath = _fileSystem.CombinePaths(ApplicationParameters.HooksLocation, hookFolderName); - FaultTolerance.try_catch_with_logging_exception( + FaultTolerance.TryCatchWithLoggingException( () => { - _fileSystem.delete_directory_if_exists(installHookPath, recursive: true); + _fileSystem.DeleteDirectoryChecked(installHookPath, recursive: true); }, - "Attempted to remove '{0}' but had an error".format_with(installHookPath)); + "Attempted to remove '{0}' but had an error".FormatWith(installHookPath)); - if (!config.CommandName.is_equal_to(CommandNameType.uninstall.to_string())) + if (!config.CommandName.IsEqualTo(CommandNameType.Uninstall.ToStringSafe())) { if (packageResult.InstallLocation == null) return; - _fileSystem.create_directory_if_not_exists(installHookPath); - var hookPath = _fileSystem.combine_paths(packageResult.InstallLocation, "hook"); - var hookFolderToCopy = _fileSystem.directory_exists(hookPath) ? hookPath : packageResult.InstallLocation; + _fileSystem.EnsureDirectoryExists(installHookPath); + var hookPath = _fileSystem.CombinePaths(packageResult.InstallLocation, "hook"); + var hookFolderToCopy = _fileSystem.DirectoryExists(hookPath) ? hookPath : packageResult.InstallLocation; - FaultTolerance.try_catch_with_logging_exception( + FaultTolerance.TryCatchWithLoggingException( () => { - _fileSystem.copy_directory(hookFolderToCopy, installHookPath, overwriteExisting: true); + _fileSystem.CopyDirectory(hookFolderToCopy, installHookPath, overwriteExisting: true); }, - "Attempted to copy{0} '{1}'{0} to '{2}'{0} but had an error".format_with(Environment.NewLine, hookFolderToCopy, installHookPath)); + "Attempted to copy{0} '{1}'{0} to '{2}'{0} but had an error".FormatWith(Environment.NewLine, hookFolderToCopy, installHookPath)); - string logMessage = " Installed/updated {0} hook.".format_with(hookFolderName); + string logMessage = " Installed/updated {0} hook.".FormatWith(hookFolderName); this.Log().Warn(logMessage); packageResult.Messages.Add(new ResultMessage(ResultType.Note, logMessage)); @@ -1678,10 +1846,100 @@ private void handle_hook_packages(ChocolateyConfiguration config, PackageResult } else { - string logMessage = " Uninstalled {0} hook.".format_with(hookFolderName); + string logMessage = " Uninstalled {0} hook.".FormatWith(hookFolderName); this.Log().Warn(logMessage); packageResult.Messages.Add(new ResultMessage(ResultType.Note, logMessage)); } } + +#pragma warning disable IDE1006 + [Obsolete("This overload is deprecated and will be removed in v3.")] + public virtual int count_run(ChocolateyConfiguration config) + => Count(config); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public void list_noop(ChocolateyConfiguration config) + => ListDryRun(config); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public virtual IEnumerable list_run(ChocolateyConfiguration config) + => List(config); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public void pack_noop(ChocolateyConfiguration config) + => PackDryRun(config); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public virtual void pack_run(ChocolateyConfiguration config) + => Pack(config); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public void push_noop(ChocolateyConfiguration config) + => PushDryRun(config); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public virtual void push_run(ChocolateyConfiguration config) + => Push(config); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public void install_noop(ChocolateyConfiguration config) + => InstallDryRun(config); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public void randomly_notify_about_pro_business(ChocolateyConfiguration config, string message = null) + => RandomlyNotifyAboutLicensedFeatures(config, message); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public virtual void handle_package_result(PackageResult packageResult, ChocolateyConfiguration config, CommandNameType commandName) + => HandlePackageResult(packageResult, config, commandName); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + protected virtual ChocolateyPackageInformation get_package_information(PackageResult packageResult, ChocolateyConfiguration config) + => GetPackageInformation(packageResult, config); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + protected virtual void update_package_information(ChocolateyPackageInformation pkgInfo) + => UpdatePackageInformation(pkgInfo); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public virtual ConcurrentDictionary install_run(ChocolateyConfiguration config) + => Install(config); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public void outdated_noop(ChocolateyConfiguration config) + => OutdatedDryRun(config); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public virtual void outdated_run(ChocolateyConfiguration config) + => Outdated(config); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public void upgrade_noop(ChocolateyConfiguration config) + => UpgradeDryRun(config); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public virtual ConcurrentDictionary upgrade_run(ChocolateyConfiguration config) + => Upgrade(config); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public void uninstall_noop(ChocolateyConfiguration config) + => UninstallDryRun(config); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public virtual ConcurrentDictionary uninstall_run(ChocolateyConfiguration config) + => Uninstall(config); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public virtual void handle_package_uninstall(PackageResult packageResult, ChocolateyConfiguration config) + => HandlePackageUninstall(packageResult, config); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public virtual void set_pending(PackageResult packageResult, ChocolateyConfiguration config) + => MarkPackagePending(packageResult, config); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public virtual void remove_pending(PackageResult packageResult, ChocolateyConfiguration config) + => UnmarkPackagePending(packageResult, config); +#pragma warning restore IDE1006 } } diff --git a/src/chocolatey/infrastructure.app/services/ConfigTransformService.cs b/src/chocolatey/infrastructure.app/services/ConfigTransformService.cs index 4b6bf639f6..7dc4d3f05a 100644 --- a/src/chocolatey/infrastructure.app/services/ConfigTransformService.cs +++ b/src/chocolatey/infrastructure.app/services/ConfigTransformService.cs @@ -30,47 +30,52 @@ namespace chocolatey.infrastructure.app.services public class ConfigTransformService : IConfigTransformService { private readonly IFileSystem _fileSystem; - private const int MUTEX_TIMEOUT = 2000; + private const int MutexTimeoutMs = 2000; public ConfigTransformService(IFileSystem fileSystem) { _fileSystem = fileSystem; } - public void run(PackageResult packageResult, ChocolateyConfiguration config) + public void Run(PackageResult packageResult, ChocolateyConfiguration config) { var installDirectory = packageResult != null ? packageResult.InstallLocation : string.Empty; - if (string.IsNullOrWhiteSpace(installDirectory) || installDirectory.is_equal_to(ApplicationParameters.InstallLocation) || installDirectory.is_equal_to(ApplicationParameters.PackagesLocation)) + if (string.IsNullOrWhiteSpace(installDirectory) || installDirectory.IsEqualTo(ApplicationParameters.InstallLocation) || installDirectory.IsEqualTo(ApplicationParameters.PackagesLocation)) { - var logMessage = "Install location is not specific enough, cannot capture files:{0} Erroneous install location captured as '{1}'".format_with(Environment.NewLine, installDirectory); + var logMessage = "Install location is not specific enough, cannot capture files:{0} Erroneous install location captured as '{1}'".FormatWith(Environment.NewLine, installDirectory); if (packageResult != null) packageResult.Messages.Add(new ResultMessage(ResultType.Warn, logMessage)); this.Log().Error(logMessage); return; } - var transformFiles = _fileSystem.get_files(installDirectory, "*" + ApplicationParameters.ConfigFileTransformExtension, SearchOption.AllDirectories); - foreach (var transformFile in transformFiles.or_empty_list_if_null()) + var transformFiles = _fileSystem.GetFiles(installDirectory, "*" + ApplicationParameters.ConfigFileTransformExtension, SearchOption.AllDirectories); + foreach (var transformFile in transformFiles.OrEmpty()) { - this.Log().Debug(() => "Preparing transform for '{0}'".format_with(transformFile)); - var targetFileName = _fileSystem.get_file_name(transformFile.Replace(ApplicationParameters.ConfigFileTransformExtension, string.Empty)); + this.Log().Debug(() => "Preparing transform for '{0}'".FormatWith(transformFile)); + var targetFileName = _fileSystem.GetFileName(transformFile.Replace(ApplicationParameters.ConfigFileTransformExtension, string.Empty)); // target files must exist, otherwise one is added next to the transform - var targetFiles = _fileSystem.get_files(installDirectory, targetFileName, SearchOption.AllDirectories); + var targetFiles = _fileSystem.GetFiles(installDirectory, targetFileName, SearchOption.AllDirectories); var targetFilesTest = targetFiles as IList ?? targetFiles.ToList(); if (!targetFilesTest.Any()) { targetFiles = new[] {transformFile.Replace(ApplicationParameters.ConfigFileTransformExtension, string.Empty)}; - this.Log().Debug(() => "No matching files found for transform {0}.{1} Creating '{2}'".format_with(_fileSystem.get_file_name(transformFile), Environment.NewLine, targetFiles.FirstOrDefault())); + this.Log().Debug(() => "No matching files found for transform {0}.{1} Creating '{2}'".FormatWith(_fileSystem.GetFileName(transformFile), Environment.NewLine, targetFiles.FirstOrDefault())); } - foreach (var targetFile in targetFilesTest.or_empty_list_if_null()) + foreach (var targetFile in targetFilesTest.OrEmpty()) { - GlobalMutex.enter( + GlobalMutex.Enter( () => { - var backupTargetFile = targetFile.Replace(ApplicationParameters.PackagesLocation, ApplicationParameters.PackageBackupLocation); + // TODO: ONce we have information about package being upgraded from, we can use this + // information instead of doing a naive resolving of the backup directory. + + var backupDirectory = Path.Combine(ApplicationParameters.PackageBackupLocation, packageResult.Name); + + var backupTargetFile = FindBackupTargetFile(targetFile, installDirectory, backupDirectory, packageResult.Version); - FaultTolerance.try_catch_with_logging_exception( + FaultTolerance.TryCatchWithLoggingException( () => { // if there is a backup, we need to put it back in place @@ -78,10 +83,10 @@ public void run(PackageResult packageResult, ChocolateyConfiguration config) // the transform file into the folder, so we will override // the replacement of the file and instead pull from the last // backup and let the transform to its thing instead. - if (_fileSystem.file_exists(backupTargetFile)) + if (_fileSystem.FileExists(backupTargetFile)) { - this.Log().Debug(()=> "Restoring backup configuration file for '{0}'.".format_with(targetFile)); - _fileSystem.copy_file(backupTargetFile, targetFile, overwriteExisting: true); + this.Log().Debug(()=> "Restoring backup configuration file for '{0}'.".FormatWith(targetFile)); + _fileSystem.CopyFile(backupTargetFile, targetFile, overwriteExisting: true); } }, "Error replacing backup config file", @@ -90,13 +95,13 @@ public void run(PackageResult packageResult, ChocolateyConfiguration config) try { - this.Log().Info(() => "Transforming '{0}' with the data from '{1}'".format_with(_fileSystem.get_file_name(targetFile), _fileSystem.get_file_name(transformFile))); + this.Log().Info(() => "Transforming '{0}' with the data from '{1}'".FormatWith(_fileSystem.GetFileName(targetFile), _fileSystem.GetFileName(transformFile))); - using (var transformation = new XmlTransformation(_fileSystem.read_file(transformFile), isTransformAFile: false, logger: null)) + using (var transformation = new XmlTransformation(_fileSystem.ReadFile(transformFile), isTransformAFile: false, logger: null)) { using (var document = new XmlTransformableDocument {PreserveWhitespace = true}) { - using (var inputStream = _fileSystem.open_file_readonly(targetFile)) + using (var inputStream = _fileSystem.OpenFileReadonly(targetFile)) { document.Load(inputStream); } @@ -104,18 +109,18 @@ public void run(PackageResult packageResult, ChocolateyConfiguration config) // before applying the XDT transformation, let's make a // backup of the file that should be transformed, in case // things don't go correctly - this.Log().Debug(() => "Creating backup configuration file for '{0}'.".format_with(targetFile)); - _fileSystem.copy_file(targetFile, backupTargetFile, overwriteExisting: true); + this.Log().Debug(() => "Creating backup configuration file for '{0}'.".FormatWith(targetFile)); + _fileSystem.CopyFile(targetFile, backupTargetFile, overwriteExisting: true); bool succeeded = transformation.Apply(document); if (succeeded) { - this.Log().Debug(() => "Transform applied successfully for '{0}'".format_with(targetFile)); + this.Log().Debug(() => "Transform applied successfully for '{0}'".FormatWith(targetFile)); using (var memoryStream = new MemoryStream()) { document.Save(memoryStream); memoryStream.Seek(0, SeekOrigin.Begin); - using (var fileStream = _fileSystem.create_file(targetFile)) + using (var fileStream = _fileSystem.CreateFile(targetFile)) { fileStream.SetLength(0); memoryStream.CopyTo(fileStream); @@ -133,7 +138,7 @@ public void run(PackageResult packageResult, ChocolateyConfiguration config) catch (Exception) { this.Log().Warn(() => "Transformed configuration file doesn't contain valid XML. Restoring backup file..."); - _fileSystem.copy_file(backupTargetFile, targetFile, overwriteExisting: true); + _fileSystem.CopyFile(backupTargetFile, targetFile, overwriteExisting: true); this.Log().Debug(() => "Backup file restored."); } } @@ -141,27 +146,57 @@ public void run(PackageResult packageResult, ChocolateyConfiguration config) { // at this point, there is no need to restore the backup file, // as the resulting transform hasn't actually been written to disk. - this.Log().Warn(() => "Transform failed for '{0}'".format_with(targetFile)); + this.Log().Warn(() => "Transform failed for '{0}'".FormatWith(targetFile)); } } } } catch (Exception) { - FaultTolerance.try_catch_with_logging_exception( + FaultTolerance.TryCatchWithLoggingException( () => { // something went wrong with the transformation, so we should restore // the original configuration file from the backup this.Log().Warn(() => "There was a problem transforming configuration file, restoring backup file..."); - _fileSystem.copy_file(backupTargetFile, targetFile, overwriteExisting: true); + _fileSystem.CopyFile(backupTargetFile, targetFile, overwriteExisting: true); this.Log().Debug(() => "Backup file restored."); }, "Error restoring backup configuration file."); } - }, MUTEX_TIMEOUT); + }, MutexTimeoutMs); + } + } + } + + private string FindBackupTargetFile(string targetFile, string installDirectory, string backupDirectory, string version) + { + foreach (var directory in _fileSystem.GetDirectories(backupDirectory)) + { + var directoryName = _fileSystem.GetFileName(directory); + + if (string.IsNullOrEmpty(directoryName) || directoryName.IsEqualTo(version)) + { + continue; + } + + var filePath = targetFile.Replace(installDirectory, directory); + + if (_fileSystem.FileExists(filePath)) + { + return filePath; } } + + // We will fall back to old location in pre-v2 if the file was + // not found in new backup directories. + return targetFile.Replace(installDirectory, backupDirectory); } + +#pragma warning disable IDE1006 + [Obsolete("This overload is deprecated and will be removed in v3.")] + public void run(PackageResult packageResult, ChocolateyConfiguration config) + => Run(packageResult, config); +#pragma warning restore IDE1006 } } diff --git a/src/chocolatey/infrastructure.app/services/CygwinService.cs b/src/chocolatey/infrastructure.app/services/CygwinService.cs index 92c11effbc..252d24cc0d 100644 --- a/src/chocolatey/infrastructure.app/services/CygwinService.cs +++ b/src/chocolatey/infrastructure.app/services/CygwinService.cs @@ -36,15 +36,15 @@ namespace chocolatey.infrastructure.app.services /// /// https://cygwin.com/faq/faq.html#faq.setup.cli /// - public sealed class CygwinService : ISourceRunner + public sealed class CygwinService : IBootstrappableSourceRunner, IInstallSourceRunner { private readonly ICommandExecutor _commandExecutor; private readonly INugetService _nugetService; private readonly IFileSystem _fileSystem; private readonly IRegistryService _registryService; - private const string PACKAGE_NAME_TOKEN = "{{packagename}}"; - private const string INSTALL_ROOT_TOKEN = "{{installroot}}"; - public const string CYGWIN_PACKAGE = "cygwin"; + private const string PackageNameToken = "{{packagename}}"; + private const string InstallRootToken = "{{installroot}}"; + private const string CygwinPackage = "cygwin"; private string _rootDirectory; private string RootDirectory @@ -53,17 +53,17 @@ private string RootDirectory { if (string.IsNullOrWhiteSpace(_rootDirectory)) { - _rootDirectory = get_root_directory(); + _rootDirectory = GetRootDirectory(); } return _rootDirectory; } } - private const string APP_NAME = "Cygwin"; - public const string PACKAGE_NAME_GROUP = "PkgName"; - public static readonly Regex InstalledRegex = new Regex(@"Extracting from file", RegexOptions.Compiled); - public static readonly Regex PackageNameRegex = new Regex(@"/(?<{0}>[^/]*).tar.".format_with(PACKAGE_NAME_GROUP), RegexOptions.Compiled); + private const string AppName = "Cygwin"; + private const string PackageNameGroup = "PkgName"; + private static readonly Regex _installedRegex = new Regex(@"Extracting from file", RegexOptions.Compiled); + private static readonly Regex _packageNameRegex = new Regex(@"/(?<{0}>[^/]*).tar.".FormatWith(PackageNameGroup), RegexOptions.Compiled); private readonly IDictionary _installArguments = new Dictionary(StringComparer.InvariantCultureIgnoreCase); @@ -73,21 +73,21 @@ public CygwinService(ICommandExecutor commandExecutor, INugetService nugetServic _nugetService = nugetService; _fileSystem = fileSystem; _registryService = registryService; - set_cmd_args_dictionaries(); + StoreCommandArgs(); } /// /// Set any command arguments dictionaries necessary for the service /// - private void set_cmd_args_dictionaries() + private void StoreCommandArgs() { - set_install_dictionary(_installArguments); + InitializeInstallDictionary(_installArguments); } /// /// Sets install dictionary /// - private void set_install_dictionary(IDictionary args) + private void InitializeInstallDictionary(IDictionary args) { //args.Add("_cmd_c_", new ExternalCommandArgument { ArgumentOption = "/c", Required = true }); //args.Add("_app_", new ExternalCommandArgument @@ -104,14 +104,14 @@ private void set_install_dictionary(IDictionary args.Add("_root_", new ExternalCommandArgument { ArgumentOption = "--root ", - ArgumentValue = INSTALL_ROOT_TOKEN, + ArgumentValue = InstallRootToken, QuoteValue = false, Required = true }); args.Add("_local_pkgs_dir_", new ExternalCommandArgument { ArgumentOption = "--local-package-dir ", - ArgumentValue = "{0}\\packages".format_with(INSTALL_ROOT_TOKEN), + ArgumentValue = "{0}\\packages".FormatWith(InstallRootToken), QuoteValue = false, Required = true }); @@ -127,7 +127,7 @@ private void set_install_dictionary(IDictionary args.Add("_package_name_", new ExternalCommandArgument { ArgumentOption = "--packages ", - ArgumentValue = PACKAGE_NAME_TOKEN, + ArgumentValue = PackageNameToken, QuoteValue = false, Required = true }); @@ -135,12 +135,12 @@ private void set_install_dictionary(IDictionary public string SourceType { - get { return SourceTypes.CYGWIN; } + get { return SourceTypes.Cygwin; } } - public void ensure_source_app_installed(ChocolateyConfiguration config, Action ensureAction) + public void EnsureSourceAppInstalled(ChocolateyConfiguration config, Action ensureAction) { - if (Platform.get_platform() != PlatformType.Windows) throw new NotImplementedException("This source is not supported on non-Windows systems"); + if (Platform.GetPlatform() != PlatformType.Windows) throw new NotImplementedException("This source is not supported on non-Windows systems"); var runnerConfig = new ChocolateyConfiguration { @@ -157,120 +157,92 @@ public void ensure_source_app_installed(ChocolateyConfiguration config, Action

p.Name.is_equal_to(CYGWIN_PACKAGE))) + if (!localPackages.Any(p => p.Name.IsEqualTo(CygwinPackage))) { - runnerConfig.PackageNames = CYGWIN_PACKAGE; + runnerConfig.PackageNames = CygwinPackage; runnerConfig.Sources = ApplicationParameters.ChocolateyCommunityFeedSource; var prompt = config.PromptForConfirmation; config.PromptForConfirmation = false; - _nugetService.install_run(runnerConfig, ensureAction.Invoke); + _nugetService.Install(runnerConfig, ensureAction.Invoke); config.PromptForConfirmation = prompt; } } - public int count_run(ChocolateyConfiguration config) - { - throw new NotImplementedException("Count is not supported for this source runner."); - } - - [Obsolete("This method does not need to be called publicly and may be made private or removed in a later version.")] - public void set_root_dir_if_not_set() + private string GetRootDirectory() { - if (!string.IsNullOrWhiteSpace(_rootDirectory)) - { - return; - } - - _rootDirectory = get_root_directory(); - } - - private string get_root_directory() - { - var setupKey = _registryService.get_key(RegistryHive.LocalMachine, "SOFTWARE\\Cygwin\\setup"); + var setupKey = _registryService.GetKey(RegistryHive.LocalMachine, "SOFTWARE\\Cygwin\\setup"); if (setupKey != null) { - return setupKey.GetValue("rootdir", string.Empty).to_string(); + return setupKey.GetValue("rootdir", string.Empty).ToStringSafe(); } var binRoot = Environment.GetEnvironmentVariable("ChocolateyBinRoot"); if (string.IsNullOrWhiteSpace(binRoot)) binRoot = "c:\\tools"; - return _fileSystem.combine_paths(binRoot, "cygwin"); + return _fileSystem.CombinePaths(binRoot, "cygwin"); } - [Obsolete("This method does not need to be called publicly and may be made private or removed in a later version.")] - public string get_exe(string rootpath) + private string GetCygwinPath(string rootpath) { - return _fileSystem.combine_paths(rootpath, "cygwinsetup.exe"); + return _fileSystem.CombinePaths(rootpath, "cygwinsetup.exe"); } - public void list_noop(ChocolateyConfiguration config) + private string BuildArgs(ChocolateyConfiguration config, IDictionary argsDictionary) { - this.Log().Warn(ChocolateyLoggers.Important, "{0} does not implement list".format_with(APP_NAME)); - } + var args = ExternalCommandArgsBuilder.BuildArguments(config, argsDictionary); - public IEnumerable list_run(ChocolateyConfiguration config) - { - throw new NotImplementedException("{0} does not implement list".format_with(APP_NAME)); - } - - [Obsolete("This method does not need to be called publicly and may be made private or removed in a later version.")] - public string build_args(ChocolateyConfiguration config, IDictionary argsDictionary) - { - var args = ExternalCommandArgsBuilder.build_arguments(config, argsDictionary); - - args = args.Replace(INSTALL_ROOT_TOKEN, RootDirectory); + args = args.Replace(InstallRootToken, RootDirectory); return args; } - public void install_noop(ChocolateyConfiguration config, Action continueAction) + public void InstallDryRun(ChocolateyConfiguration config, Action continueAction) { - var args = build_args(config, _installArguments); - this.Log().Info("Would have run '{0} {1}'".format_with(get_exe(RootDirectory).escape_curly_braces(), args.escape_curly_braces())); + var args = BuildArgs(config, _installArguments); + this.Log().Info("Would have run '{0} {1}'".FormatWith(GetCygwinPath(RootDirectory).EscapeCurlyBraces(), args.EscapeCurlyBraces())); } - public ConcurrentDictionary install_run(ChocolateyConfiguration config, Action continueAction) + public ConcurrentDictionary Install(ChocolateyConfiguration config, Action continueAction) { - return install_run(config, continueAction, beforeModifyAction: null); + return Install(config, continueAction, beforeModifyAction: null); } - public ConcurrentDictionary install_run(ChocolateyConfiguration config, Action continueAction, Action beforeModifyAction) + public ConcurrentDictionary Install(ChocolateyConfiguration config, Action continueAction, Action beforeModifyAction) { - var args = build_args(config, _installArguments); + var args = BuildArgs(config, _installArguments); var packageResults = new ConcurrentDictionary(StringComparer.InvariantCultureIgnoreCase); foreach (var packageToInstall in config.PackageNames.Split(new[] { ApplicationParameters.PackageNamesSeparator }, StringSplitOptions.RemoveEmptyEntries)) { - var argsForPackage = args.Replace(PACKAGE_NAME_TOKEN, packageToInstall); + var argsForPackage = args.Replace(PackageNameToken, packageToInstall); - var exitCode = _commandExecutor.execute( - get_exe(RootDirectory), + var exitCode = _commandExecutor.Execute( + GetCygwinPath(RootDirectory), argsForPackage, config.CommandExecutionTimeoutSeconds, - _fileSystem.get_current_directory(), + _fileSystem.GetCurrentDirectory(), (s, e) => { var logMessage = e.Data; if (string.IsNullOrWhiteSpace(logMessage)) return; - this.Log().Info(() => " [{0}] {1}".format_with(APP_NAME, logMessage.escape_curly_braces())); + this.Log().Info(() => " [{0}] {1}".FormatWith(AppName, logMessage.EscapeCurlyBraces())); - if (InstalledRegex.IsMatch(logMessage)) + if (_installedRegex.IsMatch(logMessage)) { - var packageName = get_value_from_output(logMessage, PackageNameRegex, PACKAGE_NAME_GROUP); + var packageName = GetValueFromOutput(logMessage, _packageNameRegex, PackageNameGroup); var results = packageResults.GetOrAdd(packageName, new PackageResult(packageName, null, null)); results.Messages.Add(new ResultMessage(ResultType.Note, packageName)); - this.Log().Info(ChocolateyLoggers.Important, " {0} has been installed successfully.".format_with(string.IsNullOrWhiteSpace(packageName) ? packageToInstall : packageName)); + this.Log().Info(ChocolateyLoggers.Important, " {0} has been installed successfully.".FormatWith(string.IsNullOrWhiteSpace(packageName) ? packageToInstall : packageName)); } }, (s, e) => { var logMessage = e.Data; if (string.IsNullOrWhiteSpace(logMessage)) return; - this.Log().Error("[{0}] {1}".format_with(APP_NAME, logMessage.escape_curly_braces())); + this.Log().Error("[{0}] {1}".FormatWith(AppName, logMessage.EscapeCurlyBraces())); }, updateProcessPath: false, allowUseWindow: true @@ -285,27 +257,6 @@ public ConcurrentDictionary install_run(ChocolateyConfigu return packageResults; } - public ConcurrentDictionary upgrade_noop(ChocolateyConfiguration config, Action continueAction) - { - this.Log().Warn(ChocolateyLoggers.Important, "{0} does not implement upgrade".format_with(APP_NAME)); - return new ConcurrentDictionary(StringComparer.InvariantCultureIgnoreCase); - } - - public ConcurrentDictionary upgrade_run(ChocolateyConfiguration config, Action continueAction, Action beforeUpgradeAction = null) - { - throw new NotImplementedException("{0} does not implement upgrade".format_with(APP_NAME)); - } - - public void uninstall_noop(ChocolateyConfiguration config, Action continueAction) - { - this.Log().Warn(ChocolateyLoggers.Important, "{0} does not implement uninstall".format_with(APP_NAME)); - } - - public ConcurrentDictionary uninstall_run(ChocolateyConfiguration config, Action continueAction, Action beforeUninstallAction = null) - { - throw new NotImplementedException("{0} does not implement upgrade".format_with(APP_NAME)); - } - ///

/// Grabs a value from the output based on the regex. /// @@ -313,7 +264,7 @@ public ConcurrentDictionary uninstall_run(ChocolateyConfi /// The regex. /// Name of the group. /// - private static string get_value_from_output(string output, Regex regex, string groupName) + private static string GetValueFromOutput(string output, Regex regex, string groupName) { var matchGroup = regex.Match(output).Groups[groupName]; if (matchGroup != null) @@ -323,5 +274,32 @@ private static string get_value_from_output(string output, Regex regex, string g return string.Empty; } + +#pragma warning disable IDE1006 + [Obsolete("This overload is deprecated and will be removed in v3.")] + public const string CYGWIN_PACKAGE = CygwinPackage; + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public const string PACKAGE_NAME_GROUP = PackageNameGroup; + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public static readonly Regex PackageNameRegex = _packageNameRegex; + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public void ensure_source_app_installed(ChocolateyConfiguration config, Action ensureAction) + => EnsureSourceAppInstalled(config, ensureAction); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public void install_noop(ChocolateyConfiguration config, Action continueAction) + => InstallDryRun(config, continueAction); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public ConcurrentDictionary install_run(ChocolateyConfiguration config, Action continueAction) + => Install(config, continueAction); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public ConcurrentDictionary install_run(ChocolateyConfiguration config, Action continueAction, Action beforeModifyAction) + => Install(config, continueAction, beforeModifyAction); +#pragma warning restore IDE1006 } } diff --git a/src/chocolatey/infrastructure.app/services/FilesService.cs b/src/chocolatey/infrastructure.app/services/FilesService.cs index d3810afa45..da5f278937 100644 --- a/src/chocolatey/infrastructure.app/services/FilesService.cs +++ b/src/chocolatey/infrastructure.app/services/FilesService.cs @@ -19,6 +19,7 @@ namespace chocolatey.infrastructure.app.services using System; using System.IO; using System.Linq; + using System.Runtime.ConstrainedExecution; using configuration; using cryptography; using domain; @@ -40,28 +41,28 @@ public FilesService(IXmlService xmlService, IFileSystem fileSystem, IHashProvide _hashProvider = hashProvider; } - public PackageFiles read_from_file(string filePath) + public PackageFiles ReadPackageSnapshot(string filePath) { - if (!_fileSystem.file_exists(filePath)) return null; + if (!_fileSystem.FileExists(filePath)) return null; - return _xmlService.deserialize(filePath); + return _xmlService.Deserialize(filePath); } - private string get_package_install_directory(PackageResult packageResult) + private string GetPackageInstallDirectory(PackageResult packageResult) { if (packageResult == null) return null; var installDirectory = packageResult.InstallLocation; - return package_install_directory_is_correct(installDirectory, logMessage => packageResult.Messages.Add(new ResultMessage(ResultType.Warn, logMessage))) ? installDirectory : null; + return PackageInstallDirectoryIsCorrect(installDirectory, logMessage => packageResult.Messages.Add(new ResultMessage(ResultType.Warn, logMessage))) ? installDirectory : null; } - private bool package_install_directory_is_correct(string directory, Action errorAction = null) + private bool PackageInstallDirectoryIsCorrect(string directory, Action errorAction = null) { - if (directory.to_string().is_equal_to(string.Empty)) return false; + if (directory.ToStringSafe().IsEqualTo(string.Empty)) return false; - if (directory.is_equal_to(ApplicationParameters.InstallLocation) || directory.is_equal_to(ApplicationParameters.PackagesLocation)) + if (directory.IsEqualTo(ApplicationParameters.InstallLocation) || directory.IsEqualTo(ApplicationParameters.PackagesLocation)) { - var logMessage = "Install location is not specific enough:{0} Erroneous install location captured as '{1}'".format_with(Environment.NewLine, directory); + var logMessage = "Install location is not specific enough:{0} Erroneous install location captured as '{1}'".FormatWith(Environment.NewLine, directory); if (errorAction != null) errorAction.Invoke(logMessage); this.Log().Error(logMessage); return false; @@ -70,69 +71,193 @@ private bool package_install_directory_is_correct(string directory, Action "Capturing package files in '{0}'".format_with(directory)); + this.Log().Debug(() => "Capturing package files in '{0}'".FormatWith(directory)); //gather all files in the folder - var files = _fileSystem.get_files(directory, pattern: "*.*", option: SearchOption.AllDirectories); - foreach (string file in files.or_empty_list_if_null().Where(f => !f.EndsWith(ApplicationParameters.PackagePendingFileName))) + var files = _fileSystem.GetFiles(directory, pattern: "*.*", option: SearchOption.AllDirectories); + foreach (string file in files.OrEmpty().Where(f => !f.EndsWith(ApplicationParameters.PackagePendingFileName))) { - packageFiles.Files.Add(get_package_file(file)); + packageFiles.Files.Add(GetPackageFile(file)); } return packageFiles; } - public PackageFile get_package_file(string file) + public PackageFile GetPackageFile(string file) { - var hash = _hashProvider.hash_file(file); - this.Log().Debug(ChocolateyLoggers.Verbose, () => " Found '{0}'{1} with checksum '{2}'".format_with(file, Environment.NewLine, hash)); + var hash = _hashProvider.ComputeFileHash(file); + this.Log().Debug(ChocolateyLoggers.Verbose, () => " Found '{0}'{1} with checksum '{2}'".FormatWith(file, Environment.NewLine, hash)); return new PackageFile { Path = file, Checksum = hash }; } + + public bool MovePackageUsingBackupStrategy(string sourceFolder, string destinationFolder, bool restoreSource) + { + var errored = false; + + try + { + _fileSystem.DeleteDirectoryChecked(destinationFolder, recursive: true, overrideAttributes: true, isSilent: true); + } + catch (Exception ex) + { + // We will ignore any exceptions that occur. + this.Log().Debug("Failed to delete directory '{0}', will retry for each file.{0} {1}", destinationFolder, Environment.NewLine, ex.Message); + + foreach (var file in _fileSystem.GetFiles(destinationFolder, pattern: "*", option: SearchOption.AllDirectories)) + { + try + { + _fileSystem.DeleteFile(file); + } + catch (Exception fex) + { + this.Log().Warn("Unable to delete file '{0}' This may cause further executions to fail.{1} {2}", file, Environment.NewLine, fex.Message); + } + } + } + + _fileSystem.EnsureDirectoryExists(_fileSystem.GetDirectoryName(destinationFolder)); + + if (_fileSystem.DirectoryExists(sourceFolder)) + { + this.Log().Debug("Moving {0} to {1}", sourceFolder, destinationFolder); + + try + { + _fileSystem.MoveDirectory(sourceFolder, destinationFolder, useFileMoveFallback: false, isSilent: true); + } + catch (Exception ex) + { + this.Log().Warn("Unable to move directory '{0}':{1} {2}", sourceFolder, Environment.NewLine, ex.Message); + this.Log().Warn("Retrying by moving individual files"); + + foreach (var file in _fileSystem.GetFiles(sourceFolder, pattern: "*", option: SearchOption.AllDirectories)) + { + var newLocation = file.Replace(sourceFolder, destinationFolder); + if (_fileSystem.FileExists(newLocation)) + { + continue; + } + + try + { + _fileSystem.MoveFile(file, newLocation, isSilent: true); + } + catch (Exception e) + { + this.Log().Warn("Unable to move file '{0}':{1} {2}", file, Environment.NewLine, e.Message); + + try + { + _fileSystem.CopyFile(file, newLocation, overwriteExisting: true); + } + catch (Exception cex) + { + errored = true; + this.Log().Error("Unable to copy file '{0}':{1} {2}", file, Environment.NewLine, cex.Message); + } + } + } + } + + if (!restoreSource) + { + return errored; + } + + try + { + _fileSystem.CopyDirectory(destinationFolder, sourceFolder, overwriteExisting: true, isSilent: true); + } + catch (AggregateException ex) + { + errored = true; + this.Log().Error("Error during package reset phase:{0} {1}", Environment.NewLine, string.Join(Environment.NewLine + " ", ex.InnerExceptions)); + } + catch (Exception ex) + { + errored = true; + this.Log().Error("Error during package reset phase:{0} {1}", Environment.NewLine, ex.Message); + } + } + + return errored; + } + +#pragma warning disable IDE1006 + [Obsolete("This overload is deprecated and will be removed in v3.")] + public PackageFiles read_from_file(string filePath) + => ReadPackageSnapshot(filePath); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public void save_to_file(PackageFiles snapshot, string filePath) + => SavePackageSnapshot(snapshot, filePath); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public void ensure_compatible_file_attributes(PackageResult packageResult, ChocolateyConfiguration config) + => EnsureCompatibleFileAttributes(packageResult, config); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public void ensure_compatible_file_attributes(string directory, ChocolateyConfiguration config) + => EnsureCompatibleFileAttributes(directory, config); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public PackageFiles capture_package_files(PackageResult packageResult, ChocolateyConfiguration config) + => CaptureSnapshot(packageResult, config); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public PackageFiles capture_package_files(string directory, ChocolateyConfiguration config) + => CaptureSnapshot(directory, config); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public PackageFile get_package_file(string file) + => GetPackageFile(file); +#pragma warning restore IDE1006 } } diff --git a/src/chocolatey/infrastructure.app/services/IAutomaticUninstallerService.cs b/src/chocolatey/infrastructure.app/services/IAutomaticUninstallerService.cs index 95edd0ca53..32478d7698 100644 --- a/src/chocolatey/infrastructure.app/services/IAutomaticUninstallerService.cs +++ b/src/chocolatey/infrastructure.app/services/IAutomaticUninstallerService.cs @@ -19,6 +19,7 @@ namespace chocolatey.infrastructure.app.services using configuration; using domain; using results; + using System; /// /// The automagic uninstaller service @@ -30,7 +31,7 @@ public interface IAutomaticUninstallerService /// /// The package result. /// The configuration. - void run(PackageResult packageResult, ChocolateyConfiguration config); + void Run(PackageResult packageResult, ChocolateyConfiguration config); /// /// Removes one app (registry value) based on config and records any messaging in a package result. @@ -39,6 +40,14 @@ public interface IAutomaticUninstallerService /// The configuration. /// The package result. /// The package cache location. + void Remove(RegistryApplicationKey key, ChocolateyConfiguration config, PackageResult packageResult, string packageCacheLocation); + +#pragma warning disable IDE1006 + [Obsolete("This overload is deprecated and will be removed in v3.")] + void run(PackageResult packageResult, ChocolateyConfiguration config); + + [Obsolete("This overload is deprecated and will be removed in v3.")] void remove(RegistryApplicationKey key, ChocolateyConfiguration config, PackageResult packageResult, string packageCacheLocation); +#pragma warning restore IDE1006 } } diff --git a/src/chocolatey/infrastructure.app/services/IChocolateyConfigSettingsService.cs b/src/chocolatey/infrastructure.app/services/IChocolateyConfigSettingsService.cs index 9218c274a2..0a844bd9ce 100644 --- a/src/chocolatey/infrastructure.app/services/IChocolateyConfigSettingsService.cs +++ b/src/chocolatey/infrastructure.app/services/IChocolateyConfigSettingsService.cs @@ -22,21 +22,57 @@ namespace chocolatey.infrastructure.app.services public interface IChocolateyConfigSettingsService { + void DryRun(ChocolateyConfiguration configuration); + IEnumerable ListSources(ChocolateyConfiguration configuration); + void AddSource(ChocolateyConfiguration configuration); + void RemoveSource(ChocolateyConfiguration configuration); + void DisableSource(ChocolateyConfiguration configuration); + void EnableSource(ChocolateyConfiguration configuration); + void ListFeatures(ChocolateyConfiguration configuration); + void GetFeature(ChocolateyConfiguration configuration); + void DisableFeature(ChocolateyConfiguration configuration); + void EnableFeature(ChocolateyConfiguration configuration); + string GetApiKey(ChocolateyConfiguration configuration, Action keyAction); + void SetApiKey(ChocolateyConfiguration configuration); + void RemoveApiKey(ChocolateyConfiguration configuration); + void ListConfig(ChocolateyConfiguration configuration); + void GetConfig(ChocolateyConfiguration configuration); + void SetConfig(ChocolateyConfiguration configuration); + void UnsetConfig(ChocolateyConfiguration configuration); + +#pragma warning disable IDE1006 + [Obsolete("This overload is deprecated and will be removed in v3.")] void noop(ChocolateyConfiguration configuration); + [Obsolete("This overload is deprecated and will be removed in v3.")] IEnumerable source_list(ChocolateyConfiguration configuration); + [Obsolete("This overload is deprecated and will be removed in v3.")] void source_add(ChocolateyConfiguration configuration); + [Obsolete("This overload is deprecated and will be removed in v3.")] void source_remove(ChocolateyConfiguration configuration); + [Obsolete("This overload is deprecated and will be removed in v3.")] void source_disable(ChocolateyConfiguration configuration); + [Obsolete("This overload is deprecated and will be removed in v3.")] void source_enable(ChocolateyConfiguration configuration); + [Obsolete("This overload is deprecated and will be removed in v3.")] void feature_list(ChocolateyConfiguration configuration); + [Obsolete("This overload is deprecated and will be removed in v3.")] void feature_disable(ChocolateyConfiguration configuration); + [Obsolete("This overload is deprecated and will be removed in v3.")] void feature_enable(ChocolateyConfiguration configuration); + [Obsolete("This overload is deprecated and will be removed in v3.")] string get_api_key(ChocolateyConfiguration configuration, Action keyAction); + [Obsolete("This overload is deprecated and will be removed in v3.")] void set_api_key(ChocolateyConfiguration configuration); + [Obsolete("This overload is deprecated and will be removed in v3.")] void remove_api_key(ChocolateyConfiguration configuration); + [Obsolete("This overload is deprecated and will be removed in v3.")] void config_list(ChocolateyConfiguration configuration); + [Obsolete("This overload is deprecated and will be removed in v3.")] void config_get(ChocolateyConfiguration configuration); + [Obsolete("This overload is deprecated and will be removed in v3.")] void config_set(ChocolateyConfiguration configuration); + [Obsolete("This overload is deprecated and will be removed in v3.")] void config_unset(ChocolateyConfiguration configuration); +#pragma warning restore IDE1006 } } diff --git a/src/chocolatey/infrastructure.app/services/IChocolateyPackageInformationService.cs b/src/chocolatey/infrastructure.app/services/IChocolateyPackageInformationService.cs index fde9d53323..2e51aa0612 100644 --- a/src/chocolatey/infrastructure.app/services/IChocolateyPackageInformationService.cs +++ b/src/chocolatey/infrastructure.app/services/IChocolateyPackageInformationService.cs @@ -18,11 +18,21 @@ namespace chocolatey.infrastructure.app.services { using domain; using NuGet.Packaging; + using System; public interface IChocolateyPackageInformationService { + ChocolateyPackageInformation Get(IPackageMetadata package); + void Save(ChocolateyPackageInformation packageInformation); + void Remove(IPackageMetadata package); + +#pragma warning disable IDE1006 + [Obsolete("This overload is deprecated and will be removed in v3.")] ChocolateyPackageInformation get_package_information(IPackageMetadata package); + [Obsolete("This overload is deprecated and will be removed in v3.")] void save_package_information(ChocolateyPackageInformation packageInformation); + [Obsolete("This overload is deprecated and will be removed in v3.")] void remove_package_information(IPackageMetadata package); +#pragma warning restore IDE1006 } } diff --git a/src/chocolatey/infrastructure.app/services/IChocolateyPackageService.cs b/src/chocolatey/infrastructure.app/services/IChocolateyPackageService.cs index 0ec67a9b4c..fbb84d7902 100644 --- a/src/chocolatey/infrastructure.app/services/IChocolateyPackageService.cs +++ b/src/chocolatey/infrastructure.app/services/IChocolateyPackageService.cs @@ -16,6 +16,7 @@ namespace chocolatey.infrastructure.app.services { + using System; using System.Collections.Concurrent; using System.Collections.Generic; using configuration; @@ -26,106 +27,131 @@ namespace chocolatey.infrastructure.app.services /// public interface IChocolateyPackageService { - - /// - /// Ensures the application that controls a source is installed - /// - /// The configuration. - void ensure_source_app_installed(ChocolateyConfiguration config); - /// /// Retrieves the count of items that meet the search criteria. /// /// /// - int count_run(ChocolateyConfiguration config); + int Count(ChocolateyConfiguration config); /// /// Run list in noop mode /// /// The configuration. - void list_noop(ChocolateyConfiguration config); + void ListDryRun(ChocolateyConfiguration config); /// /// Lists/searches for packages that meet a search criteria /// /// The configuration. /// - IEnumerable list_run(ChocolateyConfiguration config); + IEnumerable List(ChocolateyConfiguration config); /// /// Run pack in noop mode /// /// The configuration. - void pack_noop(ChocolateyConfiguration config); + void PackDryRun(ChocolateyConfiguration config); /// /// Compiles a package /// /// The configuration. - void pack_run(ChocolateyConfiguration config); + void Pack(ChocolateyConfiguration config); /// /// Run push in noop mode /// /// The configuration. - void push_noop(ChocolateyConfiguration config); + void PushDryRun(ChocolateyConfiguration config); /// /// Pushes packages to remote feeds. /// /// The configuration. - void push_run(ChocolateyConfiguration config); + void Push(ChocolateyConfiguration config); /// /// Run install in noop mode /// /// The configuration. - void install_noop(ChocolateyConfiguration config); + void InstallDryRun(ChocolateyConfiguration config); /// /// Installs packages /// /// The configuration. /// results of installs - ConcurrentDictionary install_run(ChocolateyConfiguration config); + ConcurrentDictionary Install(ChocolateyConfiguration config); /// /// Run outdated in noop mode /// /// The configuration. - void outdated_noop(ChocolateyConfiguration config); + void OutdatedDryRun(ChocolateyConfiguration config); /// /// Determines all packages that are out of date /// /// The configuration. - void outdated_run(ChocolateyConfiguration config); + void Outdated(ChocolateyConfiguration config); /// /// Run upgrade in noop mode /// /// The configuration. - void upgrade_noop(ChocolateyConfiguration config); + void UpgradeDryRun(ChocolateyConfiguration config); /// /// Upgrades packages /// /// The configuration. /// results of upgrades - ConcurrentDictionary upgrade_run(ChocolateyConfiguration config); + ConcurrentDictionary Upgrade(ChocolateyConfiguration config); /// /// Run uninstall in noop mode /// /// The configuration. - void uninstall_noop(ChocolateyConfiguration config); + void UninstallDryRun(ChocolateyConfiguration config); /// /// Uninstalls packages /// /// The configuration. /// results of upgrades + ConcurrentDictionary Uninstall(ChocolateyConfiguration config); + + +#pragma warning disable IDE1006 + [Obsolete("This overload is deprecated and will be removed in v3.")] + int count_run(ChocolateyConfiguration config); + [Obsolete("This overload is deprecated and will be removed in v3.")] + void list_noop(ChocolateyConfiguration config); + [Obsolete("This overload is deprecated and will be removed in v3.")] + void pack_noop(ChocolateyConfiguration config); + [Obsolete("This overload is deprecated and will be removed in v3.")] + void pack_run(ChocolateyConfiguration config); + [Obsolete("This overload is deprecated and will be removed in v3.")] + void push_noop(ChocolateyConfiguration config); + [Obsolete("This overload is deprecated and will be removed in v3.")] + void push_run(ChocolateyConfiguration config); + [Obsolete("This overload is deprecated and will be removed in v3.")] + void install_noop(ChocolateyConfiguration config); + [Obsolete("This overload is deprecated and will be removed in v3.")] + ConcurrentDictionary install_run(ChocolateyConfiguration config); + [Obsolete("This overload is deprecated and will be removed in v3.")] + void outdated_noop(ChocolateyConfiguration config); + [Obsolete("This overload is deprecated and will be removed in v3.")] + void outdated_run(ChocolateyConfiguration config); + [Obsolete("This overload is deprecated and will be removed in v3.")] + void upgrade_noop(ChocolateyConfiguration config); + [Obsolete("This overload is deprecated and will be removed in v3.")] + ConcurrentDictionary upgrade_run(ChocolateyConfiguration config); + [Obsolete("This overload is deprecated and will be removed in v3.")] + void uninstall_noop(ChocolateyConfiguration config); + [Obsolete("This overload is deprecated and will be removed in v3.")] ConcurrentDictionary uninstall_run(ChocolateyConfiguration config); +#pragma warning restore IDE1006 } } diff --git a/src/chocolatey/infrastructure.app/services/IConfigTransformService.cs b/src/chocolatey/infrastructure.app/services/IConfigTransformService.cs index 9e03878918..e877c23f11 100644 --- a/src/chocolatey/infrastructure.app/services/IConfigTransformService.cs +++ b/src/chocolatey/infrastructure.app/services/IConfigTransformService.cs @@ -18,6 +18,7 @@ namespace chocolatey.infrastructure.app.services { using configuration; using results; + using System; public interface IConfigTransformService { @@ -26,6 +27,11 @@ public interface IConfigTransformService ///
/// The package result. /// The configuration. + void Run(PackageResult packageResult, ChocolateyConfiguration config); + +#pragma warning disable IDE1006 + [Obsolete("This overload is deprecated and will be removed in v3.")] void run(PackageResult packageResult, ChocolateyConfiguration config); +#pragma warning restore IDE1006 } } diff --git a/src/chocolatey/infrastructure.app/services/IFilesService.cs b/src/chocolatey/infrastructure.app/services/IFilesService.cs index 6dea6ac8b1..1d25ff6b87 100644 --- a/src/chocolatey/infrastructure.app/services/IFilesService.cs +++ b/src/chocolatey/infrastructure.app/services/IFilesService.cs @@ -16,6 +16,7 @@ namespace chocolatey.infrastructure.app.services { + using System; using configuration; using domain; using results; @@ -30,28 +31,28 @@ public interface IFilesService /// /// The filepath. /// PackageFiles with entries based on the file if it exists, otherwise null - PackageFiles read_from_file(string filepath); + PackageFiles ReadPackageSnapshot(string filepath); /// /// Saves the files snapshot to the specified file path. /// /// The snapshot. /// The file path. - void save_to_file(PackageFiles snapshot, string filePath); + void SavePackageSnapshot(PackageFiles snapshot, string filePath); /// /// Ensure that the package files have compatible file attributes (e.g. no readonly). /// /// The package result. /// The configuration. - void ensure_compatible_file_attributes(PackageResult packageResult, ChocolateyConfiguration config); + void EnsureCompatibleFileAttributes(PackageResult packageResult, ChocolateyConfiguration config); /// /// Ensure that files in a directory have compatible file attributes (e.g. no readonly). /// /// The directory. /// The configuration. - void ensure_compatible_file_attributes(string directory, ChocolateyConfiguration config); + void EnsureCompatibleFileAttributes(string directory, ChocolateyConfiguration config); /// /// Captures the snapshot of the package files @@ -59,7 +60,7 @@ public interface IFilesService /// The package result. /// The configuration. /// PackageFiles with entries based on the install location of the package. - PackageFiles capture_package_files(PackageResult packageResult, ChocolateyConfiguration config); + PackageFiles CaptureSnapshot(PackageResult packageResult, ChocolateyConfiguration config); /// /// Captures the snapshot of the package files @@ -67,13 +68,32 @@ public interface IFilesService /// The directory. /// The configuration. /// PackageFiles with entries based on the install location of the package. - PackageFiles capture_package_files(string directory, ChocolateyConfiguration config); + PackageFiles CaptureSnapshot(string directory, ChocolateyConfiguration config); /// /// Gets a PackageFile from the filepath /// /// The file. /// PackageFile object + PackageFile GetPackageFile(string file); + + bool MovePackageUsingBackupStrategy(string sourceFolder, string destinationFolder, bool restoreSource); + +#pragma warning disable IDE1006 + [Obsolete("This overload is deprecated and will be removed in v3.")] + PackageFiles read_from_file(string filepath); + [Obsolete("This overload is deprecated and will be removed in v3.")] + void save_to_file(PackageFiles snapshot, string filePath); + [Obsolete("This overload is deprecated and will be removed in v3.")] + void ensure_compatible_file_attributes(PackageResult packageResult, ChocolateyConfiguration config); + [Obsolete("This overload is deprecated and will be removed in v3.")] + void ensure_compatible_file_attributes(string directory, ChocolateyConfiguration config); + [Obsolete("This overload is deprecated and will be removed in v3.")] + PackageFiles capture_package_files(PackageResult packageResult, ChocolateyConfiguration config); + [Obsolete("This overload is deprecated and will be removed in v3.")] + PackageFiles capture_package_files(string directory, ChocolateyConfiguration config); + [Obsolete("This overload is deprecated and will be removed in v3.")] PackageFile get_package_file(string file); +#pragma warning restore IDE1006 } } diff --git a/src/chocolatey/infrastructure.app/services/INugetService.cs b/src/chocolatey/infrastructure.app/services/INugetService.cs index 22e9debea0..a11e5571ef 100644 --- a/src/chocolatey/infrastructure.app/services/INugetService.cs +++ b/src/chocolatey/infrastructure.app/services/INugetService.cs @@ -16,6 +16,7 @@ namespace chocolatey.infrastructure.app.services { + using System; using System.Collections.Concurrent; using System.Collections.Generic; using configuration; @@ -27,43 +28,60 @@ public interface INugetService : ISourceRunner /// Get outdated packages /// /// The configuration. - ConcurrentDictionary get_outdated(ChocolateyConfiguration config); + ConcurrentDictionary GetOutdated(ChocolateyConfiguration config); /// /// Run pack in noop mode. /// /// The configuration. - void pack_noop(ChocolateyConfiguration config); + void PackDryRun(ChocolateyConfiguration config); /// /// Packages up a nuspec into a compiled nupkg. /// /// The configuration. - void pack_run(ChocolateyConfiguration config); + void Pack(ChocolateyConfiguration config); /// /// Push_noops the specified configuration. /// /// The configuration. - void push_noop(ChocolateyConfiguration config); + void PushDryRun(ChocolateyConfiguration config); /// /// Push_runs the specified configuration. /// /// The configuration. - void push_run(ChocolateyConfiguration config); + void Push(ChocolateyConfiguration config); /// /// Remove the rollback directory for a package if it exists /// /// Name of the package. - void remove_rollback_directory_if_exists(string packageName); + void EnsureBackupDirectoryRemoved(string packageName); /// /// Get all installed packages /// /// The configuration + IEnumerable GetInstalledPackages(ChocolateyConfiguration config); + +#pragma warning disable IDE1006 + [Obsolete("This overload is deprecated and will be removed in v3.")] + ConcurrentDictionary get_outdated(ChocolateyConfiguration config); + [Obsolete("This overload is deprecated and will be removed in v3.")] + void pack_noop(ChocolateyConfiguration config); + [Obsolete("This overload is deprecated and will be removed in v3.")] + void pack_run(ChocolateyConfiguration config); + [Obsolete("This overload is deprecated and will be removed in v3.")] + void push_noop(ChocolateyConfiguration config); + [Obsolete("This overload is deprecated and will be removed in v3.")] + void push_run(ChocolateyConfiguration config); + [Obsolete("This overload is deprecated and will be removed in v3.")] + void remove_rollback_directory_if_exists(string packageName); + [Obsolete("This overload is deprecated and will be removed in v3.")] IEnumerable get_all_installed_packages(ChocolateyConfiguration config); +#pragma warning restore IDE1006 } } diff --git a/src/chocolatey/infrastructure.app/services/IPendingRebootService.cs b/src/chocolatey/infrastructure.app/services/IPendingRebootService.cs index f1bfaedbe1..61ef8a2576 100644 --- a/src/chocolatey/infrastructure.app/services/IPendingRebootService.cs +++ b/src/chocolatey/infrastructure.app/services/IPendingRebootService.cs @@ -17,6 +17,7 @@ namespace chocolatey.infrastructure.app.services { using configuration; + using System; /// /// Test to see if there are any known situations that require @@ -25,6 +26,11 @@ namespace chocolatey.infrastructure.app.services /// true if reboot is required; otherwise false. public interface IPendingRebootService { + bool IsRebootPending(ChocolateyConfiguration config); + +#pragma warning disable IDE1006 + [Obsolete("This overload is deprecated and will be removed in v3.")] bool is_pending_reboot(ChocolateyConfiguration config); +#pragma warning restore IDE1006 } } diff --git a/src/chocolatey/infrastructure.app/services/IPowershellService.cs b/src/chocolatey/infrastructure.app/services/IPowershellService.cs index 2f1e2564a8..320e1f91f8 100644 --- a/src/chocolatey/infrastructure.app/services/IPowershellService.cs +++ b/src/chocolatey/infrastructure.app/services/IPowershellService.cs @@ -30,7 +30,7 @@ public interface IPowershellService /// Noops the specified package install. /// /// The package result. - void install_noop(PackageResult packageResult); + void InstallDryRun(PackageResult packageResult); /// /// Installs the specified package. @@ -38,13 +38,13 @@ public interface IPowershellService /// The configuration /// The package result. /// true if the chocolateyInstall.ps1 was found, even if it has failures - bool install(ChocolateyConfiguration configuration, PackageResult packageResult); + bool Install(ChocolateyConfiguration configuration, PackageResult packageResult); /// /// Noops the specified package uninstall. /// /// The package result. - void uninstall_noop(PackageResult packageResult); + void UninstallDryRun(PackageResult packageResult); /// /// Uninstalls the specified package. @@ -52,13 +52,13 @@ public interface IPowershellService /// The configuration /// The package result. /// true if the chocolateyUninstall.ps1 was found, even if it has failures - bool uninstall(ChocolateyConfiguration configuration, PackageResult packageResult); + bool Uninstall(ChocolateyConfiguration configuration, PackageResult packageResult); /// /// Noops the specified package before modify operation. /// /// The package result. - void before_modify_noop(PackageResult packageResult); + void BeforeModifyDryRun(PackageResult packageResult); /// /// Runs any before modification script on the specified package. @@ -66,13 +66,29 @@ public interface IPowershellService /// The configuration /// The package result. /// true if the chocolateyBeforeModify.ps1 was found, even if it has failures - bool before_modify(ChocolateyConfiguration configuration, PackageResult packageResult); + bool BeforeModify(ChocolateyConfiguration configuration, PackageResult packageResult); - void prepare_powershell_environment(IPackageSearchMetadata package, ChocolateyConfiguration configuration, string packageDirectory); + void PreparePowerShellEnvironment(IPackageSearchMetadata package, ChocolateyConfiguration configuration, string packageDirectory); - [Obsolete("This version of running the powershell host do not support running additional hooks. Use the appropriate overload instead")] - PowerShellExecutionResults run_host(ChocolateyConfiguration config, string chocoPowerShellScript, Action additionalActionsBeforeScript); + PowerShellExecutionResults RunHost(ChocolateyConfiguration config, string chocoPowerShellScript, Action additionalActionsBeforeScript, IEnumerable hookPreScriptPathList, IEnumerable hookPostScriptPathList); +#pragma warning disable IDE1006 + [Obsolete("This overload is deprecated and will be removed in v3.")] + void install_noop(PackageResult packageResult); + [Obsolete("This overload is deprecated and will be removed in v3.")] + bool install(ChocolateyConfiguration configuration, PackageResult packageResult); + [Obsolete("This overload is deprecated and will be removed in v3.")] + void uninstall_noop(PackageResult packageResult); + [Obsolete("This overload is deprecated and will be removed in v3.")] + bool uninstall(ChocolateyConfiguration configuration, PackageResult packageResult); + [Obsolete("This overload is deprecated and will be removed in v3.")] + void before_modify_noop(PackageResult packageResult); + [Obsolete("This overload is deprecated and will be removed in v3.")] + bool before_modify(ChocolateyConfiguration configuration, PackageResult packageResult); + [Obsolete("This overload is deprecated and will be removed in v3.")] + void prepare_powershell_environment(IPackageSearchMetadata package, ChocolateyConfiguration configuration, string packageDirectory); + [Obsolete("This overload is deprecated and will be removed in v3.")] PowerShellExecutionResults run_host(ChocolateyConfiguration config, string chocoPowerShellScript, Action additionalActionsBeforeScript, IEnumerable hookPreScriptPathList, IEnumerable hookPostScriptPathList); +#pragma warning restore IDE1006 } } diff --git a/src/chocolatey/infrastructure.app/services/IRegistryService.cs b/src/chocolatey/infrastructure.app/services/IRegistryService.cs index 68f0157cab..3439979bc9 100644 --- a/src/chocolatey/infrastructure.app/services/IRegistryService.cs +++ b/src/chocolatey/infrastructure.app/services/IRegistryService.cs @@ -16,6 +16,7 @@ namespace chocolatey.infrastructure.app.services { + using System; using System.Collections.Generic; using domain; using Microsoft.Win32; @@ -23,14 +24,35 @@ namespace chocolatey.infrastructure.app.services public interface IRegistryService { + Registry GetInstallerKeys(); + Registry GetInstallerKeysChanged(Registry before, Registry after); + IEnumerable GetEnvironmentValues(); + IEnumerable GetNewAndModifiedEnvironmentValues(IEnumerable before, IEnumerable after); + IEnumerable GetRemovedEnvironmentValues(IEnumerable before, IEnumerable after); + void SaveRegistrySnapshot(Registry snapshot, string filePath); + Registry ReadRegistrySnapshot(string filePath); + bool InstallerKeyExists(string keyPath); + RegistryKey GetKey(RegistryHive hive, string subKeyPath); + +#pragma warning disable IDE1006 + [Obsolete("This overload is deprecated and will be removed in v3.")] Registry get_installer_keys(); + [Obsolete("This overload is deprecated and will be removed in v3.")] Registry get_installer_key_differences(Registry before, Registry after); + [Obsolete("This overload is deprecated and will be removed in v3.")] IEnumerable get_environment_values(); + [Obsolete("This overload is deprecated and will be removed in v3.")] IEnumerable get_added_changed_environment_differences(IEnumerable before, IEnumerable after); + [Obsolete("This overload is deprecated and will be removed in v3.")] IEnumerable get_removed_environment_differences(IEnumerable before, IEnumerable after); + [Obsolete("This overload is deprecated and will be removed in v3.")] void save_to_file(Registry snapshot, string filePath); + [Obsolete("This overload is deprecated and will be removed in v3.")] Registry read_from_file(string filePath); + [Obsolete("This overload is deprecated and will be removed in v3.")] bool installer_value_exists(string keyPath, string value); + [Obsolete("This overload is deprecated and will be removed in v3.")] RegistryKey get_key(RegistryHive hive, string subKeyPath); +#pragma warning restore IDE1006 } } diff --git a/src/chocolatey/infrastructure.app/services/IShimGenerationService.cs b/src/chocolatey/infrastructure.app/services/IShimGenerationService.cs index 4577c0af73..b14ccc8840 100644 --- a/src/chocolatey/infrastructure.app/services/IShimGenerationService.cs +++ b/src/chocolatey/infrastructure.app/services/IShimGenerationService.cs @@ -18,21 +18,29 @@ namespace chocolatey.infrastructure.app.services { using configuration; using results; + using System; public interface IShimGenerationService { /// - /// Installs shimgens for the package + /// Installs shims for the package /// /// The configuration. /// The package result. - void install(ChocolateyConfiguration configuration, PackageResult packageResult); + void Install(ChocolateyConfiguration configuration, PackageResult packageResult); /// - /// Uninstalls shimgens for the package + /// Uninstalls shims for the package /// /// The configuration. /// The package result. + void Uninstall(ChocolateyConfiguration configuration, PackageResult packageResult); + +#pragma warning disable IDE1006 + [Obsolete("This overload is deprecated and will be removed in v3.")] + void install(ChocolateyConfiguration configuration, PackageResult packageResult); + [Obsolete("This overload is deprecated and will be removed in v3.")] void uninstall(ChocolateyConfiguration configuration, PackageResult packageResult); +#pragma warning restore IDE1006 } } diff --git a/src/chocolatey/infrastructure.app/services/ISourceRunner.cs b/src/chocolatey/infrastructure.app/services/ISourceRunner.cs index fb90f5e7bc..44fb09014e 100644 --- a/src/chocolatey/infrastructure.app/services/ISourceRunner.cs +++ b/src/chocolatey/infrastructure.app/services/ISourceRunner.cs @@ -25,97 +25,164 @@ namespace chocolatey.infrastructure.app.services using results; [MultiService] - public interface ISourceRunner + [Obsolete("This interface is deprecated and will be removed in v3.")] + public interface ISourceRunner : IBootstrappableSourceRunner, ICountSourceRunner, IListSourceRunner, IInstallSourceRunner, IUpgradeSourceRunner, IUninstallSourceRunner + { +#pragma warning disable IDE1006 + [Obsolete("This overload is deprecated and will be removed in v3.")] + void ensure_source_app_installed(ChocolateyConfiguration config, Action ensureAction); + [Obsolete("This overload is deprecated and will be removed in v3.")] + int count_run(ChocolateyConfiguration config); + [Obsolete("This overload is deprecated and will be removed in v3.")] + void list_noop(ChocolateyConfiguration config); + [Obsolete("This overload is deprecated and will be removed in v3.")] + IEnumerable list_run(ChocolateyConfiguration config); + [Obsolete("This overload is deprecated and will be removed in v3.")] + void install_noop(ChocolateyConfiguration config, Action continueAction); + [Obsolete("This overload is deprecated and will be removed in v3.")] + ConcurrentDictionary install_run(ChocolateyConfiguration config, Action continueAction); + [Obsolete("This overload is deprecated and will be removed in v3.")] + ConcurrentDictionary install_run(ChocolateyConfiguration config, Action continueAction, Action beforeModifyAction); + [Obsolete("This overload is deprecated and will be removed in v3.")] + ConcurrentDictionary upgrade_noop(ChocolateyConfiguration config, Action continueAction); + [Obsolete("This overload is deprecated and will be removed in v3.")] + ConcurrentDictionary upgrade_run(ChocolateyConfiguration config, Action continueAction, Action beforeUpgradeAction = null); + [Obsolete("This overload is deprecated and will be removed in v3.")] + void uninstall_noop(ChocolateyConfiguration config, Action continueAction); + [Obsolete("This overload is deprecated and will be removed in v3.")] + ConcurrentDictionary uninstall_run(ChocolateyConfiguration config, Action continueAction, Action beforeUninstallAction = null); +#pragma warning restore IDE1006 + } + + public interface IAlternativeSourceRunner { /// - /// Gets the source type the source runner implements + /// Gets the source type the source runner implements. /// /// /// The type of the source. /// string SourceType { get; } + } + public interface IBootstrappableSourceRunner : IAlternativeSourceRunner + { /// - /// Ensures the application that controls a source is installed + /// Ensures the application that controls a source is installed. /// /// The configuration. - /// The action to continue with as part of the install - void ensure_source_app_installed(ChocolateyConfiguration config, Action ensureAction); + /// The action to continue with as part of the install. + void EnsureSourceAppInstalled(ChocolateyConfiguration config, Action ensureAction); + } + public interface ICountSourceRunner : IAlternativeSourceRunner + { /// - /// Retrieve the listed packages from the source feed cout + /// Retrieve the count of the listed packages from the source. /// /// The configuration. - /// Packages count - int count_run(ChocolateyConfiguration config); + /// Packages count. + int Count(ChocolateyConfiguration config); + } + public interface IListSourceRunner : IAlternativeSourceRunner + { /// - /// Run list in noop mode + /// Run list in noop mode. /// /// The configuration. - void list_noop(ChocolateyConfiguration config); + void ListDryRun(ChocolateyConfiguration config); /// - /// Lists/searches for packages from the source feed + /// Lists for packages from the source feed. /// /// The configuration. /// - IEnumerable list_run(ChocolateyConfiguration config); + IEnumerable List(ChocolateyConfiguration config); + } + + /// + /// This interface is a 'marker' type that indicates that the List action on the current source runner + /// supports searching for specific packages. + /// + public interface ISearchableSourceRunner : IAlternativeSourceRunner + { + /// + /// Run search in noop mode. + /// + /// The configuration. + void SearchDryRun(ChocolateyConfiguration config); + + /// + /// Searches for packages from the source feed. + /// + /// The configuration. + /// + IEnumerable Search(ChocolateyConfiguration config); + } + public interface IInstallSourceRunner : IAlternativeSourceRunner + { /// - /// Run install in noop mode + /// Run install in noop mode. /// /// The configuration. /// The action to continue with for each noop test install. - void install_noop(ChocolateyConfiguration config, Action continueAction); + void InstallDryRun(ChocolateyConfiguration config, Action continueAction); /// - /// Installs packages from the source feed + /// Installs packages from the source feed. /// /// The configuration. /// The action to continue with when install is successful. - /// results of installs - ConcurrentDictionary install_run(ChocolateyConfiguration config, Action continueAction); + /// Results of installs. + ConcurrentDictionary Install(ChocolateyConfiguration config, Action continueAction); /// - /// Installs packages from the source feed + /// Installs packages from the source feed. /// /// The configuration. /// The action to continue with when install is successful. /// The action (if any) to run on any currently installed package dependencies before triggering the install or updating those dependencies. - /// results of installs - ConcurrentDictionary install_run(ChocolateyConfiguration config, Action continueAction, Action beforeModifyAction); + /// Results of installs. + ConcurrentDictionary Install(ChocolateyConfiguration config, Action continueAction, Action beforeModifyAction); + } + public interface IUpgradeSourceRunner : IAlternativeSourceRunner + { /// - /// Run upgrade in noop mode + /// Run upgrade in noop mode. /// /// The configuration. /// The action to continue with for each noop test upgrade. - ConcurrentDictionary upgrade_noop(ChocolateyConfiguration config, Action continueAction); + ConcurrentDictionary UpgradeDryRun(ChocolateyConfiguration config, Action continueAction); /// - /// Upgrades packages from NuGet related feeds + /// Upgrades packages from NuGet related feeds. /// /// The configuration. /// The action to continue with when upgrade is successful. /// The action (if any) to run on any currently installed package or its dependencies before triggering the upgrade. - /// results of installs - ConcurrentDictionary upgrade_run(ChocolateyConfiguration config, Action continueAction, Action beforeUpgradeAction = null); + /// Results of upgrades. + ConcurrentDictionary Upgrade(ChocolateyConfiguration config, Action continueAction, Action beforeUpgradeAction = null); + } + public interface IUninstallSourceRunner : IAlternativeSourceRunner + { /// - /// Run uninstall in noop mode + /// Run uninstall in noop mode. /// /// The configuration. /// The action to continue with for each noop test upgrade. - void uninstall_noop(ChocolateyConfiguration config, Action continueAction); + void UninstallDryRun(ChocolateyConfiguration config, Action continueAction); /// - /// Uninstalls packages from NuGet related feeds + /// Uninstalls packages from NuGet related feeds. /// /// The configuration. /// The action to continue with when upgrade is successful. /// The action (if any) to run on any currently installed package before triggering the uninstall. - /// results of installs - ConcurrentDictionary uninstall_run(ChocolateyConfiguration config, Action continueAction, Action beforeUninstallAction = null); + /// Results of uninstalls. + ConcurrentDictionary Uninstall(ChocolateyConfiguration config, Action continueAction, Action beforeUninstallAction = null); } } diff --git a/src/chocolatey/infrastructure.app/services/ITemplateService.cs b/src/chocolatey/infrastructure.app/services/ITemplateService.cs index 217aafa8e1..3f8400cd15 100644 --- a/src/chocolatey/infrastructure.app/services/ITemplateService.cs +++ b/src/chocolatey/infrastructure.app/services/ITemplateService.cs @@ -17,12 +17,24 @@ namespace chocolatey.infrastructure.app.services { using configuration; + using System; public interface ITemplateService { + void GenerateDryRun(ChocolateyConfiguration configuration); + void Generate(ChocolateyConfiguration configuration); + void ListDryRun(ChocolateyConfiguration configuration); + void List(ChocolateyConfiguration configuration); + +#pragma warning disable IDE1006 + [Obsolete("This overload is deprecated and will be removed in v3.")] void generate_noop(ChocolateyConfiguration configuration); + [Obsolete("This overload is deprecated and will be removed in v3.")] void generate(ChocolateyConfiguration configuration); + [Obsolete("This overload is deprecated and will be removed in v3.")] void list_noop(ChocolateyConfiguration configuration); + [Obsolete("This overload is deprecated and will be removed in v3.")] void list(ChocolateyConfiguration configuration); +#pragma warning restore IDE1006 } } diff --git a/src/chocolatey/infrastructure.app/services/NugetService.cs b/src/chocolatey/infrastructure.app/services/NugetService.cs index 94020704dd..0349148085 100644 --- a/src/chocolatey/infrastructure.app/services/NugetService.cs +++ b/src/chocolatey/infrastructure.app/services/NugetService.cs @@ -45,13 +45,10 @@ namespace chocolatey.infrastructure.app.services using NuGet.Packaging; using NuGet.Packaging.Core; using NuGet.Protocol; - using NuGet.Packaging.Signing; using NuGet.ProjectManagement; using NuGet.Protocol.Core.Types; using NuGet.Resolver; using NuGet.Versioning; - using System.Xml.Linq; - using infrastructure.configuration; using chocolatey.infrastructure.services; //todo: #2575 - this monolith is too large. Refactor once test coverage is up. @@ -64,11 +61,11 @@ public class NugetService : INugetService private readonly IFilesService _filesService; private readonly IRuleService _ruleService; //private readonly PackageDownloader _packageDownloader; - private readonly Lazy datetime_initializer = new Lazy(() => new DateTime()); + private readonly Lazy _datetime = new Lazy(() => new DateTime()); private IDateTime DateTime { - get { return datetime_initializer.Value; } + get { return _datetime.Value; } } internal const string InstallWithFilePathDeprecationMessage = @" @@ -86,6 +83,7 @@ install them. /// The nuget logger /// Package information service /// The files service + /// The rule service public NugetService( IFileSystem fileSystem, ILogger nugetLogger, @@ -102,22 +100,22 @@ public NugetService( public string SourceType { - get { return SourceTypes.NORMAL; } + get { return SourceTypes.Normal; } } - public void ensure_source_app_installed(ChocolateyConfiguration config, Action ensureAction) + public void EnsureSourceAppInstalled(ChocolateyConfiguration config, Action ensureAction) { // nothing to do. Nuget.Core is already part of Chocolatey } - public virtual int count_run(ChocolateyConfiguration config) + public virtual int Count(ChocolateyConfiguration config) { if (config.ListCommand.LocalOnly) { config.Sources = ApplicationParameters.PackagesLocation; config.Prerelease = true; - if (!_fileSystem.directory_exists(ApplicationParameters.PackagesLocation)) + if (!_fileSystem.DirectoryExists(ApplicationParameters.PackagesLocation)) { return 0; } @@ -134,16 +132,16 @@ public virtual int count_run(ChocolateyConfiguration config) } } - public virtual void list_noop(ChocolateyConfiguration config) + public virtual void ListDryRun(ChocolateyConfiguration config) { - this.Log().Info("{0} would have searched for '{1}' against the following source(s) :\"{2}\"".format_with( + this.Log().Info("{0} would have searched for '{1}' against the following source(s) :\"{2}\"".FormatWith( ApplicationParameters.Name, config.Input, config.Sources )); } - public virtual IEnumerable list_run(ChocolateyConfiguration config) + public virtual IEnumerable List(ChocolateyConfiguration config) { int count = 0; @@ -157,13 +155,29 @@ public virtual IEnumerable list_run(ChocolateyConfiguration confi config.Prerelease = true; config.ListCommand.IncludeVersionOverrides = true; - if (!_fileSystem.directory_exists(ApplicationParameters.PackagesLocation)) + if (!_fileSystem.DirectoryExists(ApplicationParameters.PackagesLocation)) { yield break; } } - if (config.RegularOutput) this.Log().Debug(() => "Running list with the following filter = '{0}'".format_with(config.Input)); + if ((config.ListCommand.ApprovedOnly || config.ListCommand.DownloadCacheAvailable || config.ListCommand.NotBroken) && config.RegularOutput) + { + // This warning has been added here, to provide context to the user, and a follow up issue + + // has been added here: https://github.com/chocolatey/choco/issues/3139 to address the actual + // issue that causes this warning to be required. + this.Log().Warn(@" +Starting vith Chocolatey CLI v2.0.0, changes have been made to the +`choco search` command which means that filtering of packages using the +`--approved-only`, `--download-cache`, and `--not-broken` options are +now performed within Chocolatey CLI. Previously, this filtering would +have been performed on the Chocolatey Community Repository. As a result, +it is possible that incomplete package lists are returned from a command +that uses these options."); + } + + if (config.RegularOutput) this.Log().Debug(() => "Running list with the following filter = '{0}'".FormatWith(config.Input)); if (config.RegularOutput) this.Log().Debug(ChocolateyLoggers.Verbose, () => "--- Start of List ---"); foreach (var pkg in NugetList.GetPackages(config, _nugetLogger, _fileSystem)) { @@ -174,7 +188,7 @@ public virtual IEnumerable list_run(ChocolateyConfiguration confi if (package.PackagePath != null && !string.IsNullOrWhiteSpace(package.PackagePath)) { packageLocalMetadata = new ChocolateyPackageMetadata(package.PackagePath, _fileSystem); - packageInstallLocation = _fileSystem.get_directory_name(package.PackagePath); + packageInstallLocation = _fileSystem.GetDirectoryName(package.PackagePath); } else { @@ -183,7 +197,7 @@ public virtual IEnumerable list_run(ChocolateyConfiguration confi if (config.ListCommand.LocalOnly && packageLocalMetadata != null) { - var packageInfo = _packageInfoService.get_package_information(packageLocalMetadata); + var packageInfo = _packageInfoService.Get(packageLocalMetadata); if (config.ListCommand.IncludeVersionOverrides) { if (packageInfo.VersionOverride != null) @@ -200,8 +214,8 @@ public virtual IEnumerable list_run(ChocolateyConfiguration confi if (config.RegularOutput) { - this.Log().Info(logger, () => "{0}{1}".format_with(package.Identity.Id, config.ListCommand.IdOnly ? string.Empty : " {0}{1}{2}{3}".format_with( - packageLocalMetadata != null ? packageLocalMetadata.Version.to_full_string() : package.Identity.Version.to_full_string(), + this.Log().Info(logger, () => "{0}{1}".FormatWith(package.Identity.Id, config.ListCommand.IdOnly ? string.Empty : " {0}{1}{2}{3}".FormatWith( + packageLocalMetadata != null ? packageLocalMetadata.Version.ToFullStringChecked() : package.Identity.Version.ToFullStringChecked(), package.IsApproved ? " [Approved]" : string.Empty, package.IsDownloadCacheAvailable ? " Downloads cached for licensed users" : string.Empty, package.PackageTestResultStatus == "Failing" && package.IsDownloadCacheAvailable ? " - Possibly broken for FOSS users (due to original download location changes by vendor)" : package.PackageTestResultStatus == "Failing" ? " - Possibly broken" : string.Empty @@ -217,52 +231,52 @@ Package url{6} Software Site: {10} Software License: {11}{12}{13}{14}{15}{16} Description: {17}{18} -".format_with( - package.Title.escape_curly_braces(), +".FormatWith( + package.Title.EscapeCurlyBraces(), package.Published.GetValueOrDefault().UtcDateTime.ToShortDateString(), - package.IsApproved ? "{0} Package approved {1} on {2}.".format_with( + package.IsApproved ? "{0} Package approved {1} on {2}.".FormatWith( Environment.NewLine, string.IsNullOrWhiteSpace(package.PackageReviewer) ? "as a trusted package" : "by " + package.PackageReviewer, package.PackageApprovedDate.GetValueOrDefault().ToString("MMM dd yyyy HH:mm:ss") ) : string.Empty, - string.IsNullOrWhiteSpace(package.PackageTestResultStatus) || package.PackageTestResultStatus.is_equal_to("unknown") ? string.Empty : "{0} Package testing status: {1} on {2}.".format_with( + string.IsNullOrWhiteSpace(package.PackageTestResultStatus) || package.PackageTestResultStatus.IsEqualTo("unknown") ? string.Empty : "{0} Package testing status: {1} on {2}.".FormatWith( Environment.NewLine, package.PackageTestResultStatus, package.PackageValidationResultDate.GetValueOrDefault().ToString("MMM dd yyyy HH:mm:ss") ), - (package.DownloadCount == null || package.DownloadCount <= 0) ? "n/a" : package.DownloadCount.to_string(), - (package.VersionDownloadCount == null || package.VersionDownloadCount <= 0) ? "n/a" : package.VersionDownloadCount.to_string(), + (package.DownloadCount == null || package.DownloadCount <= 0) ? "n/a" : package.DownloadCount.ToStringSafe(), + (package.VersionDownloadCount == null || package.VersionDownloadCount <= 0) ? "n/a" : package.VersionDownloadCount.ToStringSafe(), package.PackageDetailsUrl == null || string.IsNullOrWhiteSpace(package.PackageDetailsUrl.AbsoluteUri) ? string.Empty : " " + package.PackageDetailsUrl.AbsoluteUri, - !string.IsNullOrWhiteSpace(package.PackageSourceUrl.to_string()) - ? package.PackageSourceUrl.to_string() + !string.IsNullOrWhiteSpace(package.PackageSourceUrl.ToStringSafe()) + ? package.PackageSourceUrl.ToStringSafe() : "n/a", - string.IsNullOrWhiteSpace(package.PackageHash) ? string.Empty : "{0} Package Checksum: '{1}' ({2})".format_with( + string.IsNullOrWhiteSpace(package.PackageHash) ? string.Empty : "{0} Package Checksum: '{1}' ({2})".FormatWith( Environment.NewLine, package.PackageHash, package.PackageHashAlgorithm ), - package.Tags.trim_safe().escape_curly_braces(), - package.ProjectUrl != null ? package.ProjectUrl.to_string() : "n/a", - package.LicenseUrl != null && !string.IsNullOrWhiteSpace(package.LicenseUrl.to_string()) ? package.LicenseUrl.to_string() : "n/a", - !string.IsNullOrWhiteSpace(package.ProjectSourceUrl.to_string()) ? "{0} Software Source: {1}".format_with(Environment.NewLine, package.ProjectSourceUrl.to_string()) : string.Empty, - !string.IsNullOrWhiteSpace(package.DocsUrl.to_string()) ? "{0} Documentation: {1}".format_with(Environment.NewLine, package.DocsUrl.to_string()) : string.Empty, - !string.IsNullOrWhiteSpace(package.MailingListUrl.to_string()) ? "{0} Mailing List: {1}".format_with(Environment.NewLine, package.MailingListUrl.to_string()) : string.Empty, - !string.IsNullOrWhiteSpace(package.BugTrackerUrl.to_string()) ? "{0} Issues: {1}".format_with(Environment.NewLine, package.BugTrackerUrl.to_string()) : string.Empty, - package.Summary != null && !string.IsNullOrWhiteSpace(package.Summary.to_string()) ? "\r\n Summary: {0}".format_with(package.Summary.escape_curly_braces().to_string()) : string.Empty, - package.Description.escape_curly_braces().Replace("\n ", "\n").Replace("\n", "\n "), - !string.IsNullOrWhiteSpace(package.ReleaseNotes.to_string()) ? "{0} Release Notes: {1}".format_with(Environment.NewLine, package.ReleaseNotes.escape_curly_braces().Replace("\n ", "\n").Replace("\n", "\n ")) : string.Empty + package.Tags.TrimSafe().EscapeCurlyBraces(), + package.ProjectUrl != null ? package.ProjectUrl.ToStringSafe() : "n/a", + package.LicenseUrl != null && !string.IsNullOrWhiteSpace(package.LicenseUrl.ToStringSafe()) ? package.LicenseUrl.ToStringSafe() : "n/a", + !string.IsNullOrWhiteSpace(package.ProjectSourceUrl.ToStringSafe()) ? "{0} Software Source: {1}".FormatWith(Environment.NewLine, package.ProjectSourceUrl.ToStringSafe()) : string.Empty, + !string.IsNullOrWhiteSpace(package.DocsUrl.ToStringSafe()) ? "{0} Documentation: {1}".FormatWith(Environment.NewLine, package.DocsUrl.ToStringSafe()) : string.Empty, + !string.IsNullOrWhiteSpace(package.MailingListUrl.ToStringSafe()) ? "{0} Mailing List: {1}".FormatWith(Environment.NewLine, package.MailingListUrl.ToStringSafe()) : string.Empty, + !string.IsNullOrWhiteSpace(package.BugTrackerUrl.ToStringSafe()) ? "{0} Issues: {1}".FormatWith(Environment.NewLine, package.BugTrackerUrl.ToStringSafe()) : string.Empty, + package.Summary != null && !string.IsNullOrWhiteSpace(package.Summary.ToStringSafe()) ? "\r\n Summary: {0}".FormatWith(package.Summary.EscapeCurlyBraces().ToStringSafe()) : string.Empty, + package.Description.EscapeCurlyBraces().Replace("\n ", "\n").Replace("\n", "\n "), + !string.IsNullOrWhiteSpace(package.ReleaseNotes.ToStringSafe()) ? "{0} Release Notes: {1}".FormatWith(Environment.NewLine, package.ReleaseNotes.EscapeCurlyBraces().Replace("\n ", "\n").Replace("\n", "\n ")) : string.Empty )); } else { - this.Log().Info(logger, () => "{0}{1}".format_with(package.Identity.Id, config.ListCommand.IdOnly ? string.Empty : "|{0}".format_with(package.Identity.Version.to_full_string()))); + this.Log().Info(logger, () => "{0}{1}".FormatWith(package.Identity.Id, config.ListCommand.IdOnly ? string.Empty : "|{0}".FormatWith(package.Identity.Version.ToFullStringChecked()))); } } else { - this.Log().Debug(() => "{0}{1}".format_with(package.Identity.Id, config.ListCommand.IdOnly ? string.Empty : " {0}".format_with(package.Identity.Version.to_full_string()))); + this.Log().Debug(() => "{0}{1}".FormatWith(package.Identity.Id, config.ListCommand.IdOnly ? string.Empty : " {0}".FormatWith(package.Identity.Version.ToFullStringChecked()))); } count++; @@ -279,7 +293,7 @@ Package url{6} if (config.RegularOutput) this.Log().Debug(ChocolateyLoggers.Verbose, () => "--- End of List ---"); if (config.RegularOutput && !config.QuietOutput) { - this.Log().Warn(() => @"{0} packages {1}.".format_with(count, config.ListCommand.LocalOnly ? "installed" : "found")); + this.Log().Warn(() => @"{0} packages {1}.".FormatWith(count, config.ListCommand.LocalOnly ? "installed" : "found")); } config.Sources = sources; @@ -292,49 +306,49 @@ Package url{6} if (NugetList.ThresholdHit) { - this.Log().Warn(logType, "The threshold of {0:N0} packages per source has been met. Please refine your search, or specify a page to find any more results.".format_with(NugetList.LastPackageLimitUsed)); + this.Log().Warn(logType, "The threshold of {0:N0} packages per source has been met. Please refine your search, or specify a page to find any more results.".FormatWith(NugetList.LastPackageLimitUsed)); } else if (NugetList.LowerThresholdHit) { - this.Log().Warn(logType, "Over {0:N0} packages was found per source, there may be more packages available that was filtered out. Please refine your search, or specify a page to check for more packages.".format_with(NugetList.LastPackageLimitUsed * 0.9)); + this.Log().Warn(logType, "Over {0:N0} packages was found per source, there may be more packages available that was filtered out. Please refine your search, or specify a page to check for more packages.".FormatWith(NugetList.LastPackageLimitUsed * 0.9)); } } } - public void pack_noop(ChocolateyConfiguration config) + public void PackDryRun(ChocolateyConfiguration config) { - this.Log().Info("{0} would have searched for a nuspec file in \"{1}\" and attempted to compile it.".format_with( + this.Log().Info("{0} would have searched for a nuspec file in \"{1}\" and attempted to compile it.".FormatWith( ApplicationParameters.Name, - config.OutputDirectory ?? _fileSystem.get_current_directory() + config.OutputDirectory ?? _fileSystem.GetCurrentDirectory() )); } - public virtual string validate_and_return_package_file(ChocolateyConfiguration config, string extension) + public virtual string GetPackageFileOrThrow(ChocolateyConfiguration config, string extension) { Func getLocalFiles = (fileSystem) => { - var filesFound = fileSystem.get_files(fileSystem.get_current_directory(), "*" + extension).ToList().or_empty_list_if_null(); - Ensure.that(() => filesFound) - .meets((files) => files.Count() == 1, - (name, value) => { throw new FileNotFoundException("No {0} files (or more than 1) were found to build in '{1}'. Please specify the {0} file or try in a different directory.".format_with(extension, _fileSystem.get_current_directory())); }); + var filesFound = fileSystem.GetFiles(fileSystem.GetCurrentDirectory(), "*" + extension).ToList().OrEmpty(); + Ensure.That(() => filesFound) + .Meets((files) => files.Count() == 1, + (name, value) => { throw new FileNotFoundException("No {0} files (or more than 1) were found to build in '{1}'. Please specify the {0} file or try in a different directory.".FormatWith(extension, _fileSystem.GetCurrentDirectory())); }); return filesFound.FirstOrDefault(); }; string filePath = !string.IsNullOrWhiteSpace(config.Input) ? config.Input : getLocalFiles.Invoke(_fileSystem); - Ensure.that(() => filePath).meets((file) => _fileSystem.get_file_extension(file).is_equal_to(extension) && _fileSystem.file_exists(file), - (name, value) => { throw new ArgumentException("File specified is either not found or not a {0} file. '{1}'".format_with(extension, value)); }); + Ensure.That(() => filePath).Meets((file) => _fileSystem.GetFileExtension(file).IsEqualTo(extension) && _fileSystem.FileExists(file), + (name, value) => { throw new ArgumentException("File specified is either not found or not a {0} file. '{1}'".FormatWith(extension, value)); }); return filePath; } - public virtual void pack_run(ChocolateyConfiguration config) + public virtual void Pack(ChocolateyConfiguration config) { - var nuspecFilePath = validate_and_return_package_file(config, PackagingConstants.ManifestExtension); - validate_nuspec(nuspecFilePath, config); + var nuspecFilePath = GetPackageFileOrThrow(config, PackagingConstants.ManifestExtension); + ValidateNuspec(nuspecFilePath, config); - var nuspecDirectory = _fileSystem.get_full_path(_fileSystem.get_directory_name(nuspecFilePath)); - if (string.IsNullOrWhiteSpace(nuspecDirectory)) nuspecDirectory = _fileSystem.get_current_directory(); + var nuspecDirectory = _fileSystem.GetFullPath(_fileSystem.GetDirectoryName(nuspecFilePath)); + if (string.IsNullOrWhiteSpace(nuspecDirectory)) nuspecDirectory = _fileSystem.GetCurrentDirectory(); // Use case-insensitive properties like "nuget pack". var properties = new Dictionary(StringComparer.OrdinalIgnoreCase); @@ -342,7 +356,7 @@ public virtual void pack_run(ChocolateyConfiguration config) // Add any other properties passed to the pack command overriding any present. foreach (var property in config.PackCommand.Properties) { - this.Log().Debug(() => "Setting property '{0}': {1}".format_with( + this.Log().Debug(() => "Setting property '{0}': {1}".FormatWith( property.Key, property.Value)); @@ -352,7 +366,7 @@ public virtual void pack_run(ChocolateyConfiguration config) // Set the version property if the flag is set if (!string.IsNullOrWhiteSpace(config.Version)) { - this.Log().Debug(() => "Setting property 'version': {0}".format_with( + this.Log().Debug(() => "Setting property 'version': {0}".FormatWith( config.Version)); properties["version"] = config.Version; @@ -371,14 +385,14 @@ public virtual void pack_run(ChocolateyConfiguration config) builder.Version = new NuGetVersion(config.Version); } - string outputFile = builder.Id + "." + builder.Version.to_normalized_string() + NuGetConstants.PackageExtension; - string outputFolder = config.OutputDirectory ?? _fileSystem.get_current_directory(); - string outputPath = _fileSystem.combine_paths(outputFolder, outputFile); + string outputFile = builder.Id + "." + builder.Version.ToNormalizedStringChecked() + NuGetConstants.PackageExtension; + string outputFolder = config.OutputDirectory ?? _fileSystem.GetCurrentDirectory(); + string outputPath = _fileSystem.CombinePaths(outputFolder, outputFile); config.Sources = outputFolder; - this.Log().Info(config.QuietOutput ? ChocolateyLoggers.LogFileOnly : ChocolateyLoggers.Normal, () => "Attempting to build package from '{0}'.".format_with(_fileSystem.get_file_name(nuspecFilePath))); - _fileSystem.create_directory_if_not_exists(outputFolder); + this.Log().Info(config.QuietOutput ? ChocolateyLoggers.LogFileOnly : ChocolateyLoggers.Normal, () => "Attempting to build package from '{0}'.".FormatWith(_fileSystem.GetFileName(nuspecFilePath))); + _fileSystem.EnsureDirectoryExists(outputFolder); var createdPackage = NugetPack.BuildPackage(builder, _fileSystem, outputPath); // package.Validate().Any(v => v.Level == PackageIssueLevel.Error) @@ -392,24 +406,24 @@ public virtual void pack_run(ChocolateyConfiguration config) // AnalyzePackage(package); //} - this.Log().Info(config.QuietOutput ? ChocolateyLoggers.LogFileOnly : ChocolateyLoggers.Important, () => "Successfully created package '{0}'".format_with(outputPath)); + this.Log().Info(config.QuietOutput ? ChocolateyLoggers.LogFileOnly : ChocolateyLoggers.Important, () => "Successfully created package '{0}'".FormatWith(outputPath)); } - public void push_noop(ChocolateyConfiguration config) + public void PushDryRun(ChocolateyConfiguration config) { - string nupkgFilePath = validate_and_return_package_file(config, NuGetConstants.PackageExtension); - this.Log().Info(() => "Would have attempted to push '{0}' to source '{1}'.".format_with(_fileSystem.get_file_name(nupkgFilePath), config.Sources)); + string nupkgFilePath = GetPackageFileOrThrow(config, NuGetConstants.PackageExtension); + this.Log().Info(() => "Would have attempted to push '{0}' to source '{1}'.".FormatWith(_fileSystem.GetFileName(nupkgFilePath), config.Sources)); } - public virtual void push_run(ChocolateyConfiguration config) + public virtual void Push(ChocolateyConfiguration config) { - string nupkgFilePath = validate_and_return_package_file(config, NuGetConstants.PackageExtension); - string nupkgFileName = _fileSystem.get_file_name(nupkgFilePath); - if (config.RegularOutput) this.Log().Info(() => "Attempting to push {0} to {1}".format_with(nupkgFileName, config.Sources)); + string nupkgFilePath = GetPackageFileOrThrow(config, NuGetConstants.PackageExtension); + string nupkgFileName = _fileSystem.GetFileName(nupkgFilePath); + if (config.RegularOutput) this.Log().Info(() => "Attempting to push {0} to {1}".FormatWith(nupkgFileName, config.Sources)); - NugetPush.push_package(config, _fileSystem.get_full_path(nupkgFilePath), _nugetLogger, nupkgFileName, _fileSystem); + NugetPush.PushPackage(config, _fileSystem.GetFullPath(nupkgFilePath), _nugetLogger, nupkgFileName, _fileSystem); - if (config.RegularOutput && (config.Sources.is_equal_to(ApplicationParameters.ChocolateyCommunityFeedPushSource) || config.Sources.is_equal_to(ApplicationParameters.ChocolateyCommunityFeedPushSourceOld))) + if (config.RegularOutput && (config.Sources.IsEqualTo(ApplicationParameters.ChocolateyCommunityFeedPushSource) || config.Sources.IsEqualTo(ApplicationParameters.ChocolateyCommunityFeedPushSourceOld))) { this.Log().Warn(ChocolateyLoggers.Important, () => @" @@ -434,36 +448,36 @@ moderation at chocolatey dot org are not being sent to your spam/junk } } - public void install_noop(ChocolateyConfiguration config, Action continueAction) + public void InstallDryRun(ChocolateyConfiguration config, Action continueAction) { //todo: #2576 noop should see if packages are already installed and adjust message, amiright?! - this.Log().Info("{0} would have used NuGet to install packages (if they are not already installed):{1}{2}".format_with( + this.Log().Info("{0} would have used NuGet to install packages (if they are not already installed):{1}{2}".FormatWith( ApplicationParameters.Name, Environment.NewLine, config.PackageNames )); - var tempInstallsLocation = _fileSystem.combine_paths(_fileSystem.get_temp_path(), ApplicationParameters.Name, "TempInstalls_" + DateTime.Now.ToString("yyyyMMdd_HHmmss_ffff")); - _fileSystem.create_directory_if_not_exists(tempInstallsLocation); + var tempInstallsLocation = _fileSystem.CombinePaths(_fileSystem.GetTempPath(), ApplicationParameters.Name, "TempInstalls_" + DateTime.Now.ToString("yyyyMMdd_HHmmss_ffff")); + _fileSystem.EnsureDirectoryExists(tempInstallsLocation); var installLocation = ApplicationParameters.PackagesLocation; ApplicationParameters.PackagesLocation = tempInstallsLocation; - install_run(config, continueAction); + Install(config, continueAction); - _fileSystem.delete_directory(tempInstallsLocation, recursive: true); + _fileSystem.DeleteDirectory(tempInstallsLocation, recursive: true); ApplicationParameters.PackagesLocation = installLocation; } - public virtual ConcurrentDictionary install_run(ChocolateyConfiguration config, Action continueAction) + public virtual ConcurrentDictionary Install(ChocolateyConfiguration config, Action continueAction) { - return install_run(config, continueAction, beforeModifyAction: null); + return Install(config, continueAction, beforeModifyAction: null); } - public virtual ConcurrentDictionary install_run(ChocolateyConfiguration config, Action continueAction, Action beforeModifyAction) + public virtual ConcurrentDictionary Install(ChocolateyConfiguration config, Action continueAction, Action beforeModifyAction) { - _fileSystem.create_directory_if_not_exists(ApplicationParameters.PackagesLocation); + _fileSystem.EnsureDirectoryExists(ApplicationParameters.PackagesLocation); var packageResultsToReturn = new ConcurrentDictionary(StringComparer.InvariantCultureIgnoreCase); //todo: #23 handle all @@ -473,12 +487,13 @@ public virtual ConcurrentDictionary install_run(Chocolate var sourceCacheContext = new ChocolateySourceCacheContext(config); var remoteRepositories = NugetCommon.GetRemoteRepositories(config, _nugetLogger, _fileSystem); + var remoteEndpoints = NugetCommon.GetRepositoryResources(remoteRepositories); var localRepositorySource = NugetCommon.GetLocalRepository(); var pathResolver = NugetCommon.GetPathResolver(_fileSystem); var nugetProject = new FolderNuGetProject(ApplicationParameters.PackagesLocation, pathResolver, NuGetFramework.AnyFramework); var projectContext = new ChocolateyNuGetProjectContext(config, _nugetLogger); - IList packageNames = config.PackageNames.Split(new[] { ApplicationParameters.PackageNamesSeparator }, StringSplitOptions.RemoveEmptyEntries).or_empty_list_if_null().ToList(); + IList packageNames = config.PackageNames.Split(new[] { ApplicationParameters.PackageNamesSeparator }, StringSplitOptions.RemoveEmptyEntries).OrEmpty().ToList(); if (packageNames.Count == 1) { var packageName = packageNames.DefaultIfEmpty(string.Empty).FirstOrDefault(); @@ -490,20 +505,20 @@ public virtual ConcurrentDictionary install_run(Chocolate this.Log().Debug("Updating source and package name to handle *.nupkg or *.nuspec file."); packageNames.Clear(); - config.Sources = _fileSystem.get_directory_name(_fileSystem.get_full_path(packageName)); + config.Sources = _fileSystem.GetDirectoryName(_fileSystem.GetFullPath(packageName)); if (packageName.EndsWith(PackagingConstants.ManifestExtension)) { - packageNames.Add(_fileSystem.get_file_name_without_extension(packageName)); + packageNames.Add(_fileSystem.GetFilenameWithoutExtension(packageName)); this.Log().Debug("Building nuspec file prior to install."); config.Input = packageName; // build package - pack_run(config); + Pack(config); } else { - using (var packageFile = new PackageArchiveReader(_fileSystem.get_full_path(packageName))) + using (var packageFile = new PackageArchiveReader(_fileSystem.GetFullPath(packageName))) { version = packageFile.NuspecReader.GetVersion(); packageNames.Add(packageFile.NuspecReader.GetId()); @@ -515,36 +530,36 @@ public virtual ConcurrentDictionary install_run(Chocolate // this is when someone points the source directly at a nupkg // e.g. -source c:\somelocation\somewhere\packagename.nupkg - if (config.Sources.to_string().EndsWith(NuGetConstants.PackageExtension)) + if (config.Sources.ToStringSafe().EndsWith(NuGetConstants.PackageExtension)) { - config.Sources = _fileSystem.get_directory_name(_fileSystem.get_full_path(config.Sources)); + config.Sources = _fileSystem.GetDirectoryName(_fileSystem.GetFullPath(config.Sources)); } - config.start_backup(); + config.CreateBackup(); - foreach (string packageName in packageNames.or_empty_list_if_null()) + foreach (string packageName in packageNames.OrEmpty()) { // We need to ensure we are using a clean configuration file // before we start reading it. - config.reset_config(); + config.RevertChanges(); - var allLocalPackages = get_all_installed_packages(config).ToList(); + var allLocalPackages = GetInstalledPackages(config).ToList(); var packagesToInstall = new List(); var packagesToUninstall = new HashSet(); var sourcePackageDependencyInfos = new HashSet(PackageIdentityComparer.Default); var localPackageToRemoveDependencyInfos = new HashSet(PackageIdentityComparer.Default); - var installedPackage = allLocalPackages.FirstOrDefault(p => p.Name.Equals(packageName)); + var installedPackage = allLocalPackages.FirstOrDefault(p => p.Name.IsEqualTo(packageName)); - if (Platform.get_platform() != PlatformType.Windows && !packageName.EndsWith(".template")) + if (Platform.GetPlatform() != PlatformType.Windows && !packageName.EndsWith(".template")) { - string logMessage = "{0} is not a supported package on non-Windows systems.{1}Only template packages are currently supported.".format_with(packageName, Environment.NewLine); + string logMessage = "{0} is not a supported package on non-Windows systems.{1}Only template packages are currently supported.".FormatWith(packageName, Environment.NewLine); this.Log().Warn(ChocolateyLoggers.Important, logMessage); } if (installedPackage != null && (version == null || version == installedPackage.PackageMetadata.Version) && !config.Force) { - string logMessage = "{0} v{1} already installed.{2} Use --force to reinstall, specify a version to install, or try upgrade.".format_with(installedPackage.Name, installedPackage.Version, Environment.NewLine); + string logMessage = "{0} v{1} already installed.{2} Use --force to reinstall, specify a version to install, or try upgrade.".FormatWith(installedPackage.Name, installedPackage.Version, Environment.NewLine); var nullResult = packageResultsToReturn.GetOrAdd(packageName, installedPackage); nullResult.Messages.Add(new ResultMessage(ResultType.Warn, logMessage)); nullResult.Messages.Add(new ResultMessage(ResultType.Inconclusive, logMessage)); @@ -557,7 +572,7 @@ public virtual ConcurrentDictionary install_run(Chocolate if (installedPackage != null && (version == null || version == installedPackage.PackageMetadata.Version) && config.Force) { this.Log().Warn(ChocolateyLoggers.Important, () => @"{0} v{1} already installed. Forcing reinstall of version '{1}'. - Please use upgrade if you meant to upgrade to a new version.".format_with(installedPackage.Name, installedPackage.Version)); + Please use upgrade if you meant to upgrade to a new version.".FormatWith(installedPackage.Name, installedPackage.Version)); //This is set to ensure the same package version is reinstalled latestPackageVersion = installedPackage.PackageMetadata.Version; @@ -565,7 +580,7 @@ public virtual ConcurrentDictionary install_run(Chocolate if (installedPackage != null && version != null && version < installedPackage.PackageMetadata.Version && !config.AllowDowngrade) { - string logMessage = "A newer version of {0} (v{1}) is already installed.{2} Use --allow-downgrade or --force to attempt to install older versions.".format_with(installedPackage.Name, installedPackage.Version, Environment.NewLine); + string logMessage = "A newer version of {0} (v{1}) is already installed.{2} Use --allow-downgrade or --force to attempt to install older versions.".FormatWith(installedPackage.Name, installedPackage.Version, Environment.NewLine); var nullResult = packageResultsToReturn.GetOrAdd(packageName, installedPackage); nullResult.Messages.Add(new ResultMessage(ResultType.Error, logMessage)); this.Log().Error(ChocolateyLoggers.Important, logMessage); @@ -577,7 +592,7 @@ public virtual ConcurrentDictionary install_run(Chocolate latestPackageVersion = version; } - var availablePackage = NugetList.find_package(packageName, config, _nugetLogger, sourceCacheContext, NugetCommon.GetRepositoryResource(remoteRepositories).ToList(), NugetCommon.GetRepositoryResource(remoteRepositories).ToList(), latestPackageVersion); + var availablePackage = NugetList.FindPackage(packageName, config, _nugetLogger, sourceCacheContext, remoteEndpoints, latestPackageVersion); if (availablePackage == null) { @@ -585,22 +600,21 @@ public virtual ConcurrentDictionary install_run(Chocolate Source(s): '{1}' NOTE: When you specify explicit sources, it overrides default sources. If the package version is a prerelease and you didn't specify `--pre`, - the package may not be found.{2}{3}".format_with(packageName, config.Sources, string.IsNullOrWhiteSpace(config.Version) + the package may not be found.{2}{3}".FormatWith(packageName, config.Sources, string.IsNullOrWhiteSpace(config.Version) ? String.Empty : @" Version was specified as '{0}'. It is possible that version - does not exist for '{1}' at the source specified.".format_with(config.Version, packageName), + does not exist for '{1}' at the source specified.".FormatWith(config.Version, packageName), @" Please see https://docs.chocolatey.org/en-us/troubleshooting for more assistance."); this.Log().Error(ChocolateyLoggers.Important, logMessage); - var noPkgResult = packageResultsToReturn.GetOrAdd(packageName, new PackageResult(packageName, version.to_full_string(), null)); + var noPkgResult = packageResultsToReturn.GetOrAdd(packageName, new PackageResult(packageName, version.ToFullStringChecked(), null)); noPkgResult.Messages.Add(new ResultMessage(ResultType.Error, logMessage)); continue; } - var dependencyResources = NugetCommon.GetRepositoryResource(remoteRepositories).ToList(); - NugetCommon.GetPackageDependencies(availablePackage.Identity, NuGetFramework.AnyFramework, sourceCacheContext, _nugetLogger, dependencyResources, sourcePackageDependencyInfos, new HashSet(), config).GetAwaiter().GetResult(); + NugetCommon.GetPackageDependencies(availablePackage.Identity, NuGetFramework.AnyFramework, sourceCacheContext, _nugetLogger, remoteEndpoints, sourcePackageDependencyInfos, new HashSet(), config).GetAwaiter().GetResult(); if (installedPackage != null && (installedPackage.PackageMetadata.Version == availablePackage.Identity.Version) && config.Force) { @@ -634,12 +648,12 @@ Version was specified as '{0}'. It is possible that version null, null)); - var removedSources = remove_pinned_source_dependencies(sourcePackageDependencyInfos, allLocalPackages); + var removedSources = RemovePinnedSourceDependencies(sourcePackageDependencyInfos, allLocalPackages); sourcePackageDependencyInfos.AddRange(localPackagesDependencyInfos); if (removedSources.Count > 0 && version == null) { - remove_invalid_dependencies_and_parents(availablePackage, removedSources, sourcePackageDependencyInfos, localPackagesDependencyInfos); + RemoveInvalidDependenciesAndParents(availablePackage, removedSources, sourcePackageDependencyInfos, localPackagesDependencyInfos); } var dependencyResolver = new PackageResolver(); @@ -652,7 +666,7 @@ Version was specified as '{0}'. It is possible that version // We exclude any installed package that does have a dependency that is missing, // except if that dependency is one of the targets the user requested. // If we do not exclude such packages, we will get a resolving exception later. - .Where(p => is_dependent_on_target_ids(p, targetIdsToInstall) || !has_missing_dependency(p, allLocalPackages)) + .Where(p => IsDependentOnTargetPackages(p, targetIdsToInstall) || !HasMissingDependency(p, allLocalPackages)) .Select(p => p.SearchMetadata.Identity) // If we're forcing dependencies, we only need to know which dependencies are installed locally, not the entire list of packages .Where(p => config.ForceDependencies @@ -686,13 +700,13 @@ Version was specified as '{0}'. It is possible that version try { nugetProject.DeletePackage(packageToUninstall.Identity, projectContext, CancellationToken.None).GetAwaiter().GetResult(); - remove_cache_for_package(config, packageToUninstall.PackageMetadata); + RemovePackageFromCache(config, packageToUninstall.PackageMetadata); } catch (Exception ex) { var forcedResult = packageResultsToReturn.GetOrAdd(packageToUninstall.Identity.Id, packageToUninstall); forcedResult.Messages.Add(new ResultMessage(ResultType.Note, "Removing old version")); - string logMessage = "{0}:{1} {2}".format_with("Unable to remove existing package", Environment.NewLine, ex.Message); + string logMessage = "{0}:{1} {2}".FormatWith("Unable to remove existing package", Environment.NewLine, ex.Message); this.Log().Warn(logMessage); forcedResult.Messages.Add(new ResultMessage(ResultType.Inconclusive, logMessage)); } @@ -718,7 +732,7 @@ Version was specified as '{0}'. It is possible that version } catch (NuGetResolverConstraintException ex) { - var logMessage = get_dependency_resolution_error_message(ex); + var logMessage = GetDependencyResolutionErrorMessage(ex); this.Log().Error(ChocolateyLoggers.Important, logMessage); foreach (var pkgMetadata in packagesToInstall) @@ -729,7 +743,7 @@ Version was specified as '{0}'. It is possible that version } catch (Exception ex) { - this.Log().Warn("Need to add specific handling for exception type {0}".format_with(ex.GetType().Name)); + this.Log().Warn("Need to add specific handling for exception type {0}".FormatWith(ex.GetType().Name)); this.Log().Warn(ex.Message); } } @@ -740,13 +754,11 @@ Version was specified as '{0}'. It is possible that version if (packageRemoteMetadata is null) { - packageRemoteMetadata = packageDependencyInfo - .Source - .GetResource() + var endpoint = NuGetEndpointResources.GetResourcesBySource(packageDependencyInfo.Source); + + packageRemoteMetadata = endpoint.PackageMetadataResource .GetMetadataAsync(packageDependencyInfo, sourceCacheContext, _nugetLogger, CancellationToken.None) .GetAwaiter().GetResult(); - - var resource = packageDependencyInfo.Source.GetResource(); } bool shouldAddForcedResultMessage = false; @@ -755,7 +767,7 @@ Version was specified as '{0}'. It is possible that version if (packageToUninstall != null) { shouldAddForcedResultMessage = true; - backup_and_before_modify(packageToUninstall, config, beforeModifyAction); + BackupAndRunBeforeModify(packageToUninstall, config, beforeModifyAction); packageToUninstall.InstallLocation = pathResolver.GetInstallPath(packageToUninstall.Identity); try { @@ -763,14 +775,14 @@ Version was specified as '{0}'. It is possible that version //But it does not throw or return false if it fails to delete something... var ableToDelete = nugetProject.DeletePackage(packageToUninstall.Identity, projectContext, CancellationToken.None, shouldDeleteDirectory: false).GetAwaiter().GetResult(); //So removing directly manually so as to throw if needed. - _fileSystem.delete_directory_if_exists(packageToUninstall.InstallLocation, true, true, true); - remove_cache_for_package(config, packageToUninstall.PackageMetadata); + _fileSystem.DeleteDirectoryChecked(packageToUninstall.InstallLocation, true, true, true); + RemovePackageFromCache(config, packageToUninstall.PackageMetadata); } catch (Exception ex) { var forcedResult = packageResultsToReturn.GetOrAdd(packageToUninstall.Name, packageToUninstall); forcedResult.Messages.Add(new ResultMessage(ResultType.Note, "Backing up and removing old version")); - string logMessage = "{0}:{1} {2}".format_with("Unable to remove existing package prior to forced reinstall", Environment.NewLine, ex.Message); + string logMessage = "{0}:{1} {2}".FormatWith("Unable to remove existing package prior to forced reinstall", Environment.NewLine, ex.Message); this.Log().Warn(logMessage); forcedResult.Messages.Add(new ResultMessage(ResultType.Inconclusive, logMessage)); forcedResult.Messages.Add(new ResultMessage(ResultType.Error, logMessage)); @@ -784,10 +796,10 @@ Version was specified as '{0}'. It is possible that version try { //TODO, do sanity check here. + var endpoint = NuGetEndpointResources.GetResourcesBySource(packageDependencyInfo.Source); + var downloadResource = endpoint.DownloadResource; - var downloadResource = packageDependencyInfo.Source.GetResource(); - - _fileSystem.delete_file(pathResolver.GetInstalledPackageFilePath(packageDependencyInfo)); + _fileSystem.DeleteFile(pathResolver.GetInstalledPackageFilePath(packageDependencyInfo)); ChocolateyProgressInfo.ShouldDisplayDownloadProgress = config.Features.ShowDownloadProgress; @@ -809,36 +821,36 @@ Version was specified as '{0}'. It is possible that version var installedPath = nugetProject.GetInstalledPath(packageDependencyInfo); - fix_nuspec_casing(availablePackage, installedPath); + NormalizeNuspecCasing(availablePackage, installedPath); - remove_nuget_cache_for_package(availablePackage); + RemovePackageFromNugetCache(availablePackage); var manifestPath = nugetProject.GetInstalledManifestFilePath(packageDependencyInfo); var packageMetadata = new ChocolateyPackageMetadata(manifestPath, _fileSystem); - this.Log().Info(ChocolateyLoggers.Important, "{0}{1} v{2}{3}{4}{5}".format_with( + this.Log().Info(ChocolateyLoggers.Important, "{0}{1} v{2}{3}{4}{5}".FormatWith( System.Environment.NewLine, packageMetadata.Id, - packageMetadata.Version.to_full_string(), + packageMetadata.Version.ToFullStringChecked(), config.Force ? " (forced)" : string.Empty, packageRemoteMetadata.IsApproved ? " [Approved]" : string.Empty, packageRemoteMetadata.PackageTestResultStatus == "Failing" && packageRemoteMetadata.IsDownloadCacheAvailable ? " - Likely broken for FOSS users (due to download location changes)" : packageRemoteMetadata.PackageTestResultStatus == "Failing" ? " - Possibly broken" : string.Empty )); - var packageResult = packageResultsToReturn.GetOrAdd(packageDependencyInfo.Id.to_lower(), new PackageResult(packageMetadata, packageRemoteMetadata, installedPath)); + var packageResult = packageResultsToReturn.GetOrAdd(packageDependencyInfo.Id.ToLowerSafe(), new PackageResult(packageMetadata, packageRemoteMetadata, installedPath)); if (shouldAddForcedResultMessage) packageResult.Messages.Add(new ResultMessage(ResultType.Note, "Backing up and removing old version")); packageResult.InstallLocation = installedPath; packageResult.Messages.Add(new ResultMessage(ResultType.Debug, ApplicationParameters.Messages.ContinueChocolateyAction)); - var elementsList = _ruleService.validate_rules(manifestPath) + var elementsList = _ruleService.ValidateRules(manifestPath) .Where(r => r.Severity == infrastructure.rules.RuleType.Error && !string.IsNullOrEmpty(r.Id)) - .where_unsupported_or_deprecated() - .Select(r => "{0}: {1}".format_with(r.Id, r.Message)) + .WhereUnsupportedOrDeprecated() + .Select(r => "{0}: {1}".FormatWith(r.Id, r.Message)) .ToList(); if (elementsList.Count > 0) { - var message = "Issues found with nuspec elements\r\n" + elementsList.join("\r\n"); + var message = "Issues found with nuspec elements\r\n" + elementsList.Join("\r\n"); packageResult.Messages.Add(new ResultMessage(ResultType.Warn, message)); } @@ -852,12 +864,12 @@ Version was specified as '{0}'. It is possible that version if (webException != null) { var response = webException.Response as HttpWebResponse; - if (response != null && !string.IsNullOrWhiteSpace(response.StatusDescription)) message += " {0}".format_with(response.StatusDescription); + if (response != null && !string.IsNullOrWhiteSpace(response.StatusDescription)) message += " {0}".FormatWith(response.StatusDescription); } - var logMessage = "{0} not installed. An error occurred during installation:{1} {2}".format_with(packageDependencyInfo.Id, Environment.NewLine, message); + var logMessage = "{0} not installed. An error occurred during installation:{1} {2}".FormatWith(packageDependencyInfo.Id, Environment.NewLine, message); this.Log().Error(ChocolateyLoggers.Important, logMessage); - var errorResult = packageResultsToReturn.GetOrAdd(packageDependencyInfo.Id, new PackageResult(packageDependencyInfo.Id, version.to_full_string(), null)); + var errorResult = packageResultsToReturn.GetOrAdd(packageDependencyInfo.Id, new PackageResult(packageDependencyInfo.Id, version.ToFullStringChecked(), null)); errorResult.Messages.Add(new ResultMessage(ResultType.Error, logMessage)); if (errorResult.ExitCode == 0) errorResult.ExitCode = 1; if (continueAction != null) continueAction.Invoke(errorResult, config); @@ -868,12 +880,12 @@ Version was specified as '{0}'. It is possible that version // Reset the configuration again once we are completely done with the processing of // configurations, and make sure that we are removing any backup that was created // as part of this run. - config.reset_config(removeBackup: true); + config.RevertChanges(removeBackup: true); return packageResultsToReturn; } - protected virtual string get_dependency_resolution_error_message(NuGetResolverConstraintException exception) + protected virtual string GetDependencyResolutionErrorMessage(NuGetResolverConstraintException exception) { if (exception.Message.StartsWith("Unable to resolve dependency '")) { @@ -906,44 +918,44 @@ protected virtual string get_dependency_resolution_error_message(NuGetResolverCo return $"Unable to resolve dependency '{invalidDependencyName}': {exception.Message}"; } - public virtual void remove_rollback_directory_if_exists(string packageName) + public virtual void EnsureBackupDirectoryRemoved(string packageName) { - var rollbackDirectory = _fileSystem.get_full_path(_fileSystem.combine_paths(ApplicationParameters.PackageBackupLocation, packageName)); - if (!_fileSystem.directory_exists(rollbackDirectory)) + var rollbackDirectory = _fileSystem.GetFullPath(_fileSystem.CombinePaths(ApplicationParameters.PackageBackupLocation, packageName)); + if (!_fileSystem.DirectoryExists(rollbackDirectory)) { //search for folder - var possibleRollbacks = _fileSystem.get_directories(ApplicationParameters.PackageBackupLocation, packageName + "*"); + var possibleRollbacks = _fileSystem.GetDirectories(ApplicationParameters.PackageBackupLocation, packageName + "*"); if (possibleRollbacks != null && possibleRollbacks.Count() != 0) { rollbackDirectory = possibleRollbacks.OrderByDescending(p => p).DefaultIfEmpty(string.Empty).FirstOrDefault(); } - rollbackDirectory = _fileSystem.get_full_path(rollbackDirectory); + rollbackDirectory = _fileSystem.GetFullPath(rollbackDirectory); } - if (string.IsNullOrWhiteSpace(rollbackDirectory) || !_fileSystem.directory_exists(rollbackDirectory)) return; - if (!rollbackDirectory.StartsWith(ApplicationParameters.PackageBackupLocation) || rollbackDirectory.is_equal_to(ApplicationParameters.PackageBackupLocation)) return; + if (string.IsNullOrWhiteSpace(rollbackDirectory) || !_fileSystem.DirectoryExists(rollbackDirectory)) return; + if (!rollbackDirectory.StartsWith(ApplicationParameters.PackageBackupLocation) || rollbackDirectory.IsEqualTo(ApplicationParameters.PackageBackupLocation)) return; - FaultTolerance.try_catch_with_logging_exception( - () => _fileSystem.delete_directory_if_exists(rollbackDirectory, recursive: true), - "Attempted to remove '{0}' but had an error:".format_with(rollbackDirectory), + FaultTolerance.TryCatchWithLoggingException( + () => _fileSystem.DeleteDirectoryChecked(rollbackDirectory, recursive: true), + "Attempted to remove '{0}' but had an error:".FormatWith(rollbackDirectory), logWarningInsteadOfError: true); } - public ConcurrentDictionary upgrade_noop(ChocolateyConfiguration config, Action continueAction) + public ConcurrentDictionary UpgradeDryRun(ChocolateyConfiguration config, Action continueAction) { config.Force = false; - return upgrade_run(config, continueAction, performAction: false); + return Upgrade(config, continueAction, performAction: false); } - public ConcurrentDictionary upgrade_run(ChocolateyConfiguration config, Action continueAction, Action beforeUpgradeAction = null) + public ConcurrentDictionary Upgrade(ChocolateyConfiguration config, Action continueAction, Action beforeUpgradeAction = null) { - return upgrade_run(config, continueAction, performAction: true, beforeUpgradeAction: beforeUpgradeAction); + return Upgrade(config, continueAction, performAction: true, beforeUpgradeAction: beforeUpgradeAction); } - public virtual ConcurrentDictionary upgrade_run(ChocolateyConfiguration config, Action continueAction, bool performAction, Action beforeUpgradeAction = null) + public virtual ConcurrentDictionary Upgrade(ChocolateyConfiguration config, Action continueAction, bool performAction, Action beforeUpgradeAction = null) { - _fileSystem.create_directory_if_not_exists(ApplicationParameters.PackagesLocation); + _fileSystem.EnsureDirectoryExists(ApplicationParameters.PackagesLocation); var packageResultsToReturn = new ConcurrentDictionary(StringComparer.InvariantCultureIgnoreCase); NuGetVersion version = !string.IsNullOrWhiteSpace(config.Version) ? NuGetVersion.Parse(config.Version) : null; @@ -952,35 +964,36 @@ public virtual ConcurrentDictionary upgrade_run(Chocolate var sourceCacheContext = new ChocolateySourceCacheContext(config); var remoteRepositories = NugetCommon.GetRemoteRepositories(config, _nugetLogger, _fileSystem); + var remoteEndpoints = NugetCommon.GetRepositoryResources(remoteRepositories); var localRepositorySource = NugetCommon.GetLocalRepository(); var projectContext = new ChocolateyNuGetProjectContext(config, _nugetLogger); var configIgnoreDependencies = config.IgnoreDependencies; - set_package_names_if_all_is_specified(config, () => { config.IgnoreDependencies = true; }); + SetPackageNamesIfAllSpecified(config, () => { config.IgnoreDependencies = true; }); config.IgnoreDependencies = configIgnoreDependencies; - config.start_backup(); + config.CreateBackup(); - foreach (string packageName in config.PackageNames.Split(new[] { ApplicationParameters.PackageNamesSeparator }, StringSplitOptions.RemoveEmptyEntries).or_empty_list_if_null()) + foreach (string packageName in config.PackageNames.Split(new[] { ApplicationParameters.PackageNamesSeparator }, StringSplitOptions.RemoveEmptyEntries).OrEmpty()) { // We need to ensure we are using a clean configuration file // before we start reading it. - config.reset_config(); + config.RevertChanges(); - var allLocalPackages = get_all_installed_packages(config).ToList(); - var installedPackage = allLocalPackages.FirstOrDefault(p => p.Name.Equals(packageName)); + var allLocalPackages = GetInstalledPackages(config).ToList(); + var installedPackage = allLocalPackages.FirstOrDefault(p => p.Name.IsEqualTo(packageName)); var packagesToInstall = new List(); var packagesToUninstall = new HashSet(); var sourcePackageDependencyInfos = new HashSet(PackageIdentityComparer.Default); var localPackageToRemoveDependencyInfos = new HashSet(PackageIdentityComparer.Default); - var dependencyResources = NugetCommon.GetRepositoryResource(remoteRepositories).ToList(); + var dependencyResources = remoteEndpoints.DependencyInfoResources(); var sourceDependencyCache = new HashSet(); if (installedPackage == null) { if (config.UpgradeCommand.FailOnNotInstalled) { - string failLogMessage = "{0} is not installed. Cannot upgrade a non-existent package.".format_with(packageName); + string failLogMessage = "{0} is not installed. Cannot upgrade a non-existent package.".FormatWith(packageName); var result = packageResultsToReturn.GetOrAdd(packageName, new PackageResult(packageName, null, null)); result.Messages.Add(new ResultMessage(ResultType.Error, failLogMessage)); if (config.RegularOutput) this.Log().Error(ChocolateyLoggers.Important, failLogMessage); @@ -990,7 +1003,7 @@ public virtual ConcurrentDictionary upgrade_run(Chocolate if (config.Features.SkipPackageUpgradesWhenNotInstalled) { - string warnLogMessage = "{0} is not installed and skip non-installed option selected. Skipping...".format_with(packageName); + string warnLogMessage = "{0} is not installed and skip non-installed option selected. Skipping...".FormatWith(packageName); var result = packageResultsToReturn.GetOrAdd(packageName, new PackageResult(packageName, null, null)); result.Messages.Add(new ResultMessage(ResultType.Warn, warnLogMessage)); if (config.RegularOutput) this.Log().Warn(ChocolateyLoggers.Important, warnLogMessage); @@ -998,7 +1011,7 @@ public virtual ConcurrentDictionary upgrade_run(Chocolate continue; } - string logMessage = @"{0} is not installed. Installing...".format_with(packageName); + string logMessage = @"{0} is not installed. Installing...".FormatWith(packageName); if (config.RegularOutput) this.Log().Warn(ChocolateyLoggers.Important, logMessage); @@ -1006,11 +1019,11 @@ public virtual ConcurrentDictionary upgrade_run(Chocolate config.PackageNames = packageName; if (config.Noop) { - install_noop(config, continueAction); + InstallDryRun(config, continueAction); } else { - var installResults = install_run(config, continueAction, beforeUpgradeAction); + var installResults = Install(config, continueAction, beforeUpgradeAction); foreach (var result in installResults) { packageResultsToReturn.GetOrAdd(result.Key, result.Value); @@ -1021,7 +1034,7 @@ public virtual ConcurrentDictionary upgrade_run(Chocolate continue; } - var pkgInfo = _packageInfoService.get_package_information(installedPackage.PackageMetadata); + var pkgInfo = _packageInfoService.Get(installedPackage.PackageMetadata); bool isPinned = pkgInfo != null && pkgInfo.IsPinned; if (isPinned && config.OutdatedCommand.IgnorePinned) @@ -1029,13 +1042,13 @@ public virtual ConcurrentDictionary upgrade_run(Chocolate continue; } - set_package_config_for_upgrade(config, pkgInfo); + SetConfigFromRememberedArguments(config, pkgInfo); var pathResolver = NugetCommon.GetPathResolver(_fileSystem); var nugetProject = new FolderNuGetProject(ApplicationParameters.PackagesLocation, pathResolver, NuGetFramework.AnyFramework); if (version != null && version < installedPackage.PackageMetadata.Version && !config.AllowDowngrade) { - string logMessage = "A newer version of {0} (v{1}) is already installed.{2} Use --allow-downgrade or --force to attempt to upgrade to older versions.".format_with(installedPackage.PackageMetadata.Id, installedPackage.Version, Environment.NewLine); + string logMessage = "A newer version of {0} (v{1}) is already installed.{2} Use --allow-downgrade or --force to attempt to upgrade to older versions.".FormatWith(installedPackage.PackageMetadata.Id, installedPackage.Version, Environment.NewLine); var nullResult = packageResultsToReturn.GetOrAdd(packageName, new PackageResult(installedPackage.PackageMetadata, pathResolver.GetInstallPath(installedPackage.PackageMetadata.Id))); nullResult.Messages.Add(new ResultMessage(ResultType.Error, logMessage)); this.Log().Error(ChocolateyLoggers.Important, logMessage); @@ -1049,8 +1062,7 @@ public virtual ConcurrentDictionary upgrade_run(Chocolate // this is a prerelease - opt in for newer prereleases. config.Prerelease = true; } - - var availablePackage = NugetList.find_package(packageName, config, _nugetLogger, sourceCacheContext, NugetCommon.GetRepositoryResource(remoteRepositories).ToList(), NugetCommon.GetRepositoryResource(remoteRepositories).ToList(), version); + var availablePackage = NugetList.FindPackage(packageName, config, _nugetLogger, sourceCacheContext, remoteEndpoints, version); config.Prerelease = originalPrerelease; @@ -1058,26 +1070,26 @@ public virtual ConcurrentDictionary upgrade_run(Chocolate { if (config.Features.IgnoreUnfoundPackagesOnUpgradeOutdated) continue; - string logMessage = "{0} was not found with the source(s) listed.{1} If you specified a particular version and are receiving this message, it is possible that the package name exists but the version does not.{1} Version: \"{2}\"; Source(s): \"{3}\"".format_with(packageName, Environment.NewLine, config.Version, config.Sources); - var unfoundResult = packageResultsToReturn.GetOrAdd(packageName, new PackageResult(packageName, version.to_full_string(), null)); + string logMessage = "{0} was not found with the source(s) listed.{1} If you specified a particular version and are receiving this message, it is possible that the package name exists but the version does not.{1} Version: \"{2}\"; Source(s): \"{3}\"".FormatWith(packageName, Environment.NewLine, config.Version, config.Sources); + var unfoundResult = packageResultsToReturn.GetOrAdd(packageName, new PackageResult(packageName, version.ToFullStringChecked(), null)); if (config.UpgradeCommand.FailOnUnfound) { unfoundResult.Messages.Add(new ResultMessage(ResultType.Error, logMessage)); - if (config.RegularOutput) this.Log().Error(ChocolateyLoggers.Important, "{0}{1}".format_with(Environment.NewLine, logMessage)); + if (config.RegularOutput) this.Log().Error(ChocolateyLoggers.Important, "{0}{1}".FormatWith(Environment.NewLine, logMessage)); } else { - unfoundResult.Messages.Add(new ResultMessage(ResultType.Warn, "{0} was not found with the source(s) listed.".format_with(packageName))); + unfoundResult.Messages.Add(new ResultMessage(ResultType.Warn, "{0} was not found with the source(s) listed.".FormatWith(packageName))); unfoundResult.Messages.Add(new ResultMessage(ResultType.Inconclusive, logMessage)); if (config.RegularOutput) { - this.Log().Warn(ChocolateyLoggers.Important, "{0}{1}".format_with(Environment.NewLine, logMessage)); + this.Log().Warn(ChocolateyLoggers.Important, "{0}{1}".FormatWith(Environment.NewLine, logMessage)); } else { //last one is whether this package is pinned or not - this.Log().Info("{0}|{1}|{1}|{2}".format_with(installedPackage.PackageMetadata.Id, installedPackage.Version, isPinned.to_string().to_lower())); + this.Log().Info("{0}|{1}|{1}|{2}".FormatWith(installedPackage.PackageMetadata.Id, installedPackage.Version, isPinned.ToStringSafe().ToLowerSafe())); } } @@ -1087,7 +1099,7 @@ public virtual ConcurrentDictionary upgrade_run(Chocolate var packageResult = packageResultsToReturn.GetOrAdd(packageName, new PackageResult(availablePackage, pathResolver.GetInstallPath(availablePackage.Identity))); if (installedPackage.PackageMetadata.Version > availablePackage.Identity.Version && (!config.AllowDowngrade || (config.AllowDowngrade && version == null))) { - string logMessage = "{0} v{1} is newer than the most recent.{2} You must be smarter than the average bear...".format_with(installedPackage.PackageMetadata.Id, installedPackage.Version, Environment.NewLine); + string logMessage = "{0} v{1} is newer than the most recent.{2} You must be smarter than the average bear...".FormatWith(installedPackage.PackageMetadata.Id, installedPackage.Version, Environment.NewLine); packageResult.Messages.Add(new ResultMessage(ResultType.Inconclusive, logMessage)); if (!config.UpgradeCommand.NotifyOnlyAvailableUpgrades) @@ -1098,7 +1110,7 @@ public virtual ConcurrentDictionary upgrade_run(Chocolate } else { - this.Log().Info("{0}|{1}|{1}|{2}".format_with(installedPackage.PackageMetadata.Id, installedPackage.Version, isPinned.to_string().to_lower())); + this.Log().Info("{0}|{1}|{1}|{2}".FormatWith(installedPackage.PackageMetadata.Id, installedPackage.Version, isPinned.ToStringSafe().ToLowerSafe())); } } @@ -1107,7 +1119,7 @@ public virtual ConcurrentDictionary upgrade_run(Chocolate if (installedPackage.PackageMetadata.Version == availablePackage.Identity.Version) { - string logMessage = "{0} v{1} is the latest version available based on your source(s).".format_with(installedPackage.PackageMetadata.Id, installedPackage.Version); + string logMessage = "{0} v{1} is the latest version available based on your source(s).".FormatWith(installedPackage.PackageMetadata.Id, installedPackage.Version); if (!config.Force) { @@ -1124,7 +1136,7 @@ public virtual ConcurrentDictionary upgrade_run(Chocolate } else { - this.Log().Info("{0}|{1}|{2}|{3}".format_with(installedPackage.PackageMetadata.Id, installedPackage.Version, availablePackage.Identity.Version, isPinned.to_string().to_lower())); + this.Log().Info("{0}|{1}|{2}|{3}".FormatWith(installedPackage.PackageMetadata.Id, installedPackage.Version, availablePackage.Identity.Version, isPinned.ToStringSafe().ToLowerSafe())); } } @@ -1139,22 +1151,22 @@ public virtual ConcurrentDictionary upgrade_run(Chocolate { if (availablePackage.Identity.Version > installedPackage.PackageMetadata.Version) { - string logMessage = "You have {0} v{1} installed. Version {2} is available based on your source(s).".format_with(installedPackage.PackageMetadata.Id, installedPackage.Version, availablePackage.Identity.Version); + string logMessage = "You have {0} v{1} installed. Version {2} is available based on your source(s).".FormatWith(installedPackage.PackageMetadata.Id, installedPackage.Version, availablePackage.Identity.Version); packageResult.Messages.Add(new ResultMessage(ResultType.Note, logMessage)); if (config.RegularOutput) { - this.Log().Warn("{0}{1}".format_with(Environment.NewLine, logMessage)); + this.Log().Warn("{0}{1}".FormatWith(Environment.NewLine, logMessage)); } else { - this.Log().Info("{0}|{1}|{2}|{3}".format_with(installedPackage.PackageMetadata.Id, installedPackage.Version, availablePackage.Identity.Version, isPinned.to_string().to_lower())); + this.Log().Info("{0}|{1}|{2}|{3}".FormatWith(installedPackage.PackageMetadata.Id, installedPackage.Version, availablePackage.Identity.Version, isPinned.ToStringSafe().ToLowerSafe())); } } if (isPinned) { - string logMessage = "{0} is pinned. Skipping pinned package.".format_with(packageName); + string logMessage = "{0} is pinned. Skipping pinned package.".FormatWith(packageName); packageResult.Messages.Add(new ResultMessage(ResultType.Warn, logMessage)); packageResult.Messages.Add(new ResultMessage(ResultType.Inconclusive, logMessage)); if (config.RegularOutput) this.Log().Warn(ChocolateyLoggers.Important, logMessage); @@ -1165,7 +1177,7 @@ public virtual ConcurrentDictionary upgrade_run(Chocolate if (performAction) { - NugetCommon.GetPackageDependencies(availablePackage.Identity, NuGetFramework.AnyFramework, sourceCacheContext, _nugetLogger, dependencyResources, sourcePackageDependencyInfos, sourceDependencyCache, config).GetAwaiter().GetResult(); + NugetCommon.GetPackageDependencies(availablePackage.Identity, NuGetFramework.AnyFramework, sourceCacheContext, _nugetLogger, remoteEndpoints, sourcePackageDependencyInfos, sourceDependencyCache, config).GetAwaiter().GetResult(); packagesToUninstall.Add(installedPackage); @@ -1198,13 +1210,13 @@ public virtual ConcurrentDictionary upgrade_run(Chocolate NugetCommon.GetPackageParents(availablePackage.Identity.Id, parentInfos, localPackagesDependencyInfos).GetAwaiter().GetResult(); foreach (var parentPackage in parentInfos) { - foreach (var packageVersion in NugetList.find_all_package_versions(parentPackage.Id, config, _nugetLogger, sourceCacheContext, NugetCommon.GetRepositoryResource(remoteRepositories).ToList())) + foreach (var packageVersion in NugetList.FindAllPackageVersions(parentPackage.Id, config, _nugetLogger, sourceCacheContext, remoteEndpoints)) { - NugetCommon.GetPackageDependencies(packageVersion.Identity, NuGetFramework.AnyFramework, sourceCacheContext, _nugetLogger, dependencyResources, sourcePackageDependencyInfos, sourceDependencyCache, config).GetAwaiter().GetResult(); + NugetCommon.GetPackageDependencies(packageVersion.Identity, NuGetFramework.AnyFramework, sourceCacheContext, _nugetLogger, remoteEndpoints, sourcePackageDependencyInfos, sourceDependencyCache, config).GetAwaiter().GetResult(); } } - var removedSources = remove_pinned_source_dependencies(sourcePackageDependencyInfos, allLocalPackages); + var removedSources = RemovePinnedSourceDependencies(sourcePackageDependencyInfos, allLocalPackages); if (version != null || removedSources.Count == 0) { @@ -1215,7 +1227,7 @@ public virtual ConcurrentDictionary upgrade_run(Chocolate if (removedSources.Count > 0 && version == null) { - remove_invalid_dependencies_and_parents(availablePackage, removedSources, sourcePackageDependencyInfos, localPackagesDependencyInfos); + RemoveInvalidDependenciesAndParents(availablePackage, removedSources, sourcePackageDependencyInfos, localPackagesDependencyInfos); } var dependencyResolver = new PackageResolver(); @@ -1230,7 +1242,7 @@ public virtual ConcurrentDictionary upgrade_run(Chocolate // We exclude any installed package that does have a dependency that is missing, // except if that dependency is one of the targets the user requested. // If we do not exclude such packages, we will get a resolving exception later. - .Where(p => is_dependent_on_target_ids(p, targetIdsToInstall) || !has_missing_dependency(p, allLocalPackages)) + .Where(p => IsDependentOnTargetPackages(p, targetIdsToInstall) || !HasMissingDependency(p, allLocalPackages)) .Select(p => p.SearchMetadata.Identity) .Where(x => !targetIdsToInstall.Contains(x.Id, StringComparer.OrdinalIgnoreCase)).ToList(); } @@ -1262,13 +1274,13 @@ public virtual ConcurrentDictionary upgrade_run(Chocolate try { nugetProject.DeletePackage(packageToUninstall.Identity, projectContext, CancellationToken.None).GetAwaiter().GetResult(); - remove_cache_for_package(config, packageToUninstall.PackageMetadata); + RemovePackageFromCache(config, packageToUninstall.PackageMetadata); } catch (Exception ex) { var forcedResult = packageResultsToReturn.GetOrAdd(packageToUninstall.Identity.Id, packageToUninstall); forcedResult.Messages.Add(new ResultMessage(ResultType.Note, "Removing old version")); - string logMessage = "{0}:{1} {2}".format_with("Unable to remove existing package", Environment.NewLine, ex.Message); + string logMessage = "{0}:{1} {2}".FormatWith("Unable to remove existing package", Environment.NewLine, ex.Message); this.Log().Warn(logMessage); forcedResult.Messages.Add(new ResultMessage(ResultType.Inconclusive, logMessage)); } @@ -1295,7 +1307,7 @@ public virtual ConcurrentDictionary upgrade_run(Chocolate } catch (NuGetResolverConstraintException ex) { - var logMessage = get_dependency_resolution_error_message(ex); + var logMessage = GetDependencyResolutionErrorMessage(ex); this.Log().Error(ChocolateyLoggers.Important, logMessage); foreach (var pkgMetadata in packagesToInstall) @@ -1306,7 +1318,7 @@ public virtual ConcurrentDictionary upgrade_run(Chocolate } catch (Exception ex) { - this.Log().Warn("Need to add specific handling for exception type {0}".format_with(ex.GetType().Name)); + this.Log().Warn("Need to add specific handling for exception type {0}".FormatWith(ex.GetType().Name)); this.Log().Warn(ex.Message); } } @@ -1341,9 +1353,9 @@ public virtual ConcurrentDictionary upgrade_run(Chocolate if (packageRemoteMetadata is null) { - packageRemoteMetadata = packageDependencyInfo - .Source - .GetResource() + var endpoint = NuGetEndpointResources.GetResourcesBySource(packageDependencyInfo.Source); + + packageRemoteMetadata = endpoint.PackageMetadataResource .GetMetadataAsync(packageDependencyInfo, sourceCacheContext, _nugetLogger, CancellationToken.None) .GetAwaiter().GetResult(); } @@ -1354,22 +1366,22 @@ public virtual ConcurrentDictionary upgrade_run(Chocolate { if (packageToUninstall != null) { - var oldPkgInfo = _packageInfoService.get_package_information(packageToUninstall.PackageMetadata); + var oldPkgInfo = _packageInfoService.Get(packageToUninstall.PackageMetadata); - backup_and_before_modify(packageToUninstall, oldPkgInfo, config, beforeUpgradeAction); + BackupAndRunBeforeModify(packageToUninstall, oldPkgInfo, config, beforeUpgradeAction); packageToUninstall.InstallLocation = pathResolver.GetInstallPath(packageToUninstall.Identity); try { //It does not throw or return false if it fails to delete something... //var ableToDelete = nugetProject.DeletePackage(packageToUninstall.Identity, projectContext, CancellationToken.None, shouldDeleteDirectory: false).GetAwaiter().GetResult(); - remove_installation_files_unsafe(packageToUninstall.PackageMetadata, oldPkgInfo); + RemoveInstallationFilesUnsafe(packageToUninstall.PackageMetadata, oldPkgInfo); } catch (Exception ex) { var forcedResult = packageResultsToReturn.GetOrAdd(packageToUninstall.Name, packageToUninstall); forcedResult.Messages.Add(new ResultMessage(ResultType.Note, "Backing up and removing old version")); - string logMessage = "{0}:{1} {2}".format_with("Unable to remove existing package prior to upgrade", Environment.NewLine, ex.Message); + string logMessage = "{0}:{1} {2}".FormatWith("Unable to remove existing package prior to upgrade", Environment.NewLine, ex.Message); this.Log().Warn(logMessage); //forcedResult.Messages.Add(new ResultMessage(ResultType.Inconclusive, logMessage)); forcedResult.Messages.Add(new ResultMessage(ResultType.Error, logMessage)); @@ -1377,11 +1389,16 @@ public virtual ConcurrentDictionary upgrade_run(Chocolate continue; } + + // We need to remove the nupkg file explicitly in case it has + // been modified. + EnsureNupkgRemoved(oldPkgInfo.Package); } - var downloadResource = packageDependencyInfo.Source.GetResource(); + var endpoint = NuGetEndpointResources.GetResourcesBySource(packageDependencyInfo.Source); + var downloadResource = endpoint.DownloadResource; - _fileSystem.delete_file(pathResolver.GetInstalledPackageFilePath(packageDependencyInfo)); + _fileSystem.DeleteFile(pathResolver.GetInstalledPackageFilePath(packageDependencyInfo)); ChocolateyProgressInfo.ShouldDisplayDownloadProgress = config.Features.ShowDownloadProgress; @@ -1403,40 +1420,52 @@ public virtual ConcurrentDictionary upgrade_run(Chocolate var installedPath = nugetProject.GetInstalledPath(packageDependencyInfo); - fix_nuspec_casing(availablePackage, installedPath); + NormalizeNuspecCasing(availablePackage, installedPath); var manifestPath = nugetProject.GetInstalledManifestFilePath(packageDependencyInfo); var packageMetadata = new ChocolateyPackageMetadata(manifestPath, _fileSystem); - remove_nuget_cache_for_package(availablePackage); + RemovePackageFromNugetCache(availablePackage); - this.Log().Info(ChocolateyLoggers.Important, "{0}{1} v{2}{3}{4}{5}".format_with( + this.Log().Info(ChocolateyLoggers.Important, "{0}{1} v{2}{3}{4}{5}".FormatWith( System.Environment.NewLine, packageMetadata.Id, - packageMetadata.Version.to_full_string(), + packageMetadata.Version.ToFullStringChecked(), config.Force ? " (forced)" : string.Empty, packageRemoteMetadata.IsApproved ? " [Approved]" : string.Empty, packageRemoteMetadata.PackageTestResultStatus == "Failing" && packageRemoteMetadata.IsDownloadCacheAvailable ? " - Likely broken for FOSS users (due to download location changes)" : packageRemoteMetadata.PackageTestResultStatus == "Failing" ? " - Possibly broken" : string.Empty )); - var upgradePackageResult = packageResultsToReturn.GetOrAdd(packageDependencyInfo.Id.to_lower(), new PackageResult(packageMetadata, packageRemoteMetadata, installedPath)); + var upgradePackageResult = packageResultsToReturn.GetOrAdd(packageDependencyInfo.Id.ToLowerSafe(), new PackageResult(packageMetadata, packageRemoteMetadata, installedPath)); upgradePackageResult.ResetMetadata(packageMetadata, packageRemoteMetadata); upgradePackageResult.InstallLocation = installedPath; + upgradePackageResult.Messages.Add(new ResultMessage(ResultType.Debug, ApplicationParameters.Messages.ContinueChocolateyAction)); - var elementsList = _ruleService.validate_rules(manifestPath) + var elementsList = _ruleService.ValidateRules(manifestPath) .Where(r => r.Severity == infrastructure.rules.RuleType.Error && !string.IsNullOrEmpty(r.Id)) - .where_unsupported_or_deprecated() - .Select(r => "{0}: {1}".format_with(r.Id, r.Message)) + .WhereUnsupportedOrDeprecated() + .Select(r => "{0}: {1}".FormatWith(r.Id, r.Message)) .ToList(); if (elementsList.Count > 0) { - var message = "Issues found with nuspec elements\r\n" + elementsList.join("\r\n"); + var message = "Issues found with nuspec elements\r\n" + elementsList.Join("\r\n"); packageResult.Messages.Add(new ResultMessage(ResultType.Warn, message)); } if (continueAction != null) continueAction.Invoke(upgradePackageResult, config); + + if (packageToUninstall != null) + { + // Add any warning messages from when we uninstalled the previous package, so + // these can be propagated to the warning list at the end. + // We add these as the last elements otherwise warnings in the current/new + // package may not show up as expected. + upgradePackageResult.Messages.AddRange(packageToUninstall.Messages + .Where(p => p.MessageType == ResultType.Warn) + .Select(p => new ResultMessage(p.MessageType, "v{0} - {1}".FormatWith(packageToUninstall.Version, p.Message)))); + } } catch (Exception ex) { @@ -1445,12 +1474,12 @@ public virtual ConcurrentDictionary upgrade_run(Chocolate if (webException != null) { var response = webException.Response as HttpWebResponse; - if (response != null && !string.IsNullOrWhiteSpace(response.StatusDescription)) message += " {0}".format_with(response.StatusDescription); + if (response != null && !string.IsNullOrWhiteSpace(response.StatusDescription)) message += " {0}".FormatWith(response.StatusDescription); } - var logMessage = "{0} not upgraded. An error occurred during installation:{1} {2}".format_with(packageName, Environment.NewLine, message); + var logMessage = "{0} not upgraded. An error occurred during installation:{1} {2}".FormatWith(packageName, Environment.NewLine, message); this.Log().Error(ChocolateyLoggers.Important, logMessage); - var errorResult = packageResultsToReturn.GetOrAdd(packageDependencyInfo.Id, new PackageResult(packageDependencyInfo.Id, version.to_full_string(), null)); + var errorResult = packageResultsToReturn.GetOrAdd(packageDependencyInfo.Id, new PackageResult(packageDependencyInfo.Id, version.ToFullStringChecked(), null)); errorResult.Messages.Add(new ResultMessage(ResultType.Error, logMessage)); if (errorResult.ExitCode == 0) errorResult.ExitCode = 1; if (continueAction != null) continueAction.Invoke(errorResult, config); @@ -1463,41 +1492,41 @@ public virtual ConcurrentDictionary upgrade_run(Chocolate // Reset the configuration again once we are completely done with the processing of // configurations, and make sure that we are removing any backup that was created // as part of this run. - config.reset_config(removeBackup: true); + config.RevertChanges(removeBackup: true); return packageResultsToReturn; } - public virtual ConcurrentDictionary get_outdated(ChocolateyConfiguration config) + public virtual ConcurrentDictionary GetOutdated(ChocolateyConfiguration config) { - var remoteRepositories = NugetCommon.GetRemoteRepositories(config, _nugetLogger, _fileSystem); + var remoteEndpoints = NugetCommon.GetRepositoryResources(remoteRepositories); var pathResolver = NugetCommon.GetPathResolver(_fileSystem); var outdatedPackages = new ConcurrentDictionary(); var sourceCacheContext = new ChocolateySourceCacheContext(config); - var allPackages = set_package_names_if_all_is_specified(config, () => { config.IgnoreDependencies = true; }); - var packageNames = config.PackageNames.Split(new[] { ApplicationParameters.PackageNamesSeparator }, StringSplitOptions.RemoveEmptyEntries).or_empty_list_if_null().ToList(); + var allPackages = SetPackageNamesIfAllSpecified(config, () => { config.IgnoreDependencies = true; }); + var packageNames = config.PackageNames.Split(new[] { ApplicationParameters.PackageNamesSeparator }, StringSplitOptions.RemoveEmptyEntries).OrEmpty().ToList(); - config.start_backup(); + config.CreateBackup(); foreach (var packageName in packageNames) { // We need to ensure we are using a clean configuration file // before we start reading it. - config.reset_config(); + config.RevertChanges(); var installedPackage = allPackages.FirstOrDefault(p => string.Equals(p.Name, packageName, StringComparison.OrdinalIgnoreCase)); - var pkgInfo = _packageInfoService.get_package_information(installedPackage.PackageMetadata); + var pkgInfo = _packageInfoService.Get(installedPackage.PackageMetadata); bool isPinned = pkgInfo.IsPinned; // if the package is pinned and we are skipping pinned, // move on quickly if (isPinned && config.OutdatedCommand.IgnorePinned) { - string pinnedLogMessage = "{0} is pinned. Skipping pinned package.".format_with(packageName); + string pinnedLogMessage = "{0} is pinned. Skipping pinned package.".FormatWith(packageName); var pinnedPackageResult = outdatedPackages.GetOrAdd(packageName, new PackageResult(installedPackage.PackageMetadata, pathResolver.GetInstallPath(installedPackage.PackageMetadata.Id))); pinnedPackageResult.Messages.Add(new ResultMessage(ResultType.Debug, pinnedLogMessage)); pinnedPackageResult.Messages.Add(new ResultMessage(ResultType.Inconclusive, pinnedLogMessage)); @@ -1511,18 +1540,18 @@ public virtual ConcurrentDictionary get_outdated(Chocolat config.Prerelease = true; } - var latestPackage = NugetList.find_package(packageName, config, _nugetLogger, sourceCacheContext, NugetCommon.GetRepositoryResource(remoteRepositories).ToList(), NugetCommon.GetRepositoryResource(remoteRepositories).ToList()); + var latestPackage = NugetList.FindPackage(packageName, config, _nugetLogger, sourceCacheContext, remoteEndpoints); if (latestPackage == null) { if (config.Features.IgnoreUnfoundPackagesOnUpgradeOutdated) continue; - string unfoundLogMessage = "{0} was not found with the source(s) listed.{1} Source(s): \"{2}\"".format_with(packageName, Environment.NewLine, config.Sources); + string unfoundLogMessage = "{0} was not found with the source(s) listed.{1} Source(s): \"{2}\"".FormatWith(packageName, Environment.NewLine, config.Sources); var unfoundResult = outdatedPackages.GetOrAdd(packageName, new PackageResult(installedPackage.PackageMetadata, pathResolver.GetInstallPath(installedPackage.PackageMetadata.Id))); unfoundResult.Messages.Add(new ResultMessage(ResultType.Warn, unfoundLogMessage)); unfoundResult.Messages.Add(new ResultMessage(ResultType.Inconclusive, unfoundLogMessage)); - this.Log().Warn("{0}|{1}|{1}|{2}".format_with(installedPackage.Name, installedPackage.Version, isPinned.to_string().to_lower())); + this.Log().Warn("{0}|{1}|{1}|{2}".FormatWith(installedPackage.Name, installedPackage.Version, isPinned.ToStringSafe().ToLowerSafe())); continue; } @@ -1530,16 +1559,16 @@ public virtual ConcurrentDictionary get_outdated(Chocolat var packageResult = outdatedPackages.GetOrAdd(packageName, new PackageResult(latestPackage, pathResolver.GetInstallPath(latestPackage.Identity))); - string logMessage = "You have {0} v{1} installed. Version {2} is available based on your source(s).{3} Source(s): \"{4}\"".format_with(installedPackage.Name, installedPackage.Version, latestPackage.Identity.Version, Environment.NewLine, config.Sources); + string logMessage = "You have {0} v{1} installed. Version {2} is available based on your source(s).{3} Source(s): \"{4}\"".FormatWith(installedPackage.Name, installedPackage.Version, latestPackage.Identity.Version, Environment.NewLine, config.Sources); packageResult.Messages.Add(new ResultMessage(ResultType.Note, logMessage)); - this.Log().Info("{0}|{1}|{2}|{3}".format_with(installedPackage.Name, installedPackage.Version, latestPackage.Identity.Version, isPinned.to_string().to_lower())); + this.Log().Info("{0}|{1}|{2}|{3}".FormatWith(installedPackage.Name, installedPackage.Version, latestPackage.Identity.Version, isPinned.ToStringSafe().ToLowerSafe())); } // Reset the configuration again once we are completely done with the processing of // configurations, and make sure that we are removing any backup that was created // as part of this run. - config.reset_config(removeBackup: true); + config.RevertChanges(removeBackup: true); return outdatedPackages; } @@ -1550,40 +1579,40 @@ public virtual ConcurrentDictionary get_outdated(Chocolat /// The configuration. /// The package information. /// The original unmodified configuration, so it can be reset after upgrade - protected virtual ChocolateyConfiguration set_package_config_for_upgrade(ChocolateyConfiguration config, ChocolateyPackageInformation packageInfo) + protected virtual ChocolateyConfiguration SetConfigFromRememberedArguments(ChocolateyConfiguration config, ChocolateyPackageInformation packageInfo) { if (!config.Features.UseRememberedArgumentsForUpgrades || string.IsNullOrWhiteSpace(packageInfo.Arguments)) return config; - var packageArgumentsUnencrypted = packageInfo.Arguments.contains(" --") && packageInfo.Arguments.to_string().Length > 4 ? packageInfo.Arguments : NugetEncryptionUtility.DecryptString(packageInfo.Arguments); + var packageArgumentsUnencrypted = packageInfo.Arguments.ContainsSafe(" --") && packageInfo.Arguments.ToStringSafe().Length > 4 ? packageInfo.Arguments : NugetEncryptionUtility.DecryptString(packageInfo.Arguments); var sensitiveArgs = true; - if (!ArgumentsUtility.arguments_contain_sensitive_information(packageArgumentsUnencrypted)) + if (!ArgumentsUtility.SensitiveArgumentsProvided(packageArgumentsUnencrypted)) { sensitiveArgs = false; - this.Log().Debug(ChocolateyLoggers.Verbose, "{0} - Adding remembered arguments for upgrade: {1}".format_with(packageInfo.Package.Id, packageArgumentsUnencrypted.escape_curly_braces())); + this.Log().Debug(ChocolateyLoggers.Verbose, "{0} - Adding remembered arguments for upgrade: {1}".FormatWith(packageInfo.Package.Id, packageArgumentsUnencrypted.EscapeCurlyBraces())); } var packageArgumentsSplit = packageArgumentsUnencrypted.Split(new[] { " --" }, StringSplitOptions.RemoveEmptyEntries); var packageArguments = new List(); - foreach (var packageArgument in packageArgumentsSplit.or_empty_list_if_null()) + foreach (var packageArgument in packageArgumentsSplit.OrEmpty()) { var packageArgumentSplit = packageArgument.Split(new[] { '=' }, 2, StringSplitOptions.RemoveEmptyEntries); - var optionName = packageArgumentSplit[0].to_string(); + var optionName = packageArgumentSplit[0].ToStringSafe(); var optionValue = string.Empty; if (packageArgumentSplit.Length == 2) { - optionValue = packageArgumentSplit[1].to_string().remove_surrounding_quotes(); - if (optionValue.StartsWith("'")) optionValue.remove_surrounding_quotes(); + optionValue = packageArgumentSplit[1].ToStringSafe().UnquoteSafe(); + if (optionValue.StartsWith("'")) optionValue.UnquoteSafe(); } if (sensitiveArgs) { - this.Log().Debug(ChocolateyLoggers.Verbose, "{0} - Adding '{1}' to upgrade arguments. Values not shown due to detected sensitive arguments".format_with(packageInfo.Package.Id, optionName.escape_curly_braces())); + this.Log().Debug(ChocolateyLoggers.Verbose, "{0} - Adding '{1}' to upgrade arguments. Values not shown due to detected sensitive arguments".FormatWith(packageInfo.Package.Id, optionName.EscapeCurlyBraces())); } - packageArguments.Add("--{0}{1}".format_with(optionName, string.IsNullOrWhiteSpace(optionValue) ? string.Empty : "=" + optionValue)); + packageArguments.Add("--{0}{1}".FormatWith(optionName, string.IsNullOrWhiteSpace(optionValue) ? string.Empty : "=" + optionValue)); } - var originalConfig = config.deep_copy(); + var originalConfig = config.DeepCopy(); // this changes config globally ConfigurationOptions.OptionSet.Parse(packageArguments); @@ -1596,7 +1625,7 @@ protected virtual ChocolateyConfiguration set_package_config_for_upgrade(Chocola return originalConfig; } - private bool has_missing_dependency(PackageResult package, List allLocalPackages) + private bool HasMissingDependency(PackageResult package, List allLocalPackages) { foreach (var dependency in package.PackageMetadata.DependencyGroups.SelectMany(d => d.Packages)) { @@ -1609,11 +1638,11 @@ private bool has_missing_dependency(PackageResult package, List a return false; } - private bool is_dependent_on_target_ids(PackageResult package, IEnumerable targetIdsToInstall) + private bool IsDependentOnTargetPackages(PackageResult package, IEnumerable packageIds) { foreach (var dependency in package.PackageMetadata.DependencyGroups.SelectMany(d => d.Packages)) { - if (targetIdsToInstall.Contains(dependency.Id, StringComparer.OrdinalIgnoreCase)) + if (packageIds.Contains(dependency.Id, StringComparer.OrdinalIgnoreCase)) { return true; } @@ -1622,7 +1651,7 @@ private bool is_dependent_on_target_ids(PackageResult package, IEnumerable removedSources, HashSet sourcePackageDependencyInfos, @@ -1637,14 +1666,14 @@ private static void remove_invalid_dependencies_and_parents( if (removedAvailablePackage == null) { - removedAvailablePackage = packagesToRemove.FirstOrDefault(p => p.Id.Equals(availablePackage.Identity.Id) && p.Version == availablePackage.Identity.Version); + removedAvailablePackage = packagesToRemove.FirstOrDefault(p => p.Id.IsEqualTo(availablePackage.Identity.Id) && p.Version == availablePackage.Identity.Version); } sourcePackageDependencyInfos.RemoveWhere(s => packagesToRemove.Contains(s)); removedSources.AddRange(packagesToRemove); } - if (removedAvailablePackage != null && !sourcePackageDependencyInfos.Any(s => s.Id.Equals(removedAvailablePackage.Id))) + if (removedAvailablePackage != null && !sourcePackageDependencyInfos.Any(s => s.Id.IsEqualTo(removedAvailablePackage.Id))) { removedSources.Remove(removedAvailablePackage); sourcePackageDependencyInfos.Add(removedAvailablePackage); @@ -1668,9 +1697,9 @@ private static void remove_invalid_dependencies_and_parents( sourcePackageDependencyInfos.RemoveWhere(s => s.Id.Equals(availablePackage.Identity.Id, StringComparison.OrdinalIgnoreCase) && s.Version != maxVersion); } - private HashSet remove_pinned_source_dependencies(HashSet dependencyInfos, List localPackages) + private HashSet RemovePinnedSourceDependencies(HashSet dependencyInfos, List localPackages) { - var pinnedPackages = localPackages.Select(l => _packageInfoService.get_package_information(l.PackageMetadata)) + var pinnedPackages = localPackages.Select(l => _packageInfoService.Get(l.PackageMetadata)) .Where(p => p != null && p.IsPinned) .Select(p => p.Package.Id) .ToList(); @@ -1690,13 +1719,13 @@ private HashSet remove_pinned_source_dependencies(H return dependencyInfosToExclude; } - private void validate_nuspec(string nuspecFilePath, ChocolateyConfiguration config) + private void ValidateNuspec(string nuspecFilePath, ChocolateyConfiguration config) { - var results = _ruleService.validate_rules(nuspecFilePath); + var results = _ruleService.ValidateRules(nuspecFilePath); if (!config.PackCommand.PackThrowOnUnsupportedElements) { - results = results.where_unsupported_or_deprecated(inverse: true); + results = results.WhereUnsupportedOrDeprecated(inverse: true); } var hasErrors = false; @@ -1705,7 +1734,7 @@ private void validate_nuspec(string nuspecFilePath, ChocolateyConfiguration conf { var message = string.IsNullOrEmpty(rule.Id) ? rule.Message - : "{0}: {1}".format_with(rule.Id, rule.Message); + : "{0}: {1}".FormatWith(rule.Id, rule.Message); switch (rule.Severity) { @@ -1755,16 +1784,16 @@ private void validate_nuspec(string nuspecFilePath, ChocolateyConfiguration conf if (hasErrors) { this.Log().Info(string.Empty); - throw new InvalidDataException("One or more issues found with {0}, please fix all validation items above listed as errors.".format_with(nuspecFilePath)); + throw new InvalidDataException("One or more issues found with {0}, please fix all validation items above listed as errors.".FormatWith(nuspecFilePath)); } } - private string get_install_directory(ChocolateyConfiguration config, IPackageMetadata installedPackage) + private string GetInstallDirectory(IPackageMetadata installedPackage) { var pathResolver = NugetCommon.GetPathResolver(_fileSystem); var installDirectory = pathResolver.GetInstallPath(new PackageIdentity(installedPackage.Id, installedPackage.Version)); - if (!_fileSystem.directory_exists(installDirectory)) + if (!_fileSystem.DirectoryExists(installDirectory)) { return null; } @@ -1772,129 +1801,93 @@ private string get_install_directory(ChocolateyConfiguration config, IPackageMet return installDirectory; } - [Obsolete("This overload is obsolete and will be removed in a future version.")] - public virtual void ensure_package_files_have_compatible_attributes(ChocolateyConfiguration config, IPackageMetadata installedPackage, ChocolateyPackageInformation pkgInfo) - => ensure_package_files_have_compatible_attributes(config, installedPackage); - - protected virtual void ensure_package_files_have_compatible_attributes(ChocolateyConfiguration config, IPackageMetadata installedPackage) + protected virtual void EnsurePackageFilesHaveCompatibleAttributes(ChocolateyConfiguration config, IPackageMetadata installedPackage) { - var installDirectory = get_install_directory(config, installedPackage); - if (!_fileSystem.directory_exists(installDirectory)) return; + var installDirectory = GetInstallDirectory(installedPackage); + if (!_fileSystem.DirectoryExists(installDirectory)) return; - _filesService.ensure_compatible_file_attributes(installDirectory, config); + _filesService.EnsureCompatibleFileAttributes(installDirectory, config); } - [Obsolete("This overload is obsolete and will be removed in a future version.")] - public virtual void backup_existing_version(ChocolateyConfiguration config, IPackageMetadata installedPackage, ChocolateyPackageInformation packageInfo) - => backup_existing_version(config, packageInfo); - - protected virtual void backup_existing_version(ChocolateyConfiguration config, ChocolateyPackageInformation packageInfo) + protected virtual void BackupCurrentVersion(ChocolateyConfiguration config, ChocolateyPackageInformation packageInfo) { - _fileSystem.create_directory_if_not_exists(ApplicationParameters.PackageBackupLocation); - - var pkgInstallPath = get_install_directory(config, packageInfo.Package); - - if (_fileSystem.directory_exists(pkgInstallPath)) - { - this.Log().Debug("Backing up existing {0} prior to operation.".format_with(packageInfo.Package.Id)); - - var backupLocation = pkgInstallPath.Replace(ApplicationParameters.PackagesLocation, ApplicationParameters.PackageBackupLocation); - - var errored = false; - try - { - _fileSystem.move_directory(pkgInstallPath, backupLocation); - } - catch (Exception ex) - { - errored = true; - this.Log().Error("Error during backup (move phase):{0} {1}".format_with(Environment.NewLine, ex.Message)); - } - finally - { - try - { - _fileSystem.copy_directory(backupLocation, pkgInstallPath, overwriteExisting: true); + var pkgInstallPath = GetInstallDirectory(packageInfo.Package); + var backupLocation = _fileSystem.CombinePaths( + pkgInstallPath.Replace(ApplicationParameters.PackagesLocation, ApplicationParameters.PackageBackupLocation), + packageInfo.Package.Version.ToNormalizedStringChecked()); - remove_packaging_files_prior_to_upgrade(pkgInstallPath, config.CommandName); - } - catch (Exception ex) - { - errored = true; - this.Log().Error("Error during backup (reset phase):{0} {1}".format_with(Environment.NewLine, ex.Message)); - } - } + var errored = _filesService.MovePackageUsingBackupStrategy(pkgInstallPath, backupLocation, restoreSource: true); + RemoveOldPackageScriptsBeforeUpgrade(pkgInstallPath, config.CommandName); - backup_changed_files(pkgInstallPath, config, packageInfo); + BackupChangedFiles(pkgInstallPath, config, packageInfo); - if (errored) - { - this.Log().Warn(ChocolateyLoggers.Important, - @"There was an error accessing files. This could mean there is a + if (errored) + { + this.Log().Warn(ChocolateyLoggers.Important, + @"There was an error accessing files. This could mean there is a process locking the folder or files. Please make sure nothing is running that would lock the files or folders in this directory prior - to upgrade. If the package fails to upgrade, this is likely the cause."); - } + to upgrade or uninstall. If the package fails to upgrade or uninstall, this is likely the cause."); } } - public virtual void remove_packaging_files_prior_to_upgrade(string directoryPath, string commandName) + public virtual void RemoveOldPackageScriptsBeforeUpgrade(string directoryPath, string commandName) { - if (commandName.to_lower() == "upgrade") + if (commandName.ToLowerSafe() == "upgrade") { // Due to the way that Package Reducer works, there is a potential that a Chocolatey Packaging // script could be incorrectly left in place during an upgrade operation. To guard against this, // remove any Chocolatey Packaging scripts, which will then be restored by the new package, if // they are still required var filesToDelete = new List { "chocolateyinstall", "chocolateyuninstall", "chocolateybeforemodify" }; - var packagingScripts = _fileSystem.get_files(directoryPath, "*.ps1", SearchOption.AllDirectories) - .Where(p => filesToDelete.Contains(_fileSystem.get_file_name_without_extension(p).to_lower())); + var packagingScripts = _fileSystem.GetFiles(directoryPath, "*.ps1", SearchOption.AllDirectories) + .Where(p => filesToDelete.Contains(_fileSystem.GetFilenameWithoutExtension(p).ToLowerSafe())); foreach (var packagingScript in packagingScripts) { - if (_fileSystem.file_exists(packagingScript)) + if (_fileSystem.FileExists(packagingScript)) { - this.Log().Debug("Deleting file {0}".format_with(packagingScript)); - _fileSystem.delete_file(packagingScript); + this.Log().Debug("Deleting file {0}".FormatWith(packagingScript)); + _fileSystem.DeleteFile(packagingScript); } } } } - public virtual void backup_changed_files(string packageInstallPath, ChocolateyConfiguration config, ChocolateyPackageInformation packageInfo) + public virtual void BackupChangedFiles(string packageInstallPath, ChocolateyConfiguration config, ChocolateyPackageInformation packageInfo) { if (packageInfo == null || packageInfo.Package == null) return; - var version = packageInfo.Package.Version.to_string(); + var version = packageInfo.Package.Version.ToStringSafe(); if (packageInfo.FilesSnapshot == null || packageInfo.FilesSnapshot.Files.Count == 0) { - var configFiles = _fileSystem.get_files(packageInstallPath, ApplicationParameters.ConfigFileExtensions, SearchOption.AllDirectories); - foreach (var file in configFiles.or_empty_list_if_null()) + var configFiles = _fileSystem.GetFiles(packageInstallPath, ApplicationParameters.ConfigFileExtensions, SearchOption.AllDirectories); + foreach (var file in configFiles.OrEmpty()) { - var backupName = "{0}.{1}".format_with(_fileSystem.get_file_name(file), version); + var backupName = "{0}.{1}".FormatWith(_fileSystem.GetFileName(file), version); - FaultTolerance.try_catch_with_logging_exception( - () => _fileSystem.copy_file(file, _fileSystem.combine_paths(_fileSystem.get_directory_name(file), backupName), overwriteExisting: true), + FaultTolerance.TryCatchWithLoggingException( + () => _fileSystem.CopyFile(file, _fileSystem.CombinePaths(_fileSystem.GetDirectoryName(file), backupName), overwriteExisting: true), "Error backing up configuration file"); } } else { - var currentFiles = _filesService.capture_package_files(packageInstallPath, config); - foreach (var currentFile in currentFiles.Files.or_empty_list_if_null()) + var currentFiles = _filesService.CaptureSnapshot(packageInstallPath, config); + foreach (var currentFile in currentFiles.Files.OrEmpty()) { - var installedFile = packageInfo.FilesSnapshot.Files.FirstOrDefault(x => x.Path.is_equal_to(currentFile.Path)); + var installedFile = packageInfo.FilesSnapshot.Files.FirstOrDefault(x => x.Path.IsEqualTo(currentFile.Path)); if (installedFile != null) { - if (!currentFile.Checksum.is_equal_to(installedFile.Checksum)) + if (!currentFile.Checksum.IsEqualTo(installedFile.Checksum)) { // skip nupkgs if they are different - if (_fileSystem.get_file_extension(currentFile.Path).is_equal_to(".nupkg")) continue; + if (_fileSystem.GetFileExtension(currentFile.Path).IsEqualTo(".nupkg")) continue; - var backupName = "{0}.{1}".format_with(_fileSystem.get_file_name(currentFile.Path), version); - FaultTolerance.try_catch_with_logging_exception( - () => _fileSystem.copy_file(currentFile.Path, _fileSystem.combine_paths(_fileSystem.get_directory_name(currentFile.Path), backupName), overwriteExisting: true), + var backupName = "{0}.{1}".FormatWith(_fileSystem.GetFileName(currentFile.Path), version); + FaultTolerance.TryCatchWithLoggingException( + () => _fileSystem.CopyFile(currentFile.Path, _fileSystem.CombinePaths(_fileSystem.GetDirectoryName(currentFile.Path), backupName), overwriteExisting: true), "Error backing up changed file"); } } @@ -1910,34 +1903,32 @@ public virtual void backup_changed_files(string packageInstallPath, ChocolateyCo /// they create the files in the past (not using force with new-item typically throws /// an error if the file exists). /// - /// The configuration. /// The installed package. - /// The package information. - private void remove_shim_directors(ChocolateyConfiguration config, IPackageMetadata installedPackage) + private void RemoveShimgenDirectors(IPackageMetadata installedPackage) { - var pkgInstallPath = get_install_directory(config, installedPackage); + var pkgInstallPath = GetInstallDirectory(installedPackage); - if (_fileSystem.directory_exists(pkgInstallPath)) + if (_fileSystem.DirectoryExists(pkgInstallPath)) { - var shimDirectorFiles = _fileSystem.get_files(pkgInstallPath, ApplicationParameters.ShimDirectorFileExtensions, SearchOption.AllDirectories); - foreach (var file in shimDirectorFiles.or_empty_list_if_null()) + var shimDirectorFiles = _fileSystem.GetFiles(pkgInstallPath, ApplicationParameters.ShimDirectorFileExtensions, SearchOption.AllDirectories); + foreach (var file in shimDirectorFiles.OrEmpty()) { - FaultTolerance.try_catch_with_logging_exception( - () => _fileSystem.delete_file(file), + FaultTolerance.TryCatchWithLoggingException( + () => _fileSystem.DeleteFile(file), "Error deleting shim director file"); } } } - private void remove_cache_for_package(ChocolateyConfiguration config, IPackageMetadata installedPackage) + private void RemovePackageFromCache(ChocolateyConfiguration config, IPackageMetadata installedPackage) { this.Log().Debug(ChocolateyLoggers.Verbose, "Ensuring removal of package cache files."); - var cacheDirectory = _fileSystem.combine_paths(config.CacheLocation, installedPackage.Id, installedPackage.Version.to_string()); + var cacheDirectory = _fileSystem.CombinePaths(config.CacheLocation, installedPackage.Id, installedPackage.Version.ToStringSafe()); - if (!_fileSystem.directory_exists(cacheDirectory)) return; + if (!_fileSystem.DirectoryExists(cacheDirectory)) return; - FaultTolerance.try_catch_with_logging_exception( - () => _fileSystem.delete_directory_if_exists(cacheDirectory, recursive: true), + FaultTolerance.TryCatchWithLoggingException( + () => _fileSystem.DeleteDirectoryChecked(cacheDirectory, recursive: true), "Unable to removed cached files"); } @@ -1949,7 +1940,7 @@ private void remove_cache_for_package(ChocolateyConfiguration config, IPackageMe /// same name with different contents. /// /// The installed package. - private void remove_nuget_cache_for_package(IPackageSearchMetadata installedPackage) + protected void RemovePackageFromNugetCache(IPackageSearchMetadata installedPackage) { var tempFolder = NuGetEnvironment.GetFolderPath(NuGetFolderPath.Temp); @@ -1958,50 +1949,50 @@ private void remove_nuget_cache_for_package(IPackageSearchMetadata installedPack return; } - FaultTolerance.try_catch_with_logging_exception( + FaultTolerance.TryCatchWithLoggingException( () => { - var packageFolderPath = _fileSystem.combine_paths(tempFolder, "{0}/{1}".format_with(installedPackage.Identity.Id, installedPackage.Identity.Version.to_string())); - var nugetCachedFile = _fileSystem.combine_paths(packageFolderPath, "{0}.{1}.nupkg".format_with(installedPackage.Identity.Id, installedPackage.Identity.Version.to_string())); - var nupkgMetaDataFile = _fileSystem.combine_paths(packageFolderPath, ".nupkg.metadata"); + var packageFolderPath = _fileSystem.CombinePaths(tempFolder, "{0}/{1}".FormatWith(installedPackage.Identity.Id, installedPackage.Identity.Version.ToStringSafe())); + var nugetCachedFile = _fileSystem.CombinePaths(packageFolderPath, "{0}.{1}.nupkg".FormatWith(installedPackage.Identity.Id, installedPackage.Identity.Version.ToStringSafe())); + var nupkgMetaDataFile = _fileSystem.CombinePaths(packageFolderPath, ".nupkg.metadata"); var nupkgShaFile = nugetCachedFile + ".sha512"; - if (_fileSystem.file_exists(nugetCachedFile)) + if (_fileSystem.FileExists(nugetCachedFile)) { - _fileSystem.delete_file(nugetCachedFile); + _fileSystem.DeleteFile(nugetCachedFile); } - if (_fileSystem.file_exists(nupkgMetaDataFile)) + if (_fileSystem.FileExists(nupkgMetaDataFile)) { - _fileSystem.delete_file(nupkgMetaDataFile); + _fileSystem.DeleteFile(nupkgMetaDataFile); } - if (_fileSystem.file_exists(nupkgShaFile)) + if (_fileSystem.FileExists(nupkgShaFile)) { - _fileSystem.delete_file(nupkgShaFile); + _fileSystem.DeleteFile(nupkgShaFile); } }, "Unable to removed cached NuGet package files."); } - public void uninstall_noop(ChocolateyConfiguration config, Action continueAction) + public void UninstallDryRun(ChocolateyConfiguration config, Action continueAction) { - var results = uninstall_run(config, continueAction, performAction: false); - foreach (var packageResult in results.or_empty_list_if_null()) + var results = Uninstall(config, continueAction, performAction: false); + foreach (var packageResult in results.OrEmpty()) { var package = packageResult.Value.PackageMetadata; - if (package != null) this.Log().Warn("Would have uninstalled {0} v{1}.".format_with(package.Id, package.Version.to_full_string())); + if (package != null) this.Log().Warn("Would have uninstalled {0} v{1}.".FormatWith(package.Id, package.Version.ToFullStringChecked())); } } - public ConcurrentDictionary uninstall_run(ChocolateyConfiguration config, Action continueAction, Action beforeUninstallAction = null) + public ConcurrentDictionary Uninstall(ChocolateyConfiguration config, Action continueAction, Action beforeUninstallAction = null) { - return uninstall_run(config, continueAction, performAction: true, beforeUninstallAction: beforeUninstallAction); + return Uninstall(config, continueAction, performAction: true, beforeUninstallAction: beforeUninstallAction); } - public virtual ConcurrentDictionary uninstall_run(ChocolateyConfiguration config, Action continueAction, bool performAction, Action beforeUninstallAction = null) + public virtual ConcurrentDictionary Uninstall(ChocolateyConfiguration config, Action continueAction, bool performAction, Action beforeUninstallAction = null) { - _fileSystem.create_directory_if_not_exists(ApplicationParameters.PackagesLocation); + _fileSystem.EnsureDirectoryExists(ApplicationParameters.PackagesLocation); var packageResultsToReturn = new ConcurrentDictionary(StringComparer.InvariantCultureIgnoreCase); NuGetVersion version = config.Version != null ? NuGetVersion.Parse(config.Version) : null; @@ -2009,7 +2000,7 @@ public virtual ConcurrentDictionary uninstall_run(Chocola var sourceCacheContext = new ChocolateySourceCacheContext(config); var localRepositorySource = NugetCommon.GetLocalRepository(); var projectContext = new ChocolateyNuGetProjectContext(config, _nugetLogger); - var allLocalPackages = get_all_installed_packages(config); + var allLocalPackages = GetInstalledPackages(config); // if we are uninstalling a package and not forcing dependencies, // look to see if the user is missing the actual package they meant @@ -2017,31 +2008,31 @@ public virtual ConcurrentDictionary uninstall_run(Chocola if (!config.ForceDependencies) { // if you find an install of an .install / .portable / .commandline, allow adding it to the list - var installedPackages = allLocalPackages.Select(p => p.Name).ToList().@join(ApplicationParameters.PackageNamesSeparator); - foreach (var packageName in config.PackageNames.Split(new[] { ApplicationParameters.PackageNamesSeparator }, StringSplitOptions.RemoveEmptyEntries).or_empty_list_if_null()) - { - var installerExists = installedPackages.contains("{0}.install".format_with(packageName)); - var portableExists = installedPackages.contains("{0}.portable".format_with(packageName)); - var cmdLineExists = installedPackages.contains("{0}.commandline".format_with(packageName)); - if ((!config.PackageNames.contains("{0}.install".format_with(packageName)) - && !config.PackageNames.contains("{0}.portable".format_with(packageName)) - && !config.PackageNames.contains("{0}.commandline".format_with(packageName)) + var installedPackages = allLocalPackages.Select(p => p.Name).ToList().Join(ApplicationParameters.PackageNamesSeparator); + foreach (var packageName in config.PackageNames.Split(new[] { ApplicationParameters.PackageNamesSeparator }, StringSplitOptions.RemoveEmptyEntries).OrEmpty()) + { + var installerExists = installedPackages.ContainsSafe("{0}.install".FormatWith(packageName)); + var portableExists = installedPackages.ContainsSafe("{0}.portable".FormatWith(packageName)); + var cmdLineExists = installedPackages.ContainsSafe("{0}.commandline".FormatWith(packageName)); + if ((!config.PackageNames.ContainsSafe("{0}.install".FormatWith(packageName)) + && !config.PackageNames.ContainsSafe("{0}.portable".FormatWith(packageName)) + && !config.PackageNames.ContainsSafe("{0}.commandline".FormatWith(packageName)) ) && (installerExists || portableExists || cmdLineExists) ) { var actualPackageName = installerExists ? - "{0}.install".format_with(packageName) + "{0}.install".FormatWith(packageName) : portableExists ? - "{0}.portable".format_with(packageName) - : "{0}.commandline".format_with(packageName); + "{0}.portable".FormatWith(packageName) + : "{0}.commandline".FormatWith(packageName); var timeoutInSeconds = config.PromptForConfirmation ? 0 : 20; this.Log().Warn(@"You are uninstalling {0}, which is likely a metapackage for an *.install/*.portable package that it installed - ({0} represents discoverability).".format_with(packageName)); - var selection = InteractivePrompt.prompt_for_confirmation( - "Would you like to uninstall {0} as well?".format_with(actualPackageName), + ({0} represents discoverability).".FormatWith(packageName)); + var selection = InteractivePrompt.PromptForConfirmation( + "Would you like to uninstall {0} as well?".FormatWith(actualPackageName), new[] { "yes", "no" }, defaultChoice: null, requireAnswer: false, @@ -2050,13 +2041,13 @@ public virtual ConcurrentDictionary uninstall_run(Chocola timeoutInSeconds: timeoutInSeconds ); - if (selection.is_equal_to("yes")) + if (selection.IsEqualTo("yes")) { - config.PackageNames += ";{0}".format_with(actualPackageName); + config.PackageNames += ";{0}".FormatWith(actualPackageName); } else { - var logMessage = "To finish removing {0}, please also run the command: `choco uninstall {1}`.".format_with(packageName, actualPackageName); + var logMessage = "To finish removing {0}, please also run the command: `choco uninstall {1}`.".FormatWith(packageName, actualPackageName); var actualPackageResult = packageResultsToReturn.GetOrAdd(actualPackageName, new PackageResult(actualPackageName, null, null)); actualPackageResult.Messages.Add(new ResultMessage(ResultType.Warn, logMessage)); actualPackageResult.Messages.Add(new ResultMessage(ResultType.Inconclusive, logMessage)); @@ -2065,7 +2056,7 @@ public virtual ConcurrentDictionary uninstall_run(Chocola } } - set_package_names_if_all_is_specified(config, () => + SetPackageNamesIfAllSpecified(config, () => { // force remove the item, ignore the dependencies // as those are going to be picked up anyway @@ -2073,13 +2064,15 @@ public virtual ConcurrentDictionary uninstall_run(Chocola config.ForceDependencies = false; }); - config.start_backup(); + config.CreateBackup(); - foreach (string packageName in config.PackageNames.Split(new[] { ApplicationParameters.PackageNamesSeparator }, StringSplitOptions.RemoveEmptyEntries).or_empty_list_if_null()) + var packageVersionsToRemove = new List(); + + foreach (string packageName in config.PackageNames.Split(new[] { ApplicationParameters.PackageNamesSeparator }, StringSplitOptions.RemoveEmptyEntries).OrEmpty()) { // We need to ensure we are using a clean configuration file // before we start reading it. - config.reset_config(); + config.RevertChanges(); IList installedPackageVersions = new List(); if (string.IsNullOrWhiteSpace(config.Version)) @@ -2094,7 +2087,7 @@ public virtual ConcurrentDictionary uninstall_run(Chocola if (installedPackageVersions.Count == 0) { - string logMessage = "{0} is not installed. Cannot uninstall a non-existent package.".format_with(packageName); + string logMessage = "{0} is not installed. Cannot uninstall a non-existent package.".FormatWith(packageName); var missingResult = packageResultsToReturn.GetOrAdd(packageName, new PackageResult(packageName, null, null)); missingResult.Messages.Add(new ResultMessage(ResultType.Error, logMessage)); @@ -2102,7 +2095,8 @@ public virtual ConcurrentDictionary uninstall_run(Chocola continue; } - var packageVersionsToRemove = installedPackageVersions.ToList(); + packageVersionsToRemove.AddRange(installedPackageVersions); + if (!config.AllVersions && installedPackageVersions.Count > 1) { if (config.PromptForConfirmation) @@ -2112,7 +2106,7 @@ public virtual ConcurrentDictionary uninstall_run(Chocola IList choices = new List(); const string abortChoice = "None"; choices.Add(abortChoice); - foreach (var installedVersion in installedPackageVersions.or_empty_list_if_null()) + foreach (var installedVersion in installedPackageVersions.OrEmpty()) { choices.Add(installedVersion.Version); } @@ -2123,134 +2117,221 @@ public virtual ConcurrentDictionary uninstall_run(Chocola choices.Add(allVersionsChoice); } - var selection = InteractivePrompt.prompt_for_confirmation("Which version of {0} would you like to uninstall?".format_with(packageName), + var selection = InteractivePrompt.PromptForConfirmation("Which version of {0} would you like to uninstall?".FormatWith(packageName), choices, defaultChoice: null, requireAnswer: true, allowShortAnswer: false); if (string.IsNullOrWhiteSpace(selection)) continue; - if (selection.is_equal_to(abortChoice)) continue; - if (selection.is_equal_to(allVersionsChoice)) + if (selection.IsEqualTo(abortChoice)) continue; + if (selection.IsEqualTo(allVersionsChoice)) { - packageVersionsToRemove = installedPackageVersions.ToList(); - if (config.RegularOutput) this.Log().Info(() => "You selected to remove all versions of {0}".format_with(packageName)); + packageVersionsToRemove.AddRange(installedPackageVersions.ToList()); + if (config.RegularOutput) this.Log().Info(() => "You selected to remove all versions of {0}".FormatWith(packageName)); } else { - PackageResult pkg = installedPackageVersions.FirstOrDefault((p) => p.Version.is_equal_to(selection)); + PackageResult pkg = installedPackageVersions.FirstOrDefault((p) => p.Version.IsEqualTo(selection)); packageVersionsToRemove.Add(pkg); - if (config.RegularOutput) this.Log().Info(() => "You selected {0} v{1}".format_with(pkg.Name, pkg.Version)); + if (config.RegularOutput) this.Log().Info(() => "You selected {0} v{1}".FormatWith(pkg.Name, pkg.Version)); } } } + } + + foreach (var installedPackage in GetUninstallOrder(packageVersionsToRemove)) + { + //Need to get this again for dependency resolution + allLocalPackages = GetInstalledPackages(config); + var packagesToUninstall = new HashSet(); + var localPackagesDependencyInfos = new HashSet(PackageIdentityComparer.Default); + var pathResolver = NugetCommon.GetPathResolver(_fileSystem); + var nugetProject = new FolderNuGetProject(ApplicationParameters.PackagesLocation, pathResolver, NuGetFramework.AnyFramework); - foreach (var installedPackage in packageVersionsToRemove) + var pkgInfo = _packageInfoService.Get(installedPackage.PackageMetadata); + if (pkgInfo != null && pkgInfo.IsPinned) { - //Need to get this again for dependency resolution - allLocalPackages = get_all_installed_packages(config); - var packagesToUninstall = new HashSet(); - var localPackagesDependencyInfos = new HashSet(PackageIdentityComparer.Default); - var pathResolver = NugetCommon.GetPathResolver(config, _fileSystem); - var nugetProject = new FolderNuGetProject(ApplicationParameters.PackagesLocation, pathResolver, NuGetFramework.AnyFramework); + var logMessage = "{0} is pinned. Skipping pinned package.".FormatWith(installedPackage.Name); + var pinnedResult = packageResultsToReturn.GetOrAdd(installedPackage.Name, new PackageResult(installedPackage.Name, null, null)); + pinnedResult.Messages.Add(new ResultMessage(ResultType.Warn, logMessage)); + pinnedResult.Messages.Add(new ResultMessage(ResultType.Inconclusive, logMessage)); + if (config.RegularOutput) this.Log().Warn(ChocolateyLoggers.Important, logMessage); + continue; + } - var pkgInfo = _packageInfoService.get_package_information(installedPackage.PackageMetadata); - if (pkgInfo != null && pkgInfo.IsPinned) + if (performAction) + { + var allPackagesIdentities = allLocalPackages.Where(p => !p.Identity.Equals(installedPackage)).Select(p => p.SearchMetadata.Identity).ToList(); + localPackagesDependencyInfos.AddRange(allLocalPackages + .Select( + p => new SourcePackageDependencyInfo( + p.SearchMetadata.Identity, + p.PackageMetadata.DependencyGroups.SelectMany(x => x.Packages).ToList(), + true, + localRepositorySource, + null, + null))); + var uninstallationContext = new UninstallationContext(removeDependencies: config.ForceDependencies, forceRemove: config.Force, warnDependencyResolvingFailure: true); + + ICollection resolvedPackages = null; + try { - string logMessage = "{0} is pinned. Skipping pinned package.".format_with(packageName); - var pinnedResult = packageResultsToReturn.GetOrAdd(packageName, new PackageResult(packageName, null, null)); - pinnedResult.Messages.Add(new ResultMessage(ResultType.Warn, logMessage)); - pinnedResult.Messages.Add(new ResultMessage(ResultType.Inconclusive, logMessage)); - if (config.RegularOutput) this.Log().Warn(ChocolateyLoggers.Important, logMessage); + resolvedPackages = UninstallResolver.GetPackagesToBeUninstalled(installedPackage.Identity, localPackagesDependencyInfos, allPackagesIdentities, uninstallationContext, _nugetLogger); + } + catch (Exception ex) + { + this.Log().Warn("[NuGet]: {0}", ex.Message); + var result = packageResultsToReturn.GetOrAdd(installedPackage.Name + "." + installedPackage.Version, (key) => new PackageResult(installedPackage.PackageMetadata, pathResolver.GetInstallPath(installedPackage.PackageMetadata.Id))); + result.Messages.Add(new ResultMessage(ResultType.Error, ex.Message)); continue; } - if (performAction) + if (resolvedPackages is null) { - var allPackagesIdentities = allLocalPackages.Where(p => !p.Identity.Equals(installedPackage)).Select(p => p.SearchMetadata.Identity).ToList(); - localPackagesDependencyInfos.AddRange(allLocalPackages - .Select( - p => new SourcePackageDependencyInfo( - p.SearchMetadata.Identity, - p.PackageMetadata.DependencyGroups.SelectMany(x => x.Packages).ToList(), - true, - localRepositorySource, - null, - null))); - var uninstallationContext = new UninstallationContext(removeDependencies: config.ForceDependencies, forceRemove: config.Force); - var resolvedPackages = UninstallResolver.GetPackagesToBeUninstalled(installedPackage.Identity, localPackagesDependencyInfos, allPackagesIdentities, uninstallationContext); - packagesToUninstall.AddRange(allLocalPackages.Where(p => resolvedPackages.Contains(p.Identity))); + var result = packageResultsToReturn.GetOrAdd(installedPackage.Name + "." + installedPackage.Version, (key) => new PackageResult(installedPackage.PackageMetadata, pathResolver.GetInstallPath(installedPackage.PackageMetadata.Id))); + result.Messages.Add(new ResultMessage(ResultType.Error, "Unable to resolve dependency context. Not able to uninstall package.")); + continue; + } - foreach (var packageToUninstall in packagesToUninstall) + packagesToUninstall.AddRange(allLocalPackages.Where(p => resolvedPackages.Contains(p.Identity))); + + foreach (var packageToUninstall in packagesToUninstall) + { + try { - try - { - var uninstallPkgInfo = _packageInfoService.get_package_information(packageToUninstall.PackageMetadata); - backup_and_before_modify(packageToUninstall, uninstallPkgInfo, config, beforeUninstallAction); + this.Log().Info(ChocolateyLoggers.Important, @" +{0} v{1}", packageToUninstall.Name, packageToUninstall.Identity.Version.ToNormalizedStringChecked()); - var packageResult = packageResultsToReturn.GetOrAdd(packageToUninstall.Name + "." + packageToUninstall.Version.to_string(), packageToUninstall); - packageResult.InstallLocation = packageToUninstall.InstallLocation; - string logMessage = "{0}{1} v{2}{3}".format_with(Environment.NewLine, packageToUninstall.Name, packageToUninstall.Version.to_string(), config.Force ? " (forced)" : string.Empty); - packageResult.Messages.Add(new ResultMessage(ResultType.Debug, ApplicationParameters.Messages.ContinueChocolateyAction)); + var uninstallPkgInfo = _packageInfoService.Get(packageToUninstall.PackageMetadata); + BackupAndRunBeforeModify(packageToUninstall, uninstallPkgInfo, config, beforeUninstallAction); - if (continueAction != null) continueAction.Invoke(packageResult, config); + var key = packageToUninstall.Name + "." + packageToUninstall.Version.ToStringSafe(); - if (packageToUninstall != null) - { - packageToUninstall.InstallLocation = pathResolver.GetInstallPath(packageToUninstall.Identity); - try - { - //It does not throw or return false if it fails to delete something... - //var ableToDelete = nugetProject.DeletePackage(packageToUninstall.Identity, projectContext, CancellationToken.None, shouldDeleteDirectory: false).GetAwaiter().GetResult(); - remove_installation_files_unsafe(packageToUninstall.PackageMetadata, pkgInfo); - } - catch (Exception ex) - { - string errorlogMessage = "{0}:{1} {2}".format_with("Unable to remove existing package", Environment.NewLine, ex.Message); - this.Log().Warn(logMessage); - packageResult.Messages.Add(new ResultMessage(ResultType.Error, errorlogMessage)); - if (continueAction != null) continueAction.Invoke(packageResult, config); - continue; - } - } + if (packageResultsToReturn.TryRemove(key, out PackageResult removedPackage)) + { + // If we are here, we have already tried this package, as such we need + // to remove the package but keep any messages. This is required as + // Search Metadata may be null which is required later. + packageToUninstall.Messages.AddRange(removedPackage.Messages); + } - this.Log().Info(ChocolateyLoggers.Important, " {0} has been successfully uninstalled.".format_with(packageToUninstall.Name)); + var packageResult = packageResultsToReturn.GetOrAdd(key, packageToUninstall); - ensure_nupkg_is_removed(packageToUninstall.PackageMetadata, uninstallPkgInfo); - remove_installation_files(packageToUninstall.PackageMetadata, uninstallPkgInfo); + if (!packageResult.Success) + { + // Remove any previous error messages, otherwise the uninstall may show + // up as failing. + packageResult.Messages.RemoveAll(m => m.MessageType == ResultType.Error); } - catch (Exception ex) + + packageResult.InstallLocation = packageToUninstall.InstallLocation; + var logMessage = "{0}{1} v{2}{3}".FormatWith(Environment.NewLine, packageToUninstall.Name, packageToUninstall.Version.ToStringSafe(), config.Force ? " (forced)" : string.Empty); + packageResult.Messages.Add(new ResultMessage(ResultType.Debug, ApplicationParameters.Messages.ContinueChocolateyAction)); + + if (continueAction != null) continueAction.Invoke(packageResult, config); + + if (packageToUninstall != null) { - var logMessage = "{0} not uninstalled. An error occurred during uninstall:{1} {2}".format_with(packageName, Environment.NewLine, ex.Message); - this.Log().Error(ChocolateyLoggers.Important, logMessage); - var result = packageResultsToReturn.GetOrAdd(packageToUninstall.Name + "." + packageToUninstall.Version.to_string(), new PackageResult(packageToUninstall.PackageMetadata, pathResolver.GetInstallPath(packageToUninstall.PackageMetadata.Id))); - result.Messages.Add(new ResultMessage(ResultType.Error, logMessage)); - if (result.ExitCode == 0) result.ExitCode = 1; - if (config.Features.StopOnFirstPackageFailure) + packageToUninstall.InstallLocation = pathResolver.GetInstallPath(packageToUninstall.Identity); + try + { + //It does not throw or return false if it fails to delete something... + //var ableToDelete = nugetProject.DeletePackage(packageToUninstall.Identity, projectContext, CancellationToken.None, shouldDeleteDirectory: false).GetAwaiter().GetResult(); + + // If we have gotten here, it means we may only have files left to remove. + RemoveInstallationFilesUnsafe(packageToUninstall.PackageMetadata, pkgInfo); + } + catch (Exception ex) { - throw new ApplicationException("Stopping further execution as {0} has failed uninstallation".format_with(packageToUninstall.Name)); + var errorlogMessage = "{0}:{1} {2}".FormatWith("Unable to delete all existing package files. There will be leftover files requiring manual cleanup", Environment.NewLine, ex.Message); + this.Log().Warn(logMessage); + packageResult.Messages.Add(new ResultMessage(ResultType.Error, errorlogMessage)); + + // As the only reason we failed the uninstall is due to left over files, let us + // be good citizens and ensure that the nupkg file is removed so the package will + // not be listed as installed. This is needed to do manually as the package may + // have been optimized by licensed edition of Chocolatey CLI. + EnsureNupkgRemoved(packageToUninstall.PackageMetadata, throwError: false); + + // Do not call continueAction again here as it has already been called once. + //if (continueAction != null) continueAction.Invoke(packageResult, config); + continue; } - // do not call continueAction - will result in multiple passes } + + this.Log().Info(ChocolateyLoggers.Important, " {0} has been successfully uninstalled.".FormatWith(packageToUninstall.Name)); + + EnsureNupkgRemoved(packageToUninstall.PackageMetadata); + RemoveInstallationFiles(packageToUninstall.PackageMetadata, uninstallPkgInfo); + } + catch (Exception ex) + { + var logMessage = "{0} not uninstalled. An error occurred during uninstall:{1} {2}".FormatWith(installedPackage.Name, Environment.NewLine, ex.Message); + this.Log().Error(ChocolateyLoggers.Important, logMessage); + var result = packageResultsToReturn.GetOrAdd(packageToUninstall.Name + "." + packageToUninstall.Version.ToStringSafe(), new PackageResult(packageToUninstall.PackageMetadata, pathResolver.GetInstallPath(packageToUninstall.PackageMetadata.Id))); + result.Messages.Add(new ResultMessage(ResultType.Error, logMessage)); + if (result.ExitCode == 0) result.ExitCode = 1; + + if (config.Features.StopOnFirstPackageFailure) + { + throw new ApplicationException("Stopping further execution as {0} has failed uninstallation".FormatWith(packageToUninstall.Name)); + } + // do not call continueAction - will result in multiple passes } } - else - { - // continue action won't be found b/c we are not actually uninstalling (this is noop) - var result = packageResultsToReturn.GetOrAdd(installedPackage.Name + "." + installedPackage.Version.to_string(), new PackageResult(installedPackage.PackageMetadata, pathResolver.GetInstallPath(installedPackage.PackageMetadata.Id))); - if (continueAction != null) continueAction.Invoke(result, config); - } + } + else + { + // continue action won't be found b/c we are not actually uninstalling (this is noop) + var result = packageResultsToReturn.GetOrAdd(installedPackage.Name + "." + installedPackage.Version.ToStringSafe(), new PackageResult(installedPackage.PackageMetadata, pathResolver.GetInstallPath(installedPackage.PackageMetadata.Id))); + if (continueAction != null) continueAction.Invoke(result, config); } } // Reset the configuration again once we are completely done with the processing of // configurations, and make sure that we are removing any backup that was created // as part of this run. - config.reset_config(removeBackup: true); + config.RevertChanges(removeBackup: true); return packageResultsToReturn; } + private IEnumerable GetUninstallOrder(List packageVersionsToRemove) + { + var newResults = new List(); + + foreach (var package in packageVersionsToRemove) + { + var insertIndex = -1; + + foreach (var dependency in package.PackageMetadata.DependencyGroups.SelectMany(d => d.Packages)) + { + var existingPackage = newResults.FirstOrDefault(p => p.Name.IsEqualTo(dependency.Id)); + + if (existingPackage != null) + { + var index = newResults.IndexOf(existingPackage); + if (index > -1 && (index < insertIndex || insertIndex == -1)) + { + insertIndex = index; + } + } + } + + if (insertIndex >= 0) + { + newResults.Insert(insertIndex, package); + } + else + { + newResults.Add(package); + } + } + + return newResults; + } + /// /// This method should be called before any modifications are made to a package. /// Typically this should be called before doing an uninstall of an existing package @@ -2259,13 +2340,13 @@ public virtual ConcurrentDictionary uninstall_run(Chocola /// The package currently being modified. /// The current configuration. /// Any action to run before performing backup operations. Typically this is an invocation of the chocolateyBeforeModify script. - protected void backup_and_before_modify( + protected void BackupAndRunBeforeModify( PackageResult packageResult, ChocolateyConfiguration config, Action beforeModifyAction) { - var packageInformation = _packageInfoService.get_package_information(packageResult.PackageMetadata); - backup_and_before_modify(packageResult, packageInformation, config, beforeModifyAction); + var packageInformation = _packageInfoService.Get(packageResult.PackageMetadata); + BackupAndRunBeforeModify(packageResult, packageInformation, config, beforeModifyAction); } /// @@ -2277,7 +2358,7 @@ protected void backup_and_before_modify( /// The package information for the package being modified. /// The current configuration. /// Any action to run before performing backup operations. Typically this is an invocation of the chocolateyBeforeModify script. - protected virtual void backup_and_before_modify( + protected virtual void BackupAndRunBeforeModify( PackageResult packageResult, ChocolateyPackageInformation packageInformation, ChocolateyConfiguration config, @@ -2291,12 +2372,34 @@ protected virtual void backup_and_before_modify( if (beforeModifyAction != null) { "chocolatey".Log().Debug("Running beforeModify step for '{0}'", packageResult.PackageMetadata.Id); - beforeModifyAction(packageResult, config); + + var packageResultCopy = new PackageResult(packageResult.PackageMetadata, packageResult.SearchMetadata, packageResult.InstallLocation, packageResult.Source); + + beforeModifyAction(packageResultCopy, config); + + packageResult.Messages.AddRange(packageResultCopy.Messages.Select(m => + { + if (m.MessageType == ResultType.Error) + { + // We don't want any errors to stop execution when running before modify + // scripts. As such we will re-add this message as a warning instead. + if (m.Message.ContainsSafe("Error while running")) + { + return new ResultMessage(ResultType.Warn, "Error while running the 'chocolateyBeforeModify.ps1'."); + } + else + { + return new ResultMessage(ResultType.Warn, m.Message); + } + } + + return m; + })); } "chocolatey".Log().Debug("Backing up package files for '{0}'", packageResult.PackageMetadata.Id); - backup_existing_package_files(config, packageResult.PackageMetadata, packageInformation); + BackupCurrentPackageFiles(config, packageResult.PackageMetadata, packageInformation); } } catch (Exception error) @@ -2312,12 +2415,12 @@ protected virtual void backup_and_before_modify( /// The current configuration settings /// The metadata for the package to backup /// The package information to backup - protected void backup_existing_package_files(ChocolateyConfiguration config, IPackageMetadata package, ChocolateyPackageInformation packageInformation) + protected void BackupCurrentPackageFiles(ChocolateyConfiguration config, IPackageMetadata package, ChocolateyPackageInformation packageInformation) { - remove_rollback_directory_if_exists(package.Id); - ensure_package_files_have_compatible_attributes(config, package); - backup_existing_version(config, packageInformation); - remove_shim_directors(config, package); + EnsureBackupDirectoryRemoved(package.Id); + EnsurePackageFilesHaveCompatibleAttributes(config, package); + BackupCurrentVersion(config, packageInformation); + RemoveShimgenDirectors(package); } /// @@ -2325,111 +2428,130 @@ protected void backup_existing_package_files(ChocolateyConfiguration config, IPa /// Ensure that the package is deleted or throw an error. /// /// The installed package. - /// The package information. - private void ensure_nupkg_is_removed(IPackageMetadata removedPackage, ChocolateyPackageInformation pkgInfo) + /// Whether failing to remove the nuget package should throw an exception or not. + private void EnsureNupkgRemoved(IPackageMetadata removedPackage, bool throwError = true) { this.Log().Debug(ChocolateyLoggers.Verbose, "Removing nupkg if it still exists."); - var nupkgFile = "{0}.nupkg".format_with(removedPackage.Id); - var installDir = _fileSystem.combine_paths(ApplicationParameters.PackagesLocation, removedPackage.Id); - var nupkg = _fileSystem.combine_paths(installDir, nupkgFile); + var nupkgFile = "{0}.nupkg".FormatWith(removedPackage.Id); + var installDir = _fileSystem.CombinePaths(ApplicationParameters.PackagesLocation, removedPackage.Id); + var nupkg = _fileSystem.CombinePaths(installDir, nupkgFile); - if (!_fileSystem.file_exists(nupkg)) return; + if (!_fileSystem.FileExists(nupkg)) return; - FaultTolerance.try_catch_with_logging_exception( - () => _fileSystem.delete_file(nupkg), + FaultTolerance.TryCatchWithLoggingException( + () => _fileSystem.DeleteFile(nupkg), "Error deleting nupkg file", - throwError: true); + throwError: throwError); } - private void fix_nuspec_casing(IPackageSearchMetadata packageMetadata, string packageLocation) + protected void NormalizeNuspecCasing(IPackageSearchMetadata packageMetadata, string packageLocation) { - if (Platform.get_platform() == PlatformType.Windows) return; + if (Platform.GetPlatform() == PlatformType.Windows) return; this.Log().Debug(ChocolateyLoggers.Verbose, "Fixing nuspec casing if required"); - var expectedNuspec = _fileSystem.combine_paths(packageLocation, "{0}{1}" - .format_with(packageMetadata.Identity.Id, NuGetConstants.ManifestExtension)); - var lowercaseNuspec = _fileSystem.combine_paths(packageLocation, "{0}{1}" - .format_with(packageMetadata.Identity.Id.to_lower(), NuGetConstants.ManifestExtension)); + var expectedNuspec = _fileSystem.CombinePaths(packageLocation, "{0}{1}" + .FormatWith(packageMetadata.Identity.Id, NuGetConstants.ManifestExtension)); + var lowercaseNuspec = _fileSystem.CombinePaths(packageLocation, "{0}{1}" + .FormatWith(packageMetadata.Identity.Id.ToLowerSafe(), NuGetConstants.ManifestExtension)); - if (!_fileSystem.file_exists(expectedNuspec) && _fileSystem.file_exists(lowercaseNuspec)) + if (!_fileSystem.FileExists(expectedNuspec) && _fileSystem.FileExists(lowercaseNuspec)) { - FaultTolerance.try_catch_with_logging_exception( - () => _fileSystem.move_file(lowercaseNuspec, expectedNuspec), - "Error moving nuspec file {0} to {1}".format_with(lowercaseNuspec, expectedNuspec), + FaultTolerance.TryCatchWithLoggingException( + () => _fileSystem.MoveFile(lowercaseNuspec, expectedNuspec), + "Error moving nuspec file {0} to {1}".FormatWith(lowercaseNuspec, expectedNuspec), throwError: true); } } - public virtual void remove_installation_files_unsafe(IPackageMetadata removedPackage, ChocolateyPackageInformation pkgInfo) + public virtual void RemoveInstallationFilesUnsafe(IPackageMetadata removedPackage, ChocolateyPackageInformation pkgInfo) { this.Log().Debug(ChocolateyLoggers.Verbose, "Ensuring removal of installation files."); - var installDir = _fileSystem.combine_paths(ApplicationParameters.PackagesLocation, removedPackage.Id); + var installDir = _fileSystem.CombinePaths(ApplicationParameters.PackagesLocation, removedPackage.Id); - if (_fileSystem.directory_exists(installDir) && pkgInfo != null && pkgInfo.FilesSnapshot != null) + if (_fileSystem.DirectoryExists(installDir) && pkgInfo != null && pkgInfo.FilesSnapshot != null) { - foreach (var file in _fileSystem.get_files(installDir, "*.*", SearchOption.AllDirectories).or_empty_list_if_null()) + var exceptions = new List(); + + foreach (var file in _fileSystem.GetFiles(installDir, "*.*", SearchOption.AllDirectories).OrEmpty()) { - var fileSnapshot = pkgInfo.FilesSnapshot.Files.FirstOrDefault(f => f.Path.is_equal_to(file)); + var fileSnapshot = pkgInfo.FilesSnapshot.Files.FirstOrDefault(f => f.Path.IsEqualTo(file)); if (fileSnapshot == null) continue; - var filesystemFileChecksum = _filesService.get_package_file(file).Checksum; + var filesystemFileChecksum = _filesService.GetPackageFile(file).Checksum; if (filesystemFileChecksum == ApplicationParameters.HashProviderFileLocked) { - throw new IOException("File {0} is locked".format_with(file)); + exceptions.Add(new IOException("File {0} is locked".FormatWith(file))); + continue; } if (fileSnapshot.Checksum == filesystemFileChecksum) { - if (!_fileSystem.file_exists(file)) continue; + if (!_fileSystem.FileExists(file)) continue; - _fileSystem.delete_file(file); + try + { + _fileSystem.DeleteFile(file); + } + catch (Exception ex) + { + exceptions.Add(ex); + } } } + + if (exceptions.Count > 1) + { + throw new AggregateException(exceptions); + } + else if (exceptions.Count == 1) + { + throw exceptions[0]; + } } - if (_fileSystem.directory_exists(installDir) && !_fileSystem.get_files(installDir, "*.*", SearchOption.AllDirectories).or_empty_list_if_null().Any()) + if (_fileSystem.DirectoryExists(installDir) && !_fileSystem.GetFiles(installDir, "*.*", SearchOption.AllDirectories).OrEmpty().Any()) { - _fileSystem.delete_directory_if_exists(installDir, recursive: true); + _fileSystem.DeleteDirectoryChecked(installDir, recursive: true); } } - public virtual void remove_installation_files(IPackageMetadata removedPackage, ChocolateyPackageInformation pkgInfo) + public virtual void RemoveInstallationFiles(IPackageMetadata removedPackage, ChocolateyPackageInformation pkgInfo) { this.Log().Debug(ChocolateyLoggers.Verbose, "Ensuring removal of installation files."); - var installDir = _fileSystem.combine_paths(ApplicationParameters.PackagesLocation, removedPackage.Id); + var installDir = _fileSystem.CombinePaths(ApplicationParameters.PackagesLocation, removedPackage.Id); - if (_fileSystem.directory_exists(installDir) && pkgInfo != null && pkgInfo.FilesSnapshot != null) + if (_fileSystem.DirectoryExists(installDir) && pkgInfo != null && pkgInfo.FilesSnapshot != null) { - foreach (var file in _fileSystem.get_files(installDir, "*.*", SearchOption.AllDirectories).or_empty_list_if_null()) + foreach (var file in _fileSystem.GetFiles(installDir, "*.*", SearchOption.AllDirectories).OrEmpty()) { - var fileSnapshot = pkgInfo.FilesSnapshot.Files.FirstOrDefault(f => f.Path.is_equal_to(file)); + var fileSnapshot = pkgInfo.FilesSnapshot.Files.FirstOrDefault(f => f.Path.IsEqualTo(file)); if (fileSnapshot == null) continue; - if (fileSnapshot.Checksum == _filesService.get_package_file(file).Checksum) + if (fileSnapshot.Checksum == _filesService.GetPackageFile(file).Checksum) { - if (!_fileSystem.file_exists(file)) continue; + if (!_fileSystem.FileExists(file)) continue; - FaultTolerance.try_catch_with_logging_exception( - () => _fileSystem.delete_file(file), + FaultTolerance.TryCatchWithLoggingException( + () => _fileSystem.DeleteFile(file), "Error deleting file"); } if (fileSnapshot.Checksum == ApplicationParameters.HashProviderFileLocked) { - this.Log().Warn(() => "Snapshot for '{0}' was attempted when file was locked.{1} Please inspect and manually remove file{1} at '{2}'".format_with(_fileSystem.get_file_name(file), Environment.NewLine, _fileSystem.get_directory_name(file))); + this.Log().Warn(() => "Snapshot for '{0}' was attempted when file was locked.{1} Please inspect and manually remove file{1} at '{2}'".FormatWith(_fileSystem.GetFileName(file), Environment.NewLine, _fileSystem.GetDirectoryName(file))); } } } - if (_fileSystem.directory_exists(installDir) && !_fileSystem.get_files(installDir, "*.*", SearchOption.AllDirectories).or_empty_list_if_null().Any()) + if (_fileSystem.DirectoryExists(installDir) && !_fileSystem.GetFiles(installDir, "*.*", SearchOption.AllDirectories).OrEmpty().Any()) { - _fileSystem.delete_directory_if_exists(installDir, recursive: true); + _fileSystem.DeleteDirectoryChecked(installDir, recursive: true); } } - public IEnumerable get_all_installed_packages(ChocolateyConfiguration config) + public IEnumerable GetInstalledPackages(ChocolateyConfiguration config) { //todo: #2579 move to deep copy for get all installed //var listConfig = config.deep_copy(); @@ -2439,7 +2561,7 @@ public IEnumerable get_all_installed_packages(ChocolateyConfigura //listConfig.Input = string.Empty; //listConfig.QuietOutput = true; - //return list_run(listConfig).ToList(); + //return List(listConfig).ToList(); config.ListCommand.LocalOnly = true; var sources = config.Sources; @@ -2461,7 +2583,7 @@ public IEnumerable get_all_installed_packages(ChocolateyConfigura var version = config.Version; config.Version = string.Empty; - var installedPackages = list_run(config).ToList(); + var installedPackages = List(config).ToList(); config.ListCommand.IncludeVersionOverrides = includeVersionOverrides; config.QuietOutput = quiet; @@ -2475,10 +2597,10 @@ public IEnumerable get_all_installed_packages(ChocolateyConfigura return installedPackages; } - private IEnumerable set_package_names_if_all_is_specified(ChocolateyConfiguration config, Action customAction) + private IEnumerable SetPackageNamesIfAllSpecified(ChocolateyConfiguration config, Action customAction) { - var allPackages = get_all_installed_packages(config); - if (config.PackageNames.is_equal_to(ApplicationParameters.AllPackages)) + var allPackages = GetInstalledPackages(config); + if (config.PackageNames.IsEqualTo(ApplicationParameters.AllPackages)) { var packagesToUpdate= allPackages.Select(p => p.Name).ToList(); @@ -2487,7 +2609,7 @@ private IEnumerable set_package_names_if_all_is_specified(Chocola var packagesToSkip = config.UpgradeCommand.PackageNamesToSkip .Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries) .Where(item => !string.IsNullOrWhiteSpace(item)) - .Select(p => p.trim_safe()) + .Select(p => p.TrimSafe()) .ToList(); var unknownPackagesToSkip = packagesToSkip @@ -2496,7 +2618,7 @@ private IEnumerable set_package_names_if_all_is_specified(Chocola if (unknownPackagesToSkip.Any()) { - this.Log().Warn(() => "Some packages specified in the 'except' list were not found in the local packages: '{0}'".format_with(string.Join(",", unknownPackagesToSkip))); + this.Log().Warn(() => "Some packages specified in the 'except' list were not found in the local packages: '{0}'".FormatWith(string.Join(",", unknownPackagesToSkip))); packagesToSkip = packagesToSkip .Where(p => !unknownPackagesToSkip.Contains(p, StringComparer.OrdinalIgnoreCase)) @@ -2511,16 +2633,152 @@ private IEnumerable set_package_names_if_all_is_specified(Chocola allPackages = allPackages.Where(p => !packagesToSkip.Contains(p.Name, StringComparer.OrdinalIgnoreCase)); - this.Log().Info(() => "These packages will not be upgraded because they were specified in the 'except' list: {0}".format_with(string.Join(",", packagesToSkip))); + this.Log().Info(() => "These packages will not be upgraded because they were specified in the 'except' list: {0}".FormatWith(string.Join(",", packagesToSkip))); } } - config.PackageNames = packagesToUpdate.@join(ApplicationParameters.PackageNamesSeparator); + config.PackageNames = packagesToUpdate.Join(ApplicationParameters.PackageNamesSeparator); if (customAction != null) customAction.Invoke(); } return allPackages; } + +#pragma warning disable IDE1006 + [Obsolete("This overload is deprecated and will be removed in v3.")] + public void ensure_source_app_installed(ChocolateyConfiguration config, Action ensureAction) + => EnsureSourceAppInstalled(config, ensureAction); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public virtual int count_run(ChocolateyConfiguration config) + => Count(config); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public virtual void list_noop(ChocolateyConfiguration config) + => ListDryRun(config); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public virtual IEnumerable list_run(ChocolateyConfiguration config) + => List(config); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public void pack_noop(ChocolateyConfiguration config) + => PackDryRun(config); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public virtual string validate_and_return_package_file(ChocolateyConfiguration config, string extension) + => GetPackageFileOrThrow(config, extension); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public virtual void pack_run(ChocolateyConfiguration config) + => Pack(config); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public void push_noop(ChocolateyConfiguration config) + => PushDryRun(config); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public virtual void push_run(ChocolateyConfiguration config) + => Push(config); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public void install_noop(ChocolateyConfiguration config, Action continueAction) + => InstallDryRun(config, continueAction); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public virtual ConcurrentDictionary install_run(ChocolateyConfiguration config, Action continueAction) + => Install(config, continueAction); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public virtual ConcurrentDictionary install_run(ChocolateyConfiguration config, Action continueAction, Action beforeModifyAction) + => Install(config, continueAction, beforeModifyAction); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + protected virtual string get_dependency_resolution_error_message(NuGetResolverConstraintException exception) + => GetDependencyResolutionErrorMessage(exception); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public virtual void remove_rollback_directory_if_exists(string packageName) + => EnsureBackupDirectoryRemoved(packageName); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public ConcurrentDictionary upgrade_noop(ChocolateyConfiguration config, Action continueAction) + => UpgradeDryRun(config, continueAction); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public ConcurrentDictionary upgrade_run(ChocolateyConfiguration config, Action continueAction, Action beforeUpgradeAction = null) + => Upgrade(config, continueAction, beforeUpgradeAction); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public virtual ConcurrentDictionary upgrade_run(ChocolateyConfiguration config, Action continueAction, bool performAction, Action beforeUpgradeAction = null) + => Upgrade(config, continueAction, performAction, beforeUpgradeAction); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public virtual ConcurrentDictionary get_outdated(ChocolateyConfiguration config) + => GetOutdated(config); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + protected virtual ChocolateyConfiguration set_package_config_for_upgrade(ChocolateyConfiguration config, ChocolateyPackageInformation packageInfo) + => SetConfigFromRememberedArguments(config, packageInfo); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + protected virtual void ensure_package_files_have_compatible_attributes(ChocolateyConfiguration config, IPackageMetadata installedPackage) + => EnsurePackageFilesHaveCompatibleAttributes(config, installedPackage); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + protected virtual void backup_existing_version(ChocolateyConfiguration config, ChocolateyPackageInformation packageInfo) + => BackupCurrentVersion(config, packageInfo); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public virtual void remove_packaging_files_prior_to_upgrade(string directoryPath, string commandName) + => RemoveOldPackageScriptsBeforeUpgrade(directoryPath, commandName); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public virtual void backup_changed_files(string packageInstallPath, ChocolateyConfiguration config, ChocolateyPackageInformation packageInfo) + => BackupChangedFiles(packageInstallPath, config, packageInfo); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public void uninstall_noop(ChocolateyConfiguration config, Action continueAction) + => UninstallDryRun(config, continueAction); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public ConcurrentDictionary uninstall_run(ChocolateyConfiguration config, Action continueAction, Action beforeUninstallAction = null) + => Uninstall(config, continueAction, beforeUninstallAction); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public virtual ConcurrentDictionary uninstall_run(ChocolateyConfiguration config, Action continueAction, bool performAction, Action beforeUninstallAction = null) + => Uninstall(config, continueAction, performAction, beforeUninstallAction); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + protected void backup_and_before_modify( + PackageResult packageResult, + ChocolateyConfiguration config, + Action beforeModifyAction) + => BackupAndRunBeforeModify(packageResult, config, beforeModifyAction); + [Obsolete("This overload is deprecated and will be removed in v3.")] + protected virtual void backup_and_before_modify( + PackageResult packageResult, + ChocolateyPackageInformation packageInformation, + ChocolateyConfiguration config, + Action beforeModifyAction) + => BackupAndRunBeforeModify(packageResult, packageInformation, config, beforeModifyAction); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + protected void backup_existing_package_files(ChocolateyConfiguration config, IPackageMetadata package, ChocolateyPackageInformation packageInformation) + => BackupCurrentPackageFiles(config, package, packageInformation); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public virtual void remove_installation_files_unsafe(IPackageMetadata removedPackage, ChocolateyPackageInformation pkgInfo) + => RemoveInstallationFilesUnsafe(removedPackage, pkgInfo); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public virtual void remove_installation_files(IPackageMetadata removedPackage, ChocolateyPackageInformation pkgInfo) + => RemoveInstallationFiles(removedPackage, pkgInfo); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public IEnumerable get_all_installed_packages(ChocolateyConfiguration config) + => GetInstalledPackages(config); +#pragma warning restore IDE1006 } } diff --git a/src/chocolatey/infrastructure.app/services/PendingRebootService.cs b/src/chocolatey/infrastructure.app/services/PendingRebootService.cs index b9fd1b8f39..d4251504dd 100644 --- a/src/chocolatey/infrastructure.app/services/PendingRebootService.cs +++ b/src/chocolatey/infrastructure.app/services/PendingRebootService.cs @@ -19,6 +19,7 @@ namespace chocolatey.infrastructure.app.services using configuration; using Microsoft.Win32; using platforms; + using System; /// /// Service to check for System level pending reboot request @@ -38,7 +39,7 @@ public PendingRebootService(IRegistryService registryService) /// /// The current Chocolatey Configuration /// true if reboot is required; otherwise false. - public bool is_pending_reboot(ChocolateyConfiguration config) + public bool IsRebootPending(ChocolateyConfiguration config) { if (config.Information.PlatformType != PlatformType.Windows) { @@ -48,12 +49,12 @@ public bool is_pending_reboot(ChocolateyConfiguration config) this.Log().Debug(" Reboot Requirement Checks:"); // note this is short-circuited, if one trips, it won't continue the checks - return is_pending_computer_rename() || - is_pending_component_based_servicing() || - is_pending_windows_auto_update() || - is_pending_file_rename_operations() || - is_pending_package_installer() || - is_pending_package_installer_syswow64(); + return IsPendingComputerRename() || + IsPendingComponentBasedServicing() || + IsPendingWindowsAutoUpdate() || + IsPendingFileRenameOperation() || + IsPendingPackageInstaller() || + IsPendingPackageInstallerSysWow64(); } /// @@ -62,17 +63,17 @@ public bool is_pending_reboot(ChocolateyConfiguration config) /// /// true if [is pending computer rename]; otherwise, false. /// - private bool is_pending_computer_rename() + private bool IsPendingComputerRename() { var path = "SYSTEM\\CurrentControlSet\\Control\\ComputerName\\{0}"; - var activeName = get_registry_key_string_value(path.format_with("ActiveComputerName"), "ComputerName"); - var pendingName = get_registry_key_string_value(path.format_with("ComputerName"), "ComputerName"); + var activeName = GetRegistryKeyString(path.FormatWith("ActiveComputerName"), "ComputerName"); + var pendingName = GetRegistryKeyString(path.FormatWith("ComputerName"), "ComputerName"); bool result = !string.IsNullOrWhiteSpace(activeName) && !string.IsNullOrWhiteSpace(pendingName) && activeName != pendingName; - this.Log().Debug(" - Pending Computer Rename = {0}".format_with(result ? "Flagged" : "Checked")); + this.Log().Debug(" - Pending Computer Rename = {0}".FormatWith(result ? "Flagged" : "Checked")); return result; } @@ -88,19 +89,19 @@ private bool is_pending_computer_rename() /// /// https://blogs.technet.microsoft.com/askperf/2008/04/23/understanding-component-based-servicing/ /// - private bool is_pending_component_based_servicing() + private bool IsPendingComponentBasedServicing() { - if (!is_vista_sp1_or_later()) + if (!IsAtLeastVistaSp1()) { this.Log().Trace("Not using Windows Vista SP1 or earlier, so no check for Component Based Servicing can be made."); return false; } var path = "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Component Based Servicing\\RebootPending"; - var key = _registryService.get_key(RegistryHive.LocalMachine, path); + var key = _registryService.GetKey(RegistryHive.LocalMachine, path); var result = key != null; - this.Log().Debug(" - Pending Component Based Servicing = {0}".format_with(result ? "Flagged" : "Checked")); + this.Log().Debug(" - Pending Component Based Servicing = {0}".FormatWith(result ? "Flagged" : "Checked")); return result; } @@ -111,13 +112,13 @@ private bool is_pending_component_based_servicing() /// /// true if is pending windows automatic update; otherwise, false. /// - private bool is_pending_windows_auto_update() + private bool IsPendingWindowsAutoUpdate() { var path = "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\WindowsUpdate\\Auto Update\\RebootRequired"; - var key = _registryService.get_key(RegistryHive.LocalMachine, path); + var key = _registryService.GetKey(RegistryHive.LocalMachine, path); var result = key != null; - this.Log().Debug(" - Pending Windows Auto Update = {0}".format_with(result ? "Flagged" : "Checked")); + this.Log().Debug(" - Pending Windows Auto Update = {0}".FormatWith(result ? "Flagged" : "Checked")); return result; } @@ -128,10 +129,10 @@ private bool is_pending_windows_auto_update() /// /// false, however, additional information provided in debug log to indicate if it was ignored. /// - private bool is_pending_file_rename_operations() + private bool IsPendingFileRenameOperation() { var path = "SYSTEM\\CurrentControlSet\\Control\\Session Manager"; - var value = get_registry_key_value(path, "PendingFileRenameOperations"); + var value = GetRegistryKeyValue(path, "PendingFileRenameOperations"); var result = false; @@ -140,7 +141,7 @@ private bool is_pending_file_rename_operations() result = (value as string[]).Length != 0; } - this.Log().Debug(" - Pending File Rename Operations = {0}".format_with(result ? "Ignored" : "Checked")); + this.Log().Debug(" - Pending File Rename Operations = {0}".FormatWith(result ? "Ignored" : "Checked")); // Always return false, as we don't want this check to result in a pending reboot warning/error. // Instead, this will only provide output in the debug log indicating that the check was ignored. @@ -157,14 +158,14 @@ private bool is_pending_file_rename_operations() /// https://support.microsoft.com/kb/832475 /// 0x00000000 (0) No pending restart. /// - private bool is_pending_package_installer() + private bool IsPendingPackageInstaller() { var path = "SOFTWARE\\Microsoft\\Updates"; - var value = get_registry_key_string_value(path, "UpdateExeVolatile"); + var value = GetRegistryKeyString(path, "UpdateExeVolatile"); var result = !string.IsNullOrWhiteSpace(value) && value != "0"; - this.Log().Debug(" - Pending Windows Package Installer = {0}".format_with(result ? "Flagged" : "Checked")); + this.Log().Debug(" - Pending Windows Package Installer = {0}".FormatWith(result ? "Flagged" : "Checked")); return result; } @@ -179,33 +180,33 @@ private bool is_pending_package_installer() /// https://support.microsoft.com/kb/832475 /// 0x00000000 (0) No pending restart. /// - private bool is_pending_package_installer_syswow64() + private bool IsPendingPackageInstallerSysWow64() { var path = "SOFTWARE\\Wow6432Node\\Microsoft\\Updates"; - var value = get_registry_key_string_value(path, "UpdateExeVolatile"); + var value = GetRegistryKeyString(path, "UpdateExeVolatile"); var result = !string.IsNullOrWhiteSpace(value) && value != "0"; - this.Log().Debug(" - Pending Windows Package Installer SysWow64 = {0}".format_with(result ? "Flagged" : "Checked")); + this.Log().Debug(" - Pending Windows Package Installer SysWow64 = {0}".FormatWith(result ? "Flagged" : "Checked")); return result; } - private string get_registry_key_string_value(string path, string value) + private string GetRegistryKeyString(string path, string value) { - var key = _registryService.get_key(RegistryHive.LocalMachine, path); + var key = _registryService.GetKey(RegistryHive.LocalMachine, path); if (key == null) { return string.Empty; } - return key.GetValue(value, string.Empty).to_string(); + return key.GetValue(value, string.Empty).ToStringSafe(); } - private object get_registry_key_value(string path, string value) + private object GetRegistryKeyValue(string path, string value) { - var key = _registryService.get_key(RegistryHive.LocalMachine, path); + var key = _registryService.GetKey(RegistryHive.LocalMachine, path); if (key == null) { @@ -215,13 +216,19 @@ private object get_registry_key_value(string path, string value) return key.GetValue(value, null); } - private bool is_vista_sp1_or_later() + private bool IsAtLeastVistaSp1() { - var versionNumber = Platform.get_version(); + var versionNumber = Platform.GetVersion(); - this.Log().Trace(" Operating System Version Number: {0}".format_with(versionNumber)); + this.Log().Trace(" Operating System Version Number: {0}".FormatWith(versionNumber)); return versionNumber.Build >= 6001; } + +#pragma warning disable IDE1006 + [Obsolete("This overload is deprecated and will be removed in v3.")] + public bool is_pending_reboot(ChocolateyConfiguration config) + => IsRebootPending(config); +#pragma warning restore IDE1006 } } diff --git a/src/chocolatey/infrastructure.app/services/PowershellService.cs b/src/chocolatey/infrastructure.app/services/PowershellService.cs index 08e336f493..90b5835a07 100644 --- a/src/chocolatey/infrastructure.app/services/PowershellService.cs +++ b/src/chocolatey/infrastructure.app/services/PowershellService.cs @@ -62,22 +62,22 @@ public PowershellService(IFileSystem fileSystem, CustomString customImports) _customImports = customImports; } - private string get_script_for_action(PackageResult packageResult, CommandNameType command) + private string GetPackageScriptForAction(PackageResult packageResult, CommandNameType command) { var file = "chocolateyInstall.ps1"; switch (command) { - case CommandNameType.uninstall: + case CommandNameType.Uninstall: file = "chocolateyUninstall.ps1"; break; - case CommandNameType.upgrade: + case CommandNameType.Upgrade: file = "chocolateyBeforeModify.ps1"; break; } var packageDirectory = packageResult.InstallLocation; - var installScript = _fileSystem.get_files(packageDirectory, file, SearchOption.AllDirectories).Where(p => !p.to_lower().contains("\\templates\\")); + var installScript = _fileSystem.GetFiles(packageDirectory, file, SearchOption.AllDirectories).Where(p => !p.ToLowerSafe().ContainsSafe("\\templates\\")); if (installScript.Count() != 0) { return installScript.FirstOrDefault(); @@ -86,7 +86,7 @@ private string get_script_for_action(PackageResult packageResult, CommandNameTyp return string.Empty; } - private IEnumerable get_hook_scripts(ChocolateyConfiguration configuration, PackageResult packageResult, CommandNameType command, bool isPreHook) + private IEnumerable GetHookScripts(ChocolateyConfiguration configuration, PackageResult packageResult, CommandNameType command, bool isPreHook) { List hookScriptPaths = new List(); @@ -94,7 +94,7 @@ private IEnumerable get_hook_scripts(ChocolateyConfiguration configurati if (configuration.SkipHookScripts) return hookScriptPaths; // If hooks directory doesn't exist, return an empty list to prevent directory not exist warnings - if (!_fileSystem.directory_exists(ApplicationParameters.HooksLocation)) return hookScriptPaths; + if (!_fileSystem.DirectoryExists(ApplicationParameters.HooksLocation)) return hookScriptPaths; string filenameBase; @@ -109,110 +109,110 @@ private IEnumerable get_hook_scripts(ChocolateyConfiguration configurati switch (command) { - case CommandNameType.install: + case CommandNameType.Install: filenameBase += "install-"; break; - case CommandNameType.uninstall: + case CommandNameType.Uninstall: filenameBase += "uninstall-"; break; - case CommandNameType.upgrade: + case CommandNameType.Upgrade: filenameBase += "beforemodify-"; break; default: - throw new ApplicationException("Could not find CommandNameType '{0}' to get hook scripts".format_with(command)); + throw new ApplicationException("Could not find CommandNameType '{0}' to get hook scripts".FormatWith(command)); } - hookScriptPaths.AddRange(_fileSystem.get_files(ApplicationParameters.HooksLocation, "{0}all.ps1".format_with(filenameBase), SearchOption.AllDirectories)); - hookScriptPaths.AddRange(_fileSystem.get_files(ApplicationParameters.HooksLocation, "{0}{1}.ps1".format_with(filenameBase, packageResult.Name), SearchOption.AllDirectories)); + hookScriptPaths.AddRange(_fileSystem.GetFiles(ApplicationParameters.HooksLocation, "{0}all.ps1".FormatWith(filenameBase), SearchOption.AllDirectories)); + hookScriptPaths.AddRange(_fileSystem.GetFiles(ApplicationParameters.HooksLocation, "{0}{1}.ps1".FormatWith(filenameBase, packageResult.Name), SearchOption.AllDirectories)); return hookScriptPaths; } - public void noop_action(PackageResult packageResult, CommandNameType command) + public void DryRunAction(PackageResult packageResult, CommandNameType command) { - var chocoInstall = get_script_for_action(packageResult, command); + var chocoInstall = GetPackageScriptForAction(packageResult, command); if (!string.IsNullOrEmpty(chocoInstall)) { - this.Log().Info("Would have run '{0}':".format_with(_fileSystem.get_file_name(chocoInstall))); - this.Log().Warn(_fileSystem.read_file(chocoInstall).escape_curly_braces()); + this.Log().Info("Would have run '{0}':".FormatWith(_fileSystem.GetFileName(chocoInstall))); + this.Log().Warn(_fileSystem.ReadFile(chocoInstall).EscapeCurlyBraces()); } } - public void install_noop(PackageResult packageResult) + public void InstallDryRun(PackageResult packageResult) { - noop_action(packageResult, CommandNameType.install); + DryRunAction(packageResult, CommandNameType.Install); } - public bool install(ChocolateyConfiguration configuration, PackageResult packageResult) + public bool Install(ChocolateyConfiguration configuration, PackageResult packageResult) { - return run_action(configuration, packageResult, CommandNameType.install); + return RunAction(configuration, packageResult, CommandNameType.Install); } - public void uninstall_noop(PackageResult packageResult) + public void UninstallDryRun(PackageResult packageResult) { - noop_action(packageResult, CommandNameType.uninstall); + DryRunAction(packageResult, CommandNameType.Uninstall); } - public bool uninstall(ChocolateyConfiguration configuration, PackageResult packageResult) + public bool Uninstall(ChocolateyConfiguration configuration, PackageResult packageResult) { - return run_action(configuration, packageResult, CommandNameType.uninstall); + return RunAction(configuration, packageResult, CommandNameType.Uninstall); } - public void before_modify_noop(PackageResult packageResult) + public void BeforeModifyDryRun(PackageResult packageResult) { - noop_action(packageResult, CommandNameType.upgrade); + DryRunAction(packageResult, CommandNameType.Upgrade); } - public bool before_modify(ChocolateyConfiguration configuration, PackageResult packageResult) + public bool BeforeModify(ChocolateyConfiguration configuration, PackageResult packageResult) { - return run_action(configuration, packageResult, CommandNameType.upgrade); + return RunAction(configuration, packageResult, CommandNameType.Upgrade); } - private string get_helpers_folder() + private string GetHelpersFolder() { - return _fileSystem.combine_paths(ApplicationParameters.InstallLocation, "helpers"); + return _fileSystem.CombinePaths(ApplicationParameters.InstallLocation, "helpers"); } - public string wrap_script_with_module(string script, IEnumerable hookPreScriptPathList, IEnumerable hookPostScriptPathList, ChocolateyConfiguration config) + public string WrapScriptWithModule(string script, IEnumerable hookPreScriptPathList, IEnumerable hookPostScriptPathList, ChocolateyConfiguration config) { - var installerModule = _fileSystem.combine_paths(get_helpers_folder(), "chocolateyInstaller.psm1"); - var scriptRunner = _fileSystem.combine_paths(get_helpers_folder(), "chocolateyScriptRunner.ps1"); + var installerModule = _fileSystem.CombinePaths(GetHelpersFolder(), "chocolateyInstaller.psm1"); + var scriptRunner = _fileSystem.CombinePaths(GetHelpersFolder(), "chocolateyScriptRunner.ps1"); // removed setting all errors to terminating. Will cause too // many issues in existing packages, including upgrading // Chocolatey from older POSH client due to log errors //$ErrorActionPreference = 'Stop'; - return "[System.Threading.Thread]::CurrentThread.CurrentCulture = '';[System.Threading.Thread]::CurrentThread.CurrentUICulture = ''; & import-module -name '{0}';{2} & '{1}' {3}" - .format_with( + return "[System.Threading.Thread]::CurrentThread.CurrentCulture = '';[System.Threading.Thread]::CurrentThread.CurrentUICulture = '';[System.Net.ServicePointManager]::SecurityProtocol = [System.Net.SecurityProtocolType]::SystemDefault; & import-module -name '{0}';{2} & '{1}' {3}" + .FormatWith( installerModule, scriptRunner, - string.IsNullOrWhiteSpace(_customImports) ? string.Empty : "& {0}".format_with(_customImports.EndsWith(";") ? _customImports : _customImports + ";"), - get_script_arguments(script, hookPreScriptPathList, hookPostScriptPathList, config) + string.IsNullOrWhiteSpace(_customImports) ? string.Empty : "& {0}".FormatWith(_customImports.EndsWith(";") ? _customImports : _customImports + ";"), + GetScriptArguments(script, hookPreScriptPathList, hookPostScriptPathList, config) ); } - private string get_script_arguments(string script, IEnumerable hookPreScriptPathList, IEnumerable hookPostScriptPathList, ChocolateyConfiguration config) + private string GetScriptArguments(string script, IEnumerable hookPreScriptPathList, IEnumerable hookPostScriptPathList, ChocolateyConfiguration config) { - return "-packageScript '{0}' -installArguments '{1}' -packageParameters '{2}'{3}{4} -preRunHookScripts {5} -postRunHookScripts {6}".format_with( + return "-packageScript '{0}' -installArguments '{1}' -packageParameters '{2}'{3}{4} -preRunHookScripts {5} -postRunHookScripts {6}".FormatWith( script, - prepare_powershell_arguments(config.InstallArguments), - prepare_powershell_arguments(config.PackageParameters), + EscapePowerShellArguments(config.InstallArguments), + EscapePowerShellArguments(config.PackageParameters), config.ForceX86 ? " -forceX86" : string.Empty, config.OverrideArguments ? " -overrideArgs" : string.Empty, - hookPreScriptPathList.Any() ? "{0}".format_with(string.Join(",", hookPreScriptPathList)) : "$null", - hookPostScriptPathList.Any() ? "{0}".format_with(string.Join(",", hookPostScriptPathList)) : "$null" + hookPreScriptPathList.Any() ? "{0}".FormatWith(string.Join(",", hookPreScriptPathList)) : "$null", + hookPostScriptPathList.Any() ? "{0}".FormatWith(string.Join(",", hookPostScriptPathList)) : "$null" ); } - private string prepare_powershell_arguments(string argument) + private string EscapePowerShellArguments(string argument) { - return argument.to_string().Replace("\"", "\\\""); + return argument.ToStringSafe().Replace("\"", "\\\""); } - public bool run_action(ChocolateyConfiguration configuration, PackageResult packageResult, CommandNameType command) + public bool RunAction(ChocolateyConfiguration configuration, PackageResult packageResult, CommandNameType command) { var installerRun = false; @@ -220,34 +220,34 @@ public bool run_action(ChocolateyConfiguration configuration, PackageResult pack Debug.Assert(packageResult.SearchMetadata != null, "SearchMetadata is null"); var packageDirectory = packageResult.InstallLocation; - if (packageDirectory.is_equal_to(ApplicationParameters.InstallLocation) || packageDirectory.is_equal_to(ApplicationParameters.PackagesLocation)) + if (packageDirectory.IsEqualTo(ApplicationParameters.InstallLocation) || packageDirectory.IsEqualTo(ApplicationParameters.PackagesLocation)) { packageResult.Messages.Add( new ResultMessage( ResultType.Error, - "Install location is not specific enough, cannot run PowerShell script:{0} Erroneous install location captured as '{1}'".format_with(Environment.NewLine, packageResult.InstallLocation) + "Install location is not specific enough, cannot run PowerShell script:{0} Erroneous install location captured as '{1}'".FormatWith(Environment.NewLine, packageResult.InstallLocation) ) ); return false; } - if (!_fileSystem.directory_exists(packageDirectory)) + if (!_fileSystem.DirectoryExists(packageDirectory)) { - packageResult.Messages.Add(new ResultMessage(ResultType.Error, "Package install not found:'{0}'".format_with(packageDirectory))); + packageResult.Messages.Add(new ResultMessage(ResultType.Error, "Package install not found:'{0}'".FormatWith(packageDirectory))); return installerRun; } - var chocoPowerShellScript = get_script_for_action(packageResult, command); + var chocoPowerShellScript = GetPackageScriptForAction(packageResult, command); - var hookPreScriptPathList = get_hook_scripts(configuration, packageResult, command, true); - var hookPostScriptPathList = get_hook_scripts(configuration, packageResult, command, false); + var hookPreScriptPathList = GetHookScripts(configuration, packageResult, command, true); + var hookPostScriptPathList = GetHookScripts(configuration, packageResult, command, false); - foreach (var hookScriptPath in hookPreScriptPathList.Concat(hookPostScriptPathList).or_empty_list_if_null()) + foreach (var hookScriptPath in hookPreScriptPathList.Concat(hookPostScriptPathList).OrEmpty()) { - this.Log().Debug(ChocolateyLoggers.Important, "Contents of '{0}':".format_with(chocoPowerShellScript)); - string hookScriptContents = _fileSystem.read_file(hookScriptPath); - this.Log().Debug(() => hookScriptContents.escape_curly_braces()); + this.Log().Debug(ChocolateyLoggers.Important, "Contents of '{0}':".FormatWith(chocoPowerShellScript)); + string hookScriptContents = _fileSystem.ReadFile(hookScriptPath); + this.Log().Debug(() => hookScriptContents.EscapeCurlyBraces()); } if (!string.IsNullOrEmpty(chocoPowerShellScript) || hookPreScriptPathList.Any() || hookPostScriptPathList.Any()) @@ -255,24 +255,24 @@ public bool run_action(ChocolateyConfiguration configuration, PackageResult pack var failure = false; var package = packageResult.SearchMetadata; - prepare_powershell_environment(package, configuration, packageDirectory); + PreparePowerShellEnvironment(package, configuration, packageDirectory); bool shouldRun = !configuration.PromptForConfirmation; if (!string.IsNullOrEmpty(chocoPowerShellScript)) { - this.Log().Debug(ChocolateyLoggers.Important, "Contents of '{0}':".format_with(chocoPowerShellScript)); - string chocoPowerShellScriptContents = _fileSystem.read_file(chocoPowerShellScript); + this.Log().Debug(ChocolateyLoggers.Important, "Contents of '{0}':".FormatWith(chocoPowerShellScript)); + string chocoPowerShellScriptContents = _fileSystem.ReadFile(chocoPowerShellScript); // leave this way, doesn't take it through formatting. - this.Log().Debug(() => chocoPowerShellScriptContents.escape_curly_braces()); + this.Log().Debug(() => chocoPowerShellScriptContents.EscapeCurlyBraces()); if (!shouldRun) { - this.Log().Info(ChocolateyLoggers.Important, () => "The package {0} wants to run '{1}'.".format_with(packageResult.Name, _fileSystem.get_file_name(chocoPowerShellScript))); + this.Log().Info(ChocolateyLoggers.Important, () => "The package {0} wants to run '{1}'.".FormatWith(packageResult.Name, _fileSystem.GetFileName(chocoPowerShellScript))); this.Log().Info(ChocolateyLoggers.Important, () => "Note: If you don't run this script, the installation will fail."); this.Log().Info(ChocolateyLoggers.Important, () => @"Note: To confirm automatically next time, use '-y' or consider:"); this.Log().Info(ChocolateyLoggers.Important, () => @"choco feature enable -n allowGlobalConfirmation"); - var selection = InteractivePrompt.prompt_for_confirmation(@"Do you want to run the script?", + var selection = InteractivePrompt.PromptForConfirmation(@"Do you want to run the script?", new[] { "yes", "all - yes to all", "no", "print" }, defaultChoice: null, requireAnswer: true, @@ -280,12 +280,12 @@ public bool run_action(ChocolateyConfiguration configuration, PackageResult pack shortPrompt: true ); - if (selection.is_equal_to("print")) + if (selection.IsEqualTo("print")) { this.Log().Info(ChocolateyLoggers.Important, "------ BEGIN SCRIPT ------"); - this.Log().Info(() => "{0}{1}{0}".format_with(Environment.NewLine, chocoPowerShellScriptContents.escape_curly_braces())); + this.Log().Info(() => "{0}{1}{0}".FormatWith(Environment.NewLine, chocoPowerShellScriptContents.EscapeCurlyBraces())); this.Log().Info(ChocolateyLoggers.Important, "------- END SCRIPT -------"); - selection = InteractivePrompt.prompt_for_confirmation(@"Do you want to run this script?", + selection = InteractivePrompt.PromptForConfirmation(@"Do you want to run this script?", new[] { "yes", "no" }, defaultChoice: null, requireAnswer: true, @@ -294,19 +294,19 @@ public bool run_action(ChocolateyConfiguration configuration, PackageResult pack ); } - if (selection.is_equal_to("yes")) shouldRun = true; - if (selection.is_equal_to("all - yes to all")) + if (selection.IsEqualTo("yes")) shouldRun = true; + if (selection.IsEqualTo("all - yes to all")) { configuration.PromptForConfirmation = false; shouldRun = true; } - if (selection.is_equal_to("no")) + if (selection.IsEqualTo("no")) { //MSI ERROR_INSTALL_USEREXIT - 1602 - https://support.microsoft.com/en-us/kb/304888 / https://msdn.microsoft.com/en-us/library/aa376931.aspx //ERROR_INSTALL_CANCEL - 15608 - https://msdn.microsoft.com/en-us/library/windows/desktop/ms681384.aspx Environment.ExitCode = 15608; - packageResult.Messages.Add(new ResultMessage(ResultType.Error, "User canceled powershell portion of installation for '{0}'.{1} Specify -n to skip automated script actions.".format_with(chocoPowerShellScript, Environment.NewLine))); + packageResult.Messages.Add(new ResultMessage(ResultType.Error, "User canceled powershell portion of installation for '{0}'.{1} Specify -n to skip automated script actions.".FormatWith(chocoPowerShellScript, Environment.NewLine))); } } } @@ -322,7 +322,7 @@ public bool run_action(ChocolateyConfiguration configuration, PackageResult pack if (configuration.Features.UsePowerShellHost) { - add_assembly_resolver(); + AddAssemblyResolver(); } var result = new PowerShellExecutionResults @@ -333,18 +333,19 @@ public bool run_action(ChocolateyConfiguration configuration, PackageResult pack try { result = configuration.Features.UsePowerShellHost - ? Execute.with_timeout(configuration.CommandExecutionTimeoutSeconds).command(() => run_host(configuration, chocoPowerShellScript, null, hookPreScriptPathList, hookPostScriptPathList), result) - : run_external_powershell(configuration, chocoPowerShellScript, hookPreScriptPathList, hookPostScriptPathList); + ? Execute.WithTimeout(configuration.CommandExecutionTimeoutSeconds).Command(() => RunHost(configuration, chocoPowerShellScript, null, hookPreScriptPathList, hookPostScriptPathList), result) + : RunExternalPowerShell(configuration, chocoPowerShellScript, hookPreScriptPathList, hookPostScriptPathList); } catch (Exception ex) { - this.Log().Error(ex.Message.escape_curly_braces()); + this.Log().Error(ex.Message.EscapeCurlyBraces()); result.ExitCode = 1; } if (configuration.Features.UsePowerShellHost) { - remove_assembly_resolver(); + RemoveAssemblyResolver(); + HttpsSecurity.Reset(); } if (result.StandardErrorWritten && configuration.Features.FailOnStandardError) @@ -385,20 +386,20 @@ public bool run_action(ChocolateyConfiguration configuration, PackageResult pack if (failure) { - packageResult.Messages.Add(new ResultMessage(ResultType.Error, "Error while running '{0}'.{1} See log for details.".format_with(chocoPowerShellScript, Environment.NewLine))); + packageResult.Messages.Add(new ResultMessage(ResultType.Error, "Error while running '{0}'.{1} See log for details.".FormatWith(chocoPowerShellScript, Environment.NewLine))); } - packageResult.Messages.Add(new ResultMessage(ResultType.Note, "Ran '{0}'".format_with(chocoPowerShellScript))); + packageResult.Messages.Add(new ResultMessage(ResultType.Note, "Ran '{0}'".FormatWith(chocoPowerShellScript))); } } return installerRun; } - private PowerShellExecutionResults run_external_powershell(ChocolateyConfiguration configuration, string chocoPowerShellScript, IEnumerable hookPreScriptPathList, IEnumerable hookPostScriptPathList) + private PowerShellExecutionResults RunExternalPowerShell(ChocolateyConfiguration configuration, string chocoPowerShellScript, IEnumerable hookPreScriptPathList, IEnumerable hookPostScriptPathList) { var result = new PowerShellExecutionResults(); - result.ExitCode = PowershellExecutor.execute( - wrap_script_with_module(chocoPowerShellScript, hookPreScriptPathList, hookPostScriptPathList, configuration), + result.ExitCode = PowershellExecutor.Execute( + WrapScriptWithModule(chocoPowerShellScript, hookPreScriptPathList, hookPostScriptPathList, configuration), _fileSystem, configuration.CommandExecutionTimeoutSeconds, (s, e) => @@ -407,46 +408,46 @@ private PowerShellExecutionResults run_external_powershell(ChocolateyConfigurati //inspect for different streams if (e.Data.StartsWith("DEBUG:")) { - this.Log().Debug(() => " " + e.Data.escape_curly_braces()); + this.Log().Debug(() => " " + e.Data.EscapeCurlyBraces()); } else if (e.Data.StartsWith("WARNING:")) { - this.Log().Warn(() => " " + e.Data.escape_curly_braces()); + this.Log().Warn(() => " " + e.Data.EscapeCurlyBraces()); } else if (e.Data.StartsWith("VERBOSE:")) { - this.Log().Info(ChocolateyLoggers.Verbose, () => " " + e.Data.escape_curly_braces()); + this.Log().Info(ChocolateyLoggers.Verbose, () => " " + e.Data.EscapeCurlyBraces()); } else { - this.Log().Info(() => " " + e.Data.escape_curly_braces()); + this.Log().Info(() => " " + e.Data.EscapeCurlyBraces()); } }, (s, e) => { if (string.IsNullOrWhiteSpace(e.Data)) return; result.StandardErrorWritten = true; - this.Log().Error(() => " " + e.Data.escape_curly_braces()); + this.Log().Error(() => " " + e.Data.EscapeCurlyBraces()); }); return result; } - public void prepare_powershell_environment(IPackageSearchMetadata package, ChocolateyConfiguration configuration, string packageDirectory) + public void PreparePowerShellEnvironment(IPackageSearchMetadata package, ChocolateyConfiguration configuration, string packageDirectory) { if (package == null) return; - EnvironmentSettings.update_environment_variables(); - EnvironmentSettings.set_environment_variables(configuration); + EnvironmentSettings.UpdateEnvironmentVariables(); + EnvironmentSettings.SetEnvironmentVariables(configuration); Environment.SetEnvironmentVariable("chocolateyPackageName", package.Identity.Id); Environment.SetEnvironmentVariable("packageName", package.Identity.Id); Environment.SetEnvironmentVariable("chocolateyPackageTitle", package.Title); Environment.SetEnvironmentVariable("packageTitle", package.Title); - Environment.SetEnvironmentVariable("chocolateyPackageVersion", package.Identity.Version.to_string()); - Environment.SetEnvironmentVariable("packageVersion", package.Identity.Version.to_string()); - Environment.SetEnvironmentVariable("chocolateyPackageVersionPrerelease", package.Identity.Version.Release.to_string()); - Environment.SetEnvironmentVariable("chocolateyPackageVersionPackageRelease", package.Identity.Version.Version.to_string()); + Environment.SetEnvironmentVariable("chocolateyPackageVersion", package.Identity.Version.ToStringSafe()); + Environment.SetEnvironmentVariable("packageVersion", package.Identity.Version.ToStringSafe()); + Environment.SetEnvironmentVariable("chocolateyPackageVersionPrerelease", package.Identity.Version.Release.ToStringSafe()); + Environment.SetEnvironmentVariable("chocolateyPackageVersionPackageRelease", package.Identity.Version.Version.ToStringSafe()); Environment.SetEnvironmentVariable("chocolateyPackageFolder", packageDirectory); Environment.SetEnvironmentVariable("packageFolder", packageDirectory); @@ -468,9 +469,9 @@ public void prepare_powershell_environment(IPackageSearchMetadata package, Choco // we only want to pass the following args to packages that would apply. // like choco install git --params '' should pass those params to git.install, // but not another package unless the switch apply-install-arguments-to-dependencies is used - if (!PackageUtility.package_is_a_dependency(configuration, package.Identity.Id) || configuration.ApplyInstallArgumentsToDependencies) + if (!PackageUtility.PackageIdHasDependencySuffix(configuration, package.Identity.Id) || configuration.ApplyInstallArgumentsToDependencies) { - this.Log().Debug(ChocolateyLoggers.Verbose, "Setting installer args for {0}".format_with(package.Identity.Id)); + this.Log().Debug(ChocolateyLoggers.Verbose, "Setting installer args for {0}".FormatWith(package.Identity.Id)); Environment.SetEnvironmentVariable("installArguments", configuration.InstallArguments); Environment.SetEnvironmentVariable("installerArguments", configuration.InstallArguments); Environment.SetEnvironmentVariable("chocolateyInstallArguments", configuration.InstallArguments); @@ -483,9 +484,9 @@ public void prepare_powershell_environment(IPackageSearchMetadata package, Choco // we only want to pass package parameters to packages that would apply. // but not another package unless the switch apply-package-parameters-to-dependencies is used - if (!PackageUtility.package_is_a_dependency(configuration, package.Identity.Id) || configuration.ApplyPackageParametersToDependencies) + if (!PackageUtility.PackageIdHasDependencySuffix(configuration, package.Identity.Id) || configuration.ApplyPackageParametersToDependencies) { - this.Log().Debug(ChocolateyLoggers.Verbose, "Setting package parameters for {0}".format_with(package.Identity.Id)); + this.Log().Debug(ChocolateyLoggers.Verbose, "Setting package parameters for {0}".FormatWith(package.Identity.Id)); Environment.SetEnvironmentVariable("packageParameters", configuration.PackageParameters); Environment.SetEnvironmentVariable("chocolateyPackageParameters", configuration.PackageParameters); } @@ -531,34 +532,34 @@ public void prepare_powershell_environment(IPackageSearchMetadata package, Choco { Environment.SetEnvironmentVariable("DownloadCacheAvailable", "true"); - foreach (var downloadCache in package.DownloadCache.or_empty_list_if_null()) + foreach (var downloadCache in package.DownloadCache.OrEmpty()) { - var urlKey = CryptoHashProvider.hash_value(downloadCache.OriginalUrl, CryptoHashProviderType.Sha256).Replace("=", string.Empty); - Environment.SetEnvironmentVariable("CacheFile_{0}".format_with(urlKey), downloadCache.FileName); - Environment.SetEnvironmentVariable("CacheChecksum_{0}".format_with(urlKey), downloadCache.Checksum); - Environment.SetEnvironmentVariable("CacheChecksumType_{0}".format_with(urlKey), "sha512"); + var urlKey = CryptoHashProvider.ComputeStringHash(downloadCache.OriginalUrl, CryptoHashProviderType.Sha256).Replace("=", string.Empty); + Environment.SetEnvironmentVariable("CacheFile_{0}".FormatWith(urlKey), downloadCache.FileName); + Environment.SetEnvironmentVariable("CacheChecksum_{0}".FormatWith(urlKey), downloadCache.Checksum); + Environment.SetEnvironmentVariable("CacheChecksumType_{0}".FormatWith(urlKey), "sha512"); } } - SecurityProtocol.set_protocol(configuration, provideWarning: false); + HttpsSecurity.Reset(); } private ResolveEventHandler _handler = null; - private void add_assembly_resolver() + private void AddAssemblyResolver() { _handler = (sender, args) => { var requestedAssembly = new AssemblyName(args.Name); - this.Log().Debug(ChocolateyLoggers.Verbose, "Redirecting {0}, requested by '{1}'".format_with(args.Name, args.RequestingAssembly == null ? string.Empty : args.RequestingAssembly.FullName)); + this.Log().Debug(ChocolateyLoggers.Verbose, "Redirecting {0}, requested by '{1}'".FormatWith(args.Name, args.RequestingAssembly == null ? string.Empty : args.RequestingAssembly.FullName)); AppDomain.CurrentDomain.AssemblyResolve -= _handler; // we build against v1 - everything should update in a kosher manner to the newest, but it may not. - var assembly = attempt_version_load(requestedAssembly, new Version(5, 0, 0, 0)) ?? attempt_version_load(requestedAssembly, new Version(4, 0, 0, 0)); - if (assembly == null) assembly = attempt_version_load(requestedAssembly, new Version(3, 0, 0, 0)); - if (assembly == null) assembly = attempt_version_load(requestedAssembly, new Version(1, 0, 0, 0)); + var assembly = TryLoadVersionedAssembly(requestedAssembly, new Version(5, 0, 0, 0)) ?? TryLoadVersionedAssembly(requestedAssembly, new Version(4, 0, 0, 0)); + if (assembly == null) assembly = TryLoadVersionedAssembly(requestedAssembly, new Version(3, 0, 0, 0)); + if (assembly == null) assembly = TryLoadVersionedAssembly(requestedAssembly, new Version(1, 0, 0, 0)); return assembly; }; @@ -566,13 +567,13 @@ private void add_assembly_resolver() AppDomain.CurrentDomain.AssemblyResolve += _handler; } - private System.Reflection.Assembly attempt_version_load(AssemblyName requestedAssembly, Version version) + private System.Reflection.Assembly TryLoadVersionedAssembly(AssemblyName requestedAssembly, Version version) { if (requestedAssembly == null) return null; requestedAssembly.Version = version; - if (requestedAssembly.Name.EndsWith(".resources", StringComparison.OrdinalIgnoreCase) && requestedAssembly.CultureInfo.Name.is_equal_to("en-US")) + if (requestedAssembly.Name.EndsWith(".resources", StringComparison.OrdinalIgnoreCase) && requestedAssembly.CultureInfo.Name.IsEqualTo("en-US")) { return null; } @@ -585,13 +586,13 @@ private System.Reflection.Assembly attempt_version_load(AssemblyName requestedAs { if (requestedAssembly.Name.EndsWith(".resources", StringComparison.OrdinalIgnoreCase)) return null; - this.Log().Debug(ChocolateyLoggers.Verbose, "Attempting to load assembly {0} failed:{1} {2}".format_with(requestedAssembly.Name, Environment.NewLine, ex.Message.escape_curly_braces())); + this.Log().Debug(ChocolateyLoggers.Verbose, "Attempting to load assembly {0} failed:{1} {2}".FormatWith(requestedAssembly.Name, Environment.NewLine, ex.Message.EscapeCurlyBraces())); return null; } } - private void remove_assembly_resolver() + private void RemoveAssemblyResolver() { if (_handler != null) { @@ -599,13 +600,7 @@ private void remove_assembly_resolver() } } - [Obsolete("This version of running the powershell host do not support running additional hooks. Use the appropriate overload instead")] - public PowerShellExecutionResults run_host(ChocolateyConfiguration config, string chocoPowershellScript, Action additionalActionsBeforeScript) - { - return run_host(config, chocoPowershellScript, additionalActionsBeforeScript, Enumerable.Empty(), Enumerable.Empty()); - } - - public PowerShellExecutionResults run_host(ChocolateyConfiguration config, string chocoPowerShellScript, Action additionalActionsBeforeScript, IEnumerable hookPreScriptPathList, IEnumerable hookPostScriptPathList) + public PowerShellExecutionResults RunHost(ChocolateyConfiguration config, string chocoPowerShellScript, Action additionalActionsBeforeScript, IEnumerable hookPreScriptPathList, IEnumerable hookPostScriptPathList) { // since we control output in the host, always set these true Environment.SetEnvironmentVariable("ChocolateyEnvironmentDebug", "true"); @@ -613,9 +608,9 @@ public PowerShellExecutionResults run_host(ChocolateyConfiguration config, strin var result = new PowerShellExecutionResults(); - string commandToRun = wrap_script_with_module(chocoPowerShellScript, hookPreScriptPathList, hookPostScriptPathList, config); + string commandToRun = WrapScriptWithModule(chocoPowerShellScript, hookPreScriptPathList, hookPostScriptPathList, config); var host = new PoshHost(config); - this.Log().Debug(() => "Calling built-in PowerShell host with ['{0}']".format_with(commandToRun.escape_curly_braces())); + this.Log().Debug(() => "Calling built-in PowerShell host with ['{0}']".FormatWith(commandToRun.EscapeCurlyBraces())); var initialSessionState = InitialSessionState.CreateDefault(); // override system execution policy without accidentally setting it @@ -647,7 +642,7 @@ public PowerShellExecutionResults run_host(ChocolateyConfiguration config, strin { while (reader.Count > 0) { - host.UI.WriteLine(reader.Read().to_string().escape_curly_braces()); + host.UI.WriteLine(reader.Read().ToStringSafe().EscapeCurlyBraces()); } } }; @@ -661,18 +656,18 @@ public PowerShellExecutionResults run_host(ChocolateyConfiguration config, strin { while (reader.Count > 0) { - host.UI.WriteErrorLine(reader.Read().to_string().escape_curly_braces()); + host.UI.WriteErrorLine(reader.Read().ToStringSafe().EscapeCurlyBraces()); } } }; var documentsFolder = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments, Environment.SpecialFolderOption.DoNotVerify); - var currentUserCurrentHostProfile = _fileSystem.combine_paths(documentsFolder, "WindowsPowerShell\\Microsoft.PowerShell_profile.ps1"); + var currentUserCurrentHostProfile = _fileSystem.CombinePaths(documentsFolder, "WindowsPowerShell\\Microsoft.PowerShell_profile.ps1"); var recreateProfileScript = @" if ((Test-Path(""{0}"")) -and ($profile -eq $null -or $profile -eq '')) {{ $global:profile = ""{1}"" }} -".format_with(documentsFolder, currentUserCurrentHostProfile); +".FormatWith(documentsFolder, currentUserCurrentHostProfile); pipeline.Commands.Add(new Command(recreateProfileScript, isScript: true, useLocalScope: false)); @@ -718,16 +713,16 @@ public PowerShellExecutionResults run_host(ChocolateyConfiguration config, strin var scriptStackTrace = record.GetType().GetProperty("ScriptStackTrace"); if (scriptStackTrace != null) { - var scriptError = scriptStackTrace.GetValue(record, null).to_string(); + var scriptError = scriptStackTrace.GetValue(record, null).ToStringSafe(); if (!string.IsNullOrWhiteSpace(scriptError)) errorStackTrace = scriptError; } } - this.Log().Error("ERROR: {0}{1}".format_with(ex.Message.escape_curly_braces(), !config.Debug ? string.Empty : "{0} {1}".format_with(Environment.NewLine, errorStackTrace.escape_curly_braces()))); + this.Log().Error("ERROR: {0}{1}".FormatWith(ex.Message.EscapeCurlyBraces(), !config.Debug ? string.Empty : "{0} {1}".FormatWith(Environment.NewLine, errorStackTrace.EscapeCurlyBraces()))); } catch (Exception ex) { // Unfortunately this doesn't print line number and character. It might be nice to get back to those items unless it involves tons of work. - this.Log().Error("ERROR: {0}{1}".format_with(ex.Message.escape_curly_braces(), !config.Debug ? string.Empty : "{0} {1}".format_with(Environment.NewLine, ex.StackTrace.escape_curly_braces()))); + this.Log().Error("ERROR: {0}{1}".FormatWith(ex.Message.EscapeCurlyBraces(), !config.Debug ? string.Empty : "{0} {1}".FormatWith(Environment.NewLine, ex.StackTrace.EscapeCurlyBraces()))); } if (pipeline.PipelineStateInfo != null) @@ -753,12 +748,58 @@ public PowerShellExecutionResults run_host(ChocolateyConfiguration config, strin } } - this.Log().Debug("Built-in PowerShell host called with ['{0}'] exited with '{1}'.".format_with(commandToRun.escape_curly_braces(), host.ExitCode)); + this.Log().Debug("Built-in PowerShell host called with ['{0}'] exited with '{1}'.".FormatWith(commandToRun.EscapeCurlyBraces(), host.ExitCode)); result.ExitCode = host.ExitCode; result.StandardErrorWritten = host.StandardErrorWritten; return result; } + +#pragma warning disable IDE1006 + [Obsolete("This overload is deprecated and will be removed in v3.")] + public void noop_action(PackageResult packageResult, CommandNameType command) + => DryRunAction(packageResult, command); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public void install_noop(PackageResult packageResult) + => InstallDryRun(packageResult); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public bool install(ChocolateyConfiguration configuration, PackageResult packageResult) + => Install(configuration, packageResult); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public void uninstall_noop(PackageResult packageResult) + => UninstallDryRun(packageResult); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public bool uninstall(ChocolateyConfiguration configuration, PackageResult packageResult) + => Uninstall(configuration, packageResult); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public void before_modify_noop(PackageResult packageResult) + => BeforeModifyDryRun(packageResult); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public bool before_modify(ChocolateyConfiguration configuration, PackageResult packageResult) + => BeforeModify(configuration, packageResult); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public string wrap_script_with_module(string script, IEnumerable hookPreScriptPathList, IEnumerable hookPostScriptPathList, ChocolateyConfiguration config) + => WrapScriptWithModule(script, hookPreScriptPathList, hookPostScriptPathList, config); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public bool run_action(ChocolateyConfiguration configuration, PackageResult packageResult, CommandNameType command) + => RunAction(configuration, packageResult, command); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public void prepare_powershell_environment(IPackageSearchMetadata package, ChocolateyConfiguration configuration, string packageDirectory) + => PreparePowerShellEnvironment(package, configuration, packageDirectory); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public PowerShellExecutionResults run_host(ChocolateyConfiguration config, string chocoPowerShellScript, Action additionalActionsBeforeScript, IEnumerable hookPreScriptPathList, IEnumerable hookPostScriptPathList) + => RunHost(config, chocoPowerShellScript, additionalActionsBeforeScript, hookPreScriptPathList, hookPostScriptPathList); +#pragma warning restore IDE1006 } } diff --git a/src/chocolatey/infrastructure.app/services/PythonService.cs b/src/chocolatey/infrastructure.app/services/PythonService.cs index 9286981148..718bbccae3 100644 --- a/src/chocolatey/infrastructure.app/services/PythonService.cs +++ b/src/chocolatey/infrastructure.app/services/PythonService.cs @@ -34,25 +34,25 @@ namespace chocolatey.infrastructure.app.services /// /// Alternative Source for Installing Python packages /// - public sealed class PythonService : ISourceRunner + public sealed class PythonService : IBootstrappableSourceRunner, IListSourceRunner, IInstallSourceRunner, IUpgradeSourceRunner, IUninstallSourceRunner { private readonly ICommandExecutor _commandExecutor; private readonly INugetService _nugetService; private readonly IFileSystem _fileSystem; private readonly IRegistryService _registryService; - private const string PACKAGE_NAME_TOKEN = "{{packagename}}"; - private const string LOG_LEVEL_TOKEN = "{{loglevel}}"; - private const string FORCE_TOKEN = "{{force}}"; - public const string PYTHON_PACKAGE = "python"; + private const string PackageNameToken = "{{packagename}}"; + private const string LogLevelToken = "{{loglevel}}"; + private const string ForceToken = "{{force}}"; + private const string PythonPackage = "python"; private string _exePath = string.Empty; - private const string APP_NAME = "Python"; - public const string PACKAGE_NAME_GROUP = "PkgName"; - public static readonly Regex InstalledRegex = new Regex(@"Successfully installed", RegexOptions.Compiled); - public static readonly Regex UninstalledRegex = new Regex(@"Successfully uninstalled", RegexOptions.Compiled); - public static readonly Regex PackageNameRegex = new Regex(@"\s(?<{0}>[^-\s]*)-".format_with(PACKAGE_NAME_GROUP), RegexOptions.Compiled); - public static readonly Regex ErrorRegex = new Regex(@"Error:", RegexOptions.Compiled); - public static readonly Regex ErrorNotFoundRegex = new Regex(@"Could not find any downloads that", RegexOptions.Compiled); + private const string AppName = "Python"; + private const string PackageNameGroup = "PkgName"; + private static readonly Regex _installedRegex = new Regex(@"Successfully installed", RegexOptions.Compiled); + private static readonly Regex _uninstalledRegex = new Regex(@"Successfully uninstalled", RegexOptions.Compiled); + private static readonly Regex _packageNameRegex = new Regex(@"\s(?<{0}>[^-\s]*)-".FormatWith(PackageNameGroup), RegexOptions.Compiled); + private static readonly Regex _errorRegex = new Regex(@"Error:", RegexOptions.Compiled); + private static readonly Regex _errorNotFoundRegex = new Regex(@"Could not find any downloads that", RegexOptions.Compiled); private readonly IDictionary _listArguments = new Dictionary(StringComparer.InvariantCultureIgnoreCase); private readonly IDictionary _installArguments = new Dictionary(StringComparer.InvariantCultureIgnoreCase); @@ -65,41 +65,41 @@ public PythonService(ICommandExecutor commandExecutor, INugetService nugetServic _nugetService = nugetService; _fileSystem = fileSystem; _registryService = registryService; - set_cmd_args_dictionaries(); + SetupCommandArgsDictionaries(); } /// /// Set any command arguments dictionaries necessary for the service /// - private void set_cmd_args_dictionaries() + private void SetupCommandArgsDictionaries() { - set_list_dictionary(_listArguments); - set_install_dictionary(_installArguments); - set_upgrade_dictionary(_upgradeArguments); - set_uninstall_dictionary(_uninstallArguments); + SetupListDictionary(_listArguments); + SetupInstallDictionary(_installArguments); + SetupUpgradeDictionary(_upgradeArguments); + SetupUninstallDictionary(_uninstallArguments); } /// /// Sets list dictionary /// - private void set_list_dictionary(IDictionary args) + private void SetupListDictionary(IDictionary args) { - set_common_args(args); + AddCommonArguments(args); args.Add("_command_", new ExternalCommandArgument { ArgumentOption = "list", Required = true }); } /// /// Sets install dictionary /// - private void set_install_dictionary(IDictionary args) + private void SetupInstallDictionary(IDictionary args) { - set_common_args(args); + AddCommonArguments(args); args.Add("_command_", new ExternalCommandArgument { ArgumentOption = "install", Required = true }); args.Add("_package_name_", new ExternalCommandArgument { ArgumentOption = "", - ArgumentValue = PACKAGE_NAME_TOKEN, + ArgumentValue = PackageNameToken, QuoteValue = false, UseValueOnly = true, Required = true @@ -109,16 +109,16 @@ private void set_install_dictionary(IDictionary /// /// Sets install dictionary /// - private void set_upgrade_dictionary(IDictionary args) + private void SetupUpgradeDictionary(IDictionary args) { - set_common_args(args); + AddCommonArguments(args); args.Add("_command_", new ExternalCommandArgument { ArgumentOption = "install", Required = true }); args.Add("_upgrade_", new ExternalCommandArgument { ArgumentOption = "--upgrade", Required = true }); args.Add("_package_name_", new ExternalCommandArgument { ArgumentOption = "", - ArgumentValue = PACKAGE_NAME_TOKEN, + ArgumentValue = PackageNameToken, QuoteValue = false, UseValueOnly = true, Required = true @@ -128,28 +128,28 @@ private void set_upgrade_dictionary(IDictionary /// /// Sets uninstall dictionary /// - private void set_uninstall_dictionary(IDictionary args) + private void SetupUninstallDictionary(IDictionary args) { - set_common_args(args); + AddCommonArguments(args); args.Add("_command_", new ExternalCommandArgument { ArgumentOption = "uninstall", Required = true }); args.Add("_confirm_", new ExternalCommandArgument { ArgumentOption = "-y", Required = true }); args.Add("_package_name_", new ExternalCommandArgument { ArgumentOption = "", - ArgumentValue = PACKAGE_NAME_TOKEN, + ArgumentValue = PackageNameToken, QuoteValue = false, UseValueOnly = true, Required = true }); } - private void set_common_args(IDictionary args) + private void AddCommonArguments(IDictionary args) { args.Add("_loglevel_", new ExternalCommandArgument { ArgumentOption = "", - ArgumentValue = LOG_LEVEL_TOKEN, + ArgumentValue = LogLevelToken, QuoteValue = false, UseValueOnly = true, Required = true @@ -158,7 +158,7 @@ private void set_common_args(IDictionary args) args.Add("_force_", new ExternalCommandArgument { ArgumentOption = "", - ArgumentValue = FORCE_TOKEN, + ArgumentValue = ForceToken, QuoteValue = false, UseValueOnly = true, Required = true @@ -167,18 +167,18 @@ private void set_common_args(IDictionary args) public string SourceType { - get { return SourceTypes.PYTHON; } + get { return SourceTypes.Python; } } - public void ensure_source_app_installed(ChocolateyConfiguration config, Action ensureAction) + public void EnsureSourceAppInstalled(ChocolateyConfiguration config, Action ensureAction) { - if (Platform.get_platform() != PlatformType.Windows) throw new NotImplementedException("This source is not supported on non-Windows systems"); + if (Platform.GetPlatform() != PlatformType.Windows) throw new NotImplementedException("This source is not supported on non-Windows systems"); //ensure at least python 2.7.9 is installed - var python = _fileSystem.get_executable_path("python"); + var python = _fileSystem.GetExecutablePath("python"); //python -V - if (python.is_equal_to("python")) + if (python.IsEqualTo("python")) { var runnerConfig = new ChocolateyConfiguration { @@ -195,37 +195,32 @@ public void ensure_source_app_installed(ChocolateyConfiguration config, Action

p.Name.is_equal_to(PYTHON_PACKAGE))) + if (!localPackages.Any(p => p.Name.IsEqualTo(PythonPackage))) { - runnerConfig.PackageNames = PYTHON_PACKAGE; + runnerConfig.PackageNames = PythonPackage; runnerConfig.Sources = ApplicationParameters.ChocolateyCommunityFeedSource; var prompt = config.PromptForConfirmation; config.PromptForConfirmation = false; - _nugetService.install_run(runnerConfig, ensureAction.Invoke); + _nugetService.Install(runnerConfig, ensureAction.Invoke); config.PromptForConfirmation = prompt; } } } - public int count_run(ChocolateyConfiguration config) - { - throw new NotImplementedException("Count is not supported for this source runner."); - } - - public void set_executable_path_if_not_set() + private void EnsureExecutablePathSet() { if (!string.IsNullOrWhiteSpace(_exePath)) return; - var python = _fileSystem.get_executable_path("python"); + var python = _fileSystem.GetExecutablePath("python"); var pipPath = string.Empty; - if (!python.is_equal_to("python")) + if (!python.IsEqualTo("python")) { - pipPath = _fileSystem.combine_paths(_fileSystem.get_directory_name(python), "Scripts", "pip.exe"); - if (_fileSystem.file_exists(pipPath)) + pipPath = _fileSystem.CombinePaths(_fileSystem.GetDirectoryName(python), "Scripts", "pip.exe"); + if (_fileSystem.FileExists(pipPath)) { _exePath = pipPath; return; @@ -233,17 +228,17 @@ public void set_executable_path_if_not_set() } var topLevelPath = string.Empty; - var python34PathKey = _registryService.get_key(RegistryHive.LocalMachine, "SOFTWARE\\Python\\PythonCore\\3.4\\InstallPath"); + var python34PathKey = _registryService.GetKey(RegistryHive.LocalMachine, "SOFTWARE\\Python\\PythonCore\\3.4\\InstallPath"); if (python34PathKey != null) { - topLevelPath = python34PathKey.GetValue("", string.Empty).to_string(); + topLevelPath = python34PathKey.GetValue("", string.Empty).ToStringSafe(); } if (string.IsNullOrWhiteSpace(topLevelPath)) { - var python27PathKey = _registryService.get_key(RegistryHive.LocalMachine, "SOFTWARE\\Python\\PythonCore\\2.7\\InstallPath"); + var python27PathKey = _registryService.GetKey(RegistryHive.LocalMachine, "SOFTWARE\\Python\\PythonCore\\2.7\\InstallPath"); if (python27PathKey != null) { - topLevelPath = python27PathKey.GetValue("", string.Empty).to_string(); + topLevelPath = python27PathKey.GetValue("", string.Empty).ToStringSafe(); } } @@ -252,11 +247,11 @@ public void set_executable_path_if_not_set() var binRoot = Environment.GetEnvironmentVariable("ChocolateyBinRoot"); if (string.IsNullOrWhiteSpace(binRoot)) binRoot = "c:\\tools"; - topLevelPath = _fileSystem.combine_paths(binRoot, "python"); + topLevelPath = _fileSystem.CombinePaths(binRoot, "python"); } - pipPath = _fileSystem.combine_paths(_fileSystem.get_directory_name(topLevelPath), "Scripts", "pip.exe"); - if (_fileSystem.file_exists(pipPath)) + pipPath = _fileSystem.CombinePaths(_fileSystem.GetDirectoryName(topLevelPath), "Scripts", "pip.exe"); + if (_fileSystem.FileExists(pipPath)) { _exePath = pipPath; } @@ -264,63 +259,63 @@ public void set_executable_path_if_not_set() if (string.IsNullOrWhiteSpace(_exePath)) throw new FileNotFoundException("Unable to find pip"); } - public string build_args(ChocolateyConfiguration config, IDictionary argsDictionary) + private string BuildArguments(ChocolateyConfiguration config, IDictionary argsDictionary) { - var args = ExternalCommandArgsBuilder.build_arguments(config, argsDictionary); + var args = ExternalCommandArgsBuilder.BuildArguments(config, argsDictionary); - args = args.Replace(LOG_LEVEL_TOKEN, config.Debug ? "-vvv" : ""); + args = args.Replace(LogLevelToken, config.Debug ? "-vvv" : ""); - if (config.CommandName.is_equal_to("install")) + if (config.CommandName.IsEqualTo("install")) { - args = args.Replace(FORCE_TOKEN, config.Force ? "--ignore-installed" : ""); + args = args.Replace(ForceToken, config.Force ? "--ignore-installed" : ""); } - else if (config.CommandName.is_equal_to("upgrade")) + else if (config.CommandName.IsEqualTo("upgrade")) { - args = args.Replace(FORCE_TOKEN, config.Force ? "--force-reinstall" : ""); + args = args.Replace(ForceToken, config.Force ? "--force-reinstall" : ""); } else { - args = args.Replace(FORCE_TOKEN, ""); + args = args.Replace(ForceToken, ""); } return args; } - public void list_noop(ChocolateyConfiguration config) + public void ListDryRun(ChocolateyConfiguration config) { - set_executable_path_if_not_set(); - var args = build_args(config, _listArguments); - this.Log().Info("Would have run '{0} {1}'".format_with(_exePath.escape_curly_braces(), args.escape_curly_braces())); + EnsureExecutablePathSet(); + var args = BuildArguments(config, _listArguments); + this.Log().Info("Would have run '{0} {1}'".FormatWith(_exePath.EscapeCurlyBraces(), args.EscapeCurlyBraces())); } - public IEnumerable list_run(ChocolateyConfiguration config) + public IEnumerable List(ChocolateyConfiguration config) { - set_executable_path_if_not_set(); - var args = build_args(config, _listArguments); + EnsureExecutablePathSet(); + var args = BuildArguments(config, _listArguments); var packageResults = new List(); - Environment.ExitCode = _commandExecutor.execute( + Environment.ExitCode = _commandExecutor.Execute( _exePath, args, config.CommandExecutionTimeoutSeconds, - _fileSystem.get_current_directory(), + _fileSystem.GetCurrentDirectory(), stdOutAction: (s, e) => { var logMessage = e.Data; if (string.IsNullOrWhiteSpace(logMessage)) return; if (!config.QuietOutput) { - this.Log().Info(logMessage.escape_curly_braces()); + this.Log().Info(logMessage.EscapeCurlyBraces()); } else { - this.Log().Debug(() => "[{0}] {1}".format_with(APP_NAME, logMessage.escape_curly_braces())); + this.Log().Debug(() => "[{0}] {1}".FormatWith(AppName, logMessage.EscapeCurlyBraces())); } }, stdErrAction: (s, e) => { if (string.IsNullOrWhiteSpace(e.Data)) return; - this.Log().Error(() => "{0}".format_with(e.Data.escape_curly_braces())); + this.Log().Error(() => "{0}".FormatWith(e.Data.EscapeCurlyBraces())); }, updateProcessPath: false, allowUseWindow: true @@ -329,22 +324,22 @@ public IEnumerable list_run(ChocolateyConfiguration config) return packageResults; } - public void install_noop(ChocolateyConfiguration config, Action continueAction) + public void InstallDryRun(ChocolateyConfiguration config, Action continueAction) { - set_executable_path_if_not_set(); - var args = build_args(config, _installArguments); - this.Log().Info("Would have run '{0} {1}'".format_with(_exePath.escape_curly_braces(), args.escape_curly_braces())); + EnsureExecutablePathSet(); + var args = BuildArguments(config, _installArguments); + this.Log().Info("Would have run '{0} {1}'".FormatWith(_exePath.EscapeCurlyBraces(), args.EscapeCurlyBraces())); } - public ConcurrentDictionary install_run(ChocolateyConfiguration config, Action continueAction) + public ConcurrentDictionary Install(ChocolateyConfiguration config, Action continueAction) { - return install_run(config, continueAction, beforeModifyAction: null); + return Install(config, continueAction, beforeModifyAction: null); } - public ConcurrentDictionary install_run(ChocolateyConfiguration config, Action continueAction, Action beforeModifyAction) + public ConcurrentDictionary Install(ChocolateyConfiguration config, Action continueAction, Action beforeModifyAction) { - set_executable_path_if_not_set(); - var args = build_args(config, _installArguments); + EnsureExecutablePathSet(); + var args = BuildArguments(config, _installArguments); var packageResults = new ConcurrentDictionary(StringComparer.InvariantCultureIgnoreCase); foreach (var packageToInstall in config.PackageNames.Split(new[] { ApplicationParameters.PackageNamesSeparator }, StringSplitOptions.RemoveEmptyEntries)) @@ -352,42 +347,42 @@ public ConcurrentDictionary install_run(ChocolateyConfigu var pkgName = packageToInstall; if (!string.IsNullOrWhiteSpace(config.Version)) { - pkgName = "{0}=={1}".format_with(packageToInstall, config.Version); + pkgName = "{0}=={1}".FormatWith(packageToInstall, config.Version); } - var argsForPackage = args.Replace(PACKAGE_NAME_TOKEN, pkgName); + var argsForPackage = args.Replace(PackageNameToken, pkgName); - var exitCode = _commandExecutor.execute( + var exitCode = _commandExecutor.Execute( _exePath, argsForPackage, config.CommandExecutionTimeoutSeconds, - _fileSystem.get_current_directory(), + _fileSystem.GetCurrentDirectory(), (s, e) => { var logMessage = e.Data; if (string.IsNullOrWhiteSpace(logMessage)) return; - this.Log().Info(() => " [{0}] {1}".format_with(APP_NAME, logMessage.escape_curly_braces())); + this.Log().Info(() => " [{0}] {1}".FormatWith(AppName, logMessage.EscapeCurlyBraces())); - if (ErrorRegex.IsMatch(logMessage) || ErrorNotFoundRegex.IsMatch(logMessage)) + if (_errorRegex.IsMatch(logMessage) || _errorNotFoundRegex.IsMatch(logMessage)) { var results = packageResults.GetOrAdd(packageToInstall, new PackageResult(packageToInstall, null, null)); results.Messages.Add(new ResultMessage(ResultType.Error, logMessage)); } - if (InstalledRegex.IsMatch(logMessage)) + if (_installedRegex.IsMatch(logMessage)) { - var packageName = get_value_from_output(logMessage, PackageNameRegex, PACKAGE_NAME_GROUP); + var packageName = GetValueFromOutput(logMessage, _packageNameRegex, PackageNameGroup); var results = packageResults.GetOrAdd(packageName, new PackageResult(packageName, null, null)); results.Messages.Add(new ResultMessage(ResultType.Note, packageName)); - this.Log().Info(ChocolateyLoggers.Important, " {0} has been installed successfully.".format_with(string.IsNullOrWhiteSpace(packageName) ? packageToInstall : packageName)); + this.Log().Info(ChocolateyLoggers.Important, " {0} has been installed successfully.".FormatWith(string.IsNullOrWhiteSpace(packageName) ? packageToInstall : packageName)); } }, (s, e) => { var logMessage = e.Data; if (string.IsNullOrWhiteSpace(logMessage)) return; - this.Log().Error("[{0}] {1}".format_with(APP_NAME, logMessage.escape_curly_braces())); + this.Log().Error("[{0}] {1}".FormatWith(AppName, logMessage.EscapeCurlyBraces())); - if (ErrorRegex.IsMatch(logMessage) || ErrorNotFoundRegex.IsMatch(logMessage)) + if (_errorRegex.IsMatch(logMessage) || _errorNotFoundRegex.IsMatch(logMessage)) { var results = packageResults.GetOrAdd(packageToInstall, new PackageResult(packageToInstall, null, null)); results.Messages.Add(new ResultMessage(ResultType.Error, logMessage)); @@ -406,23 +401,23 @@ public ConcurrentDictionary install_run(ChocolateyConfigu return packageResults; } - public ConcurrentDictionary upgrade_noop(ChocolateyConfiguration config, Action continueAction) + public ConcurrentDictionary UpgradeDryRun(ChocolateyConfiguration config, Action continueAction) { - set_executable_path_if_not_set(); - var args = build_args(config, _upgradeArguments); - this.Log().Info("Would have run '{0} {1}'".format_with(_exePath.escape_curly_braces(), args.escape_curly_braces())); + EnsureExecutablePathSet(); + var args = BuildArguments(config, _upgradeArguments); + this.Log().Info("Would have run '{0} {1}'".FormatWith(_exePath.EscapeCurlyBraces(), args.EscapeCurlyBraces())); return new ConcurrentDictionary(StringComparer.InvariantCultureIgnoreCase); } - public ConcurrentDictionary upgrade_run(ChocolateyConfiguration config, Action continueAction, Action beforeUpgradeAction = null) + public ConcurrentDictionary Upgrade(ChocolateyConfiguration config, Action continueAction, Action beforeUpgradeAction = null) { - if (config.PackageNames.is_equal_to(ApplicationParameters.AllPackages)) + if (config.PackageNames.IsEqualTo(ApplicationParameters.AllPackages)) { throw new NotImplementedException("The all keyword is not available for alternate sources"); } - set_executable_path_if_not_set(); - var args = build_args(config, _upgradeArguments); + EnsureExecutablePathSet(); + var args = BuildArguments(config, _upgradeArguments); var packageResults = new ConcurrentDictionary(StringComparer.InvariantCultureIgnoreCase); foreach (var packageToInstall in config.PackageNames.Split(new[] { ApplicationParameters.PackageNamesSeparator }, StringSplitOptions.RemoveEmptyEntries)) @@ -430,43 +425,43 @@ public ConcurrentDictionary upgrade_run(ChocolateyConfigu var pkgName = packageToInstall; if (!string.IsNullOrWhiteSpace(config.Version)) { - pkgName = "{0}=={1}".format_with(packageToInstall, config.Version); + pkgName = "{0}=={1}".FormatWith(packageToInstall, config.Version); } - var argsForPackage = args.Replace(PACKAGE_NAME_TOKEN, pkgName); + var argsForPackage = args.Replace(PackageNameToken, pkgName); - var exitCode = _commandExecutor.execute( + var exitCode = _commandExecutor.Execute( _exePath, argsForPackage, config.CommandExecutionTimeoutSeconds, - _fileSystem.get_current_directory(), + _fileSystem.GetCurrentDirectory(), (s, e) => { var logMessage = e.Data; if (string.IsNullOrWhiteSpace(logMessage)) return; - this.Log().Info(() => " [{0}] {1}".format_with(APP_NAME, logMessage.escape_curly_braces())); + this.Log().Info(() => " [{0}] {1}".FormatWith(AppName, logMessage.EscapeCurlyBraces())); - if (ErrorRegex.IsMatch(logMessage) || ErrorNotFoundRegex.IsMatch(logMessage)) + if (_errorRegex.IsMatch(logMessage) || _errorNotFoundRegex.IsMatch(logMessage)) { var results = packageResults.GetOrAdd(packageToInstall, new PackageResult(packageToInstall, null, null)); results.Messages.Add(new ResultMessage(ResultType.Error, logMessage)); } - if (InstalledRegex.IsMatch(logMessage)) + if (_installedRegex.IsMatch(logMessage)) { - var packageName = get_value_from_output(logMessage, PackageNameRegex, PACKAGE_NAME_GROUP); + var packageName = GetValueFromOutput(logMessage, _packageNameRegex, PackageNameGroup); var results = packageResults.GetOrAdd(packageName, new PackageResult(packageName, null, null)); results.Messages.Add(new ResultMessage(ResultType.Note, packageName)); - this.Log().Info(ChocolateyLoggers.Important, " {0} has been installed successfully.".format_with(string.IsNullOrWhiteSpace(packageName) ? packageToInstall : packageName)); + this.Log().Info(ChocolateyLoggers.Important, " {0} has been installed successfully.".FormatWith(string.IsNullOrWhiteSpace(packageName) ? packageToInstall : packageName)); } }, (s, e) => { var logMessage = e.Data; if (string.IsNullOrWhiteSpace(logMessage)) return; - this.Log().Error("[{0}] {1}".format_with(APP_NAME, logMessage.escape_curly_braces())); + this.Log().Error("[{0}] {1}".FormatWith(AppName, logMessage.EscapeCurlyBraces())); - if (ErrorRegex.IsMatch(logMessage) || ErrorNotFoundRegex.IsMatch(logMessage)) + if (_errorRegex.IsMatch(logMessage) || _errorNotFoundRegex.IsMatch(logMessage)) { var results = packageResults.GetOrAdd(packageToInstall, new PackageResult(packageToInstall, null, null)); results.Messages.Add(new ResultMessage(ResultType.Error, logMessage)); @@ -485,55 +480,55 @@ public ConcurrentDictionary upgrade_run(ChocolateyConfigu return packageResults; } - public void uninstall_noop(ChocolateyConfiguration config, Action continueAction) + public void UninstallDryRun(ChocolateyConfiguration config, Action continueAction) { - set_executable_path_if_not_set(); - var args = build_args(config, _uninstallArguments); - this.Log().Info("Would have run '{0} {1}'".format_with(_exePath.escape_curly_braces(), args.escape_curly_braces())); + EnsureExecutablePathSet(); + var args = BuildArguments(config, _uninstallArguments); + this.Log().Info("Would have run '{0} {1}'".FormatWith(_exePath.EscapeCurlyBraces(), args.EscapeCurlyBraces())); } - public ConcurrentDictionary uninstall_run(ChocolateyConfiguration config, Action continueAction, Action beforeUninstallAction = null) + public ConcurrentDictionary Uninstall(ChocolateyConfiguration config, Action continueAction, Action beforeUninstallAction = null) { - set_executable_path_if_not_set(); - var args = build_args(config, _uninstallArguments); + EnsureExecutablePathSet(); + var args = BuildArguments(config, _uninstallArguments); var packageResults = new ConcurrentDictionary(StringComparer.InvariantCultureIgnoreCase); foreach (var packageToInstall in config.PackageNames.Split(new[] { ApplicationParameters.PackageNamesSeparator }, StringSplitOptions.RemoveEmptyEntries)) { - var argsForPackage = args.Replace(PACKAGE_NAME_TOKEN, packageToInstall); + var argsForPackage = args.Replace(PackageNameToken, packageToInstall); - var exitCode = _commandExecutor.execute( + var exitCode = _commandExecutor.Execute( _exePath, argsForPackage, config.CommandExecutionTimeoutSeconds, - _fileSystem.get_current_directory(), + _fileSystem.GetCurrentDirectory(), (s, e) => { var logMessage = e.Data; if (string.IsNullOrWhiteSpace(logMessage)) return; - this.Log().Info(() => " [{0}] {1}".format_with(APP_NAME, logMessage.escape_curly_braces())); + this.Log().Info(() => " [{0}] {1}".FormatWith(AppName, logMessage.EscapeCurlyBraces())); - if (ErrorRegex.IsMatch(logMessage) || ErrorNotFoundRegex.IsMatch(logMessage)) + if (_errorRegex.IsMatch(logMessage) || _errorNotFoundRegex.IsMatch(logMessage)) { var results = packageResults.GetOrAdd(packageToInstall, new PackageResult(packageToInstall, null, null)); results.Messages.Add(new ResultMessage(ResultType.Error, packageToInstall)); } - if (UninstalledRegex.IsMatch(logMessage)) + if (_uninstalledRegex.IsMatch(logMessage)) { - var packageName = get_value_from_output(logMessage, PackageNameRegex, PACKAGE_NAME_GROUP); + var packageName = GetValueFromOutput(logMessage, _packageNameRegex, PackageNameGroup); var results = packageResults.GetOrAdd(packageName, new PackageResult(packageName, null, null)); results.Messages.Add(new ResultMessage(ResultType.Note, packageName)); - this.Log().Info(ChocolateyLoggers.Important, " {0} has been uninstalled successfully.".format_with(string.IsNullOrWhiteSpace(packageName) ? packageToInstall : packageName)); + this.Log().Info(ChocolateyLoggers.Important, " {0} has been uninstalled successfully.".FormatWith(string.IsNullOrWhiteSpace(packageName) ? packageToInstall : packageName)); } }, (s, e) => { var logMessage = e.Data; if (string.IsNullOrWhiteSpace(logMessage)) return; - this.Log().Error("[{0}] {1}".format_with(APP_NAME, logMessage.escape_curly_braces())); + this.Log().Error("[{0}] {1}".FormatWith(AppName, logMessage.EscapeCurlyBraces())); - if (ErrorRegex.IsMatch(logMessage) || ErrorNotFoundRegex.IsMatch(logMessage)) + if (_errorRegex.IsMatch(logMessage) || _errorNotFoundRegex.IsMatch(logMessage)) { var results = packageResults.GetOrAdd(packageToInstall, new PackageResult(packageToInstall, null, null)); results.Messages.Add(new ResultMessage(ResultType.Error, logMessage)); @@ -559,7 +554,7 @@ public ConcurrentDictionary uninstall_run(ChocolateyConfi /// The regex. /// Name of the group. /// - private static string get_value_from_output(string output, Regex regex, string groupName) + private static string GetValueFromOutput(string output, Regex regex, string groupName) { var matchGroup = regex.Match(output).Groups[groupName]; if (matchGroup != null) @@ -569,5 +564,70 @@ private static string get_value_from_output(string output, Regex regex, string g return string.Empty; } + +#pragma warning disable IDE1006 + [Obsolete("This overload is deprecated and will be removed in v3.")] + public const string PYTHON_PACKAGE = PythonPackage; + [Obsolete("This overload is deprecated and will be removed in v3.")] + public const string PACKAGE_NAME_GROUP = PackageNameGroup; + [Obsolete("This overload is deprecated and will be removed in v3.")] + public static readonly Regex InstalledRegex = _installedRegex; + [Obsolete("This overload is deprecated and will be removed in v3.")] + public static readonly Regex UninstalledRegex = _uninstalledRegex; + [Obsolete("This overload is deprecated and will be removed in v3.")] + public static readonly Regex PackageNameRegex = _packageNameRegex; + [Obsolete("This overload is deprecated and will be removed in v3.")] + public static readonly Regex ErrorRegex = _errorRegex; + [Obsolete("This overload is deprecated and will be removed in v3.")] + public static readonly Regex ErrorNotFoundRegex = new Regex(@"Could not find any downloads that", RegexOptions.Compiled); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public void ensure_source_app_installed(ChocolateyConfiguration config, Action ensureAction) + => EnsureSourceAppInstalled(config, ensureAction); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public void set_executable_path_if_not_set() + => EnsureExecutablePathSet(); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public string build_args(ChocolateyConfiguration config, IDictionary argsDictionary) + => BuildArguments(config, argsDictionary); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public void list_noop(ChocolateyConfiguration config) + => ListDryRun(config); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public IEnumerable list_run(ChocolateyConfiguration config) + => List(config); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public void install_noop(ChocolateyConfiguration config, Action continueAction) + => InstallDryRun(config, continueAction); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public ConcurrentDictionary install_run(ChocolateyConfiguration config, Action continueAction) + => Install(config, continueAction); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public ConcurrentDictionary install_run(ChocolateyConfiguration config, Action continueAction, Action beforeModifyAction) + => Install(config, continueAction, beforeModifyAction); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public ConcurrentDictionary upgrade_noop(ChocolateyConfiguration config, Action continueAction) + => UpgradeDryRun(config, continueAction); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public ConcurrentDictionary upgrade_run(ChocolateyConfiguration config, Action continueAction, Action beforeUpgradeAction = null) + => Upgrade(config, continueAction, beforeUpgradeAction); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public void uninstall_noop(ChocolateyConfiguration config, Action continueAction) + => UninstallDryRun(config, continueAction); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public ConcurrentDictionary uninstall_run(ChocolateyConfiguration config, Action continueAction, Action beforeUninstallAction = null) + => Uninstall(config, continueAction, beforeUninstallAction); +#pragma warning restore IDE1006 } } diff --git a/src/chocolatey/infrastructure.app/services/RegistryService.cs b/src/chocolatey/infrastructure.app/services/RegistryService.cs index 16895a3ca3..2a39ed966c 100644 --- a/src/chocolatey/infrastructure.app/services/RegistryService.cs +++ b/src/chocolatey/infrastructure.app/services/RegistryService.cs @@ -42,10 +42,10 @@ public sealed class RegistryService : IRegistryService private readonly bool _logOutput = false; //public RegistryService() {} - private const string UNINSTALLER_KEY_NAME = "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall"; - private const string UNINSTALLER_MSI_MACHINE_KEY_NAME = "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Installer\\UserData"; - private const string USER_ENVIRONMENT_REGISTRY_KEY_NAME = "Environment"; - private const string MACHINE_ENVIRONMENT_REGISTRY_KEY_NAME = "SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment"; + private const string UninstallerKeyName = "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall"; + private const string UninstallerMsiMachineKeyName = "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Installer\\UserData"; + private const string UserEnvironmentRegistryKeyName = "Environment"; + private const string MachineEnvironmentRegistryKeyName = "SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment"; public RegistryService(IXmlService xmlService, IFileSystem fileSystem) { @@ -53,47 +53,47 @@ public RegistryService(IXmlService xmlService, IFileSystem fileSystem) _fileSystem = fileSystem; } - private RegistryKey open_key(RegistryHive hive, RegistryView view) + private RegistryKey OpenKey(RegistryHive hive, RegistryView view) { - return FaultTolerance.try_catch_with_logging_exception( + return FaultTolerance.TryCatchWithLoggingException( () => RegistryKey.OpenBaseKey(hive, view), - "Could not open registry hive '{0}' for view '{1}'".format_with(hive.to_string(), view.to_string()), + "Could not open registry hive '{0}' for view '{1}'".FormatWith(hive.ToStringSafe(), view.ToStringSafe()), logWarningInsteadOfError: true); } - private void add_key(IList keys, RegistryHive hive, RegistryView view) + private void AddKey(IList keys, RegistryHive hive, RegistryView view) { - var key = open_key(hive, view); + var key = OpenKey(hive, view); if (key != null) keys.Add(key); } - public Registry get_installer_keys() + public Registry GetInstallerKeys() { var snapshot = new Registry(); var windowsIdentity = WindowsIdentity.GetCurrent(); - if (windowsIdentity != null) snapshot.User = windowsIdentity.User.to_string(); + if (windowsIdentity != null) snapshot.User = windowsIdentity.User.ToStringSafe(); IList keys = new List(); if (Environment.Is64BitOperatingSystem) { - add_key(keys, RegistryHive.CurrentUser, RegistryView.Registry64); - add_key(keys, RegistryHive.LocalMachine, RegistryView.Registry64); + AddKey(keys, RegistryHive.CurrentUser, RegistryView.Registry64); + AddKey(keys, RegistryHive.LocalMachine, RegistryView.Registry64); } - add_key(keys, RegistryHive.CurrentUser, RegistryView.Registry32); - add_key(keys, RegistryHive.LocalMachine, RegistryView.Registry32); + AddKey(keys, RegistryHive.CurrentUser, RegistryView.Registry32); + AddKey(keys, RegistryHive.LocalMachine, RegistryView.Registry32); foreach (var registryKey in keys) { - var uninstallKey = FaultTolerance.try_catch_with_logging_exception( - () => registryKey.OpenSubKey(UNINSTALLER_KEY_NAME, RegistryKeyPermissionCheck.ReadSubTree, RegistryRights.ReadKey), - "Could not open uninstall subkey for key '{0}'".format_with(registryKey.Name), + var uninstallKey = FaultTolerance.TryCatchWithLoggingException( + () => registryKey.OpenSubKey(UninstallerKeyName, RegistryKeyPermissionCheck.ReadSubTree, RegistryRights.ReadKey), + "Could not open uninstall subkey for key '{0}'".FormatWith(registryKey.Name), logWarningInsteadOfError: true); if (uninstallKey != null) { //Console.WriteLine("Evaluating {0} of {1}".format_with(uninstallKey.View, uninstallKey.Name)); - evaluate_keys(uninstallKey, snapshot); + UpdateSnapshot(uninstallKey, snapshot); } registryKey.Close(); registryKey.Dispose(); @@ -102,11 +102,11 @@ public Registry get_installer_keys() if (_logOutput) { Console.WriteLine(""); - Console.WriteLine("A total of {0} unrecognized apps".format_with(snapshot.RegistryKeys.Where((p) => p.InstallerType == InstallerType.Unknown && p.is_in_programs_and_features()).Count())); + Console.WriteLine("A total of {0} unrecognized apps".FormatWith(snapshot.RegistryKeys.Where((p) => p.InstallerType == InstallerType.Unknown && p.IsInProgramsAndFeatures()).Count())); Console.WriteLine(""); Console.WriteLine(""); - Console.WriteLine("A total of {0} of {1} are programs and features apps".format_with(snapshot.RegistryKeys.Where((p) => p.is_in_programs_and_features()).Count(), snapshot.RegistryKeys.Count)); + Console.WriteLine("A total of {0} of {1} are programs and features apps".FormatWith(snapshot.RegistryKeys.Where((p) => p.IsInProgramsAndFeatures()).Count(), snapshot.RegistryKeys.Count)); Console.WriteLine(""); } @@ -118,30 +118,30 @@ public Registry get_installer_keys() ///

/// The key. /// The snapshot. - public void evaluate_keys(RegistryKey key, Registry snapshot) + public void UpdateSnapshot(RegistryKey key, Registry snapshot) { if (key == null) return; - FaultTolerance.try_catch_with_logging_exception( + FaultTolerance.TryCatchWithLoggingException( () => { foreach (var subKeyName in key.GetSubKeyNames()) { - FaultTolerance.try_catch_with_logging_exception( - () => evaluate_keys(key.OpenSubKey(subKeyName, RegistryKeyPermissionCheck.ReadSubTree, RegistryRights.ReadKey), snapshot), - "Failed to open subkey named '{0}' for '{1}', likely due to permissions".format_with(subKeyName, key.Name), + FaultTolerance.TryCatchWithLoggingException( + () => UpdateSnapshot(key.OpenSubKey(subKeyName, RegistryKeyPermissionCheck.ReadSubTree, RegistryRights.ReadKey), snapshot), + "Failed to open subkey named '{0}' for '{1}', likely due to permissions".FormatWith(subKeyName, key.Name), logWarningInsteadOfError: true); } }, - "Failed to open subkeys for '{0}', likely due to permissions".format_with(key.Name), + "Failed to open subkeys for '{0}', likely due to permissions".FormatWith(key.Name), logWarningInsteadOfError: true); var appKey = new RegistryApplicationKey { KeyPath = key.Name, RegistryView = key.View, - DefaultValue = key.get_value_as_string(""), - DisplayName = key.get_value_as_string("DisplayName") + DefaultValue = key.AsXmlSafeString(""), + DisplayName = key.AsXmlSafeString("DisplayName") }; if (string.IsNullOrWhiteSpace(appKey.DisplayName)) @@ -151,64 +151,64 @@ public void evaluate_keys(RegistryKey key, Registry snapshot) if (!string.IsNullOrWhiteSpace(appKey.DisplayName)) { - appKey.InstallLocation = key.get_value_as_string("InstallLocation"); - appKey.UninstallString = key.get_value_as_string("UninstallString"); - if (!string.IsNullOrWhiteSpace(key.get_value_as_string("QuietUninstallString"))) + appKey.InstallLocation = key.AsXmlSafeString("InstallLocation"); + appKey.UninstallString = key.AsXmlSafeString("UninstallString"); + if (!string.IsNullOrWhiteSpace(key.AsXmlSafeString("QuietUninstallString"))) { - appKey.UninstallString = key.get_value_as_string("QuietUninstallString"); + appKey.UninstallString = key.AsXmlSafeString("QuietUninstallString"); appKey.HasQuietUninstall = true; } // informational - appKey.Publisher = key.get_value_as_string("Publisher"); - appKey.InstallDate = key.get_value_as_string("InstallDate"); - appKey.InstallSource = key.get_value_as_string("InstallSource"); - appKey.Language = key.get_value_as_string("Language"); + appKey.Publisher = key.AsXmlSafeString("Publisher"); + appKey.InstallDate = key.AsXmlSafeString("InstallDate"); + appKey.InstallSource = key.AsXmlSafeString("InstallSource"); + appKey.Language = key.AsXmlSafeString("Language"); // Version - appKey.DisplayVersion = key.get_value_as_string("DisplayVersion"); - appKey.Version = key.get_value_as_string("Version"); - appKey.VersionMajor = key.get_value_as_string("VersionMajor"); - appKey.VersionMinor = key.get_value_as_string("VersionMinor"); + appKey.DisplayVersion = key.AsXmlSafeString("DisplayVersion"); + appKey.Version = key.AsXmlSafeString("Version"); + appKey.VersionMajor = key.AsXmlSafeString("VersionMajor"); + appKey.VersionMinor = key.AsXmlSafeString("VersionMinor"); // installinformation - appKey.SystemComponent = key.get_value_as_string("SystemComponent") == "1"; - appKey.WindowsInstaller = key.get_value_as_string("WindowsInstaller") == "1"; - appKey.NoRemove = key.get_value_as_string("NoRemove") == "1"; - appKey.NoModify = key.get_value_as_string("NoModify") == "1"; - appKey.NoRepair = key.get_value_as_string("NoRepair") == "1"; - appKey.ReleaseType = key.get_value_as_string("ReleaseType"); - appKey.ParentKeyName = key.get_value_as_string("ParentKeyName"); - - if (appKey.WindowsInstaller || appKey.UninstallString.to_string().to_lower().Contains("msiexec")) + appKey.SystemComponent = key.AsXmlSafeString("SystemComponent") == "1"; + appKey.WindowsInstaller = key.AsXmlSafeString("WindowsInstaller") == "1"; + appKey.NoRemove = key.AsXmlSafeString("NoRemove") == "1"; + appKey.NoModify = key.AsXmlSafeString("NoModify") == "1"; + appKey.NoRepair = key.AsXmlSafeString("NoRepair") == "1"; + appKey.ReleaseType = key.AsXmlSafeString("ReleaseType"); + appKey.ParentKeyName = key.AsXmlSafeString("ParentKeyName"); + + if (appKey.WindowsInstaller || appKey.UninstallString.ToStringSafe().ToLowerSafe().Contains("msiexec")) { appKey.InstallerType = InstallerType.Msi; } - if (key.Name.EndsWith("_is1") || !string.IsNullOrWhiteSpace(key.get_value_as_string("Inno Setup: Setup Version"))) + if (key.Name.EndsWith("_is1") || !string.IsNullOrWhiteSpace(key.AsXmlSafeString("Inno Setup: Setup Version"))) { appKey.InstallerType = InstallerType.InnoSetup; } - if (!string.IsNullOrWhiteSpace(key.get_value_as_string("dwVersionMajor"))) + if (!string.IsNullOrWhiteSpace(key.AsXmlSafeString("dwVersionMajor"))) { appKey.InstallerType = InstallerType.Nsis; - appKey.VersionMajor = key.get_value_as_string("dwVersionMajor"); - appKey.VersionMinor = key.get_value_as_string("dwVersionMinor"); - appKey.VersionRevision = key.get_value_as_string("dwVersionRev"); - appKey.VersionBuild = key.get_value_as_string("dwVersionBuild"); + appKey.VersionMajor = key.AsXmlSafeString("dwVersionMajor"); + appKey.VersionMinor = key.AsXmlSafeString("dwVersionMinor"); + appKey.VersionRevision = key.AsXmlSafeString("dwVersionRev"); + appKey.VersionBuild = key.AsXmlSafeString("dwVersionBuild"); } - if (appKey.ReleaseType.is_equal_to("Hotfix") || appKey.ReleaseType.is_equal_to("Update Rollup") || appKey.ReleaseType.is_equal_to("Security Update") || appKey.DefaultValue.to_string().StartsWith("KB", ignoreCase: true, culture: CultureInfo.InvariantCulture)) + if (appKey.ReleaseType.IsEqualTo("Hotfix") || appKey.ReleaseType.IsEqualTo("Update Rollup") || appKey.ReleaseType.IsEqualTo("Security Update") || appKey.DefaultValue.ToStringSafe().StartsWith("KB", ignoreCase: true, culture: CultureInfo.InvariantCulture)) { appKey.InstallerType = InstallerType.HotfixOrSecurityUpdate; } - if (appKey.ReleaseType.is_equal_to("ServicePack")) + if (appKey.ReleaseType.IsEqualTo("ServicePack")) { appKey.InstallerType = InstallerType.ServicePack; } // assume NSIS if we still don't know and we find uninst.exe - if (appKey.InstallerType == InstallerType.Unknown && appKey.UninstallString.to_string().to_lower().Contains("uninst.exe")) + if (appKey.InstallerType == InstallerType.Unknown && appKey.UninstallString.ToStringSafe().ToLowerSafe().Contains("uninst.exe")) { appKey.InstallerType = InstallerType.Nsis; } @@ -220,7 +220,7 @@ public void evaluate_keys(RegistryKey key, Registry snapshot) if (appKey.InstallerType == InstallerType.Msi) { - get_msi_information(appKey, key); + GetMsiInformation(appKey, key); } if (_logOutput) @@ -230,10 +230,10 @@ public void evaluate_keys(RegistryKey key, Registry snapshot) foreach (var name in key.GetValueNames()) { //var kind = key.GetValueKind(name); - var value = key.get_value_as_string(name); - if (name.is_equal_to("QuietUninstallString") || name.is_equal_to("UninstallString")) + var value = key.AsXmlSafeString(name); + if (name.IsEqualTo("QuietUninstallString") || name.IsEqualTo("UninstallString")) { - Console.WriteLine("key - {0}|{1}={2}|Type detected={3}|install location={4}".format_with(key.Name, name, value.to_string(), appKey.InstallerType.to_string(),appKey.InstallLocation.to_string())); + Console.WriteLine("key - {0}|{1}={2}|Type detected={3}|install location={4}".FormatWith(key.Name, name, value.ToStringSafe(), appKey.InstallerType.ToStringSafe(),appKey.InstallLocation.ToStringSafe())); } //Console.WriteLine("key - {0}, name - {1}, kind - {2}, value - {3}".format_with(key.Name, name, kind, value.to_string())); @@ -248,44 +248,44 @@ public void evaluate_keys(RegistryKey key, Registry snapshot) key.Dispose(); } - private void get_msi_information(RegistryApplicationKey appKey, RegistryKey key) + private void GetMsiInformation(RegistryApplicationKey appKey, RegistryKey key) { - var userDataProductKeyId = get_msi_user_data_key(key.Name); + var userDataProductKeyId = GetMsiUserDataKey(key.Name); if (string.IsNullOrWhiteSpace(userDataProductKeyId)) return; - var hklm = open_key(RegistryHive.LocalMachine, RegistryView.Default); + var hklm = OpenKey(RegistryHive.LocalMachine, RegistryView.Default); if (Environment.Is64BitOperatingSystem) { - hklm = open_key(RegistryHive.LocalMachine, RegistryView.Registry64); + hklm = OpenKey(RegistryHive.LocalMachine, RegistryView.Registry64); } - FaultTolerance.try_catch_with_logging_exception( + FaultTolerance.TryCatchWithLoggingException( () => { - var msiRegistryKey = hklm.OpenSubKey(UNINSTALLER_MSI_MACHINE_KEY_NAME, RegistryKeyPermissionCheck.ReadSubTree, RegistryRights.ReadKey); + var msiRegistryKey = hklm.OpenSubKey(UninstallerMsiMachineKeyName, RegistryKeyPermissionCheck.ReadSubTree, RegistryRights.ReadKey); if (msiRegistryKey == null) return; foreach (var subKeyName in msiRegistryKey.GetSubKeyNames()) { - var msiProductKey = FaultTolerance.try_catch_with_logging_exception( - () => msiRegistryKey.OpenSubKey("{0}\\Products\\{1}\\InstallProperties".format_with(subKeyName, userDataProductKeyId), RegistryKeyPermissionCheck.ReadSubTree, RegistryRights.ReadKey), - "Failed to open subkey named '{0}' for '{1}', likely due to permissions".format_with(subKeyName, msiRegistryKey.Name), + var msiProductKey = FaultTolerance.TryCatchWithLoggingException( + () => msiRegistryKey.OpenSubKey("{0}\\Products\\{1}\\InstallProperties".FormatWith(subKeyName, userDataProductKeyId), RegistryKeyPermissionCheck.ReadSubTree, RegistryRights.ReadKey), + "Failed to open subkey named '{0}' for '{1}', likely due to permissions".FormatWith(subKeyName, msiRegistryKey.Name), logWarningInsteadOfError: true); if (msiProductKey == null) continue; - appKey.InstallLocation = set_if_empty(appKey.InstallLocation, msiProductKey.get_value_as_string("InstallLocation")); + appKey.InstallLocation = SetIfEmpty(appKey.InstallLocation, msiProductKey.AsXmlSafeString("InstallLocation")); // informational - appKey.Publisher = set_if_empty(appKey.Publisher, msiProductKey.get_value_as_string("Publisher")); - appKey.InstallDate = set_if_empty(appKey.InstallDate, msiProductKey.get_value_as_string("InstallDate")); - appKey.InstallSource = set_if_empty(appKey.InstallSource, msiProductKey.get_value_as_string("InstallSource")); - appKey.Language = set_if_empty(appKey.Language, msiProductKey.get_value_as_string("Language")); - appKey.LocalPackage = set_if_empty(appKey.LocalPackage, msiProductKey.get_value_as_string("LocalPackage")); + appKey.Publisher = SetIfEmpty(appKey.Publisher, msiProductKey.AsXmlSafeString("Publisher")); + appKey.InstallDate = SetIfEmpty(appKey.InstallDate, msiProductKey.AsXmlSafeString("InstallDate")); + appKey.InstallSource = SetIfEmpty(appKey.InstallSource, msiProductKey.AsXmlSafeString("InstallSource")); + appKey.Language = SetIfEmpty(appKey.Language, msiProductKey.AsXmlSafeString("Language")); + appKey.LocalPackage = SetIfEmpty(appKey.LocalPackage, msiProductKey.AsXmlSafeString("LocalPackage")); // Version - appKey.DisplayVersion = set_if_empty(appKey.DisplayVersion, msiProductKey.get_value_as_string("DisplayVersion")); - appKey.Version = set_if_empty(appKey.Version, msiProductKey.get_value_as_string("Version")); - appKey.VersionMajor = set_if_empty(appKey.VersionMajor, msiProductKey.get_value_as_string("VersionMajor")); - appKey.VersionMinor = set_if_empty(appKey.VersionMinor, msiProductKey.get_value_as_string("VersionMinor")); + appKey.DisplayVersion = SetIfEmpty(appKey.DisplayVersion, msiProductKey.AsXmlSafeString("DisplayVersion")); + appKey.Version = SetIfEmpty(appKey.Version, msiProductKey.AsXmlSafeString("Version")); + appKey.VersionMajor = SetIfEmpty(appKey.VersionMajor, msiProductKey.AsXmlSafeString("VersionMajor")); + appKey.VersionMinor = SetIfEmpty(appKey.VersionMinor, msiProductKey.AsXmlSafeString("VersionMinor")); // int _componentLoopCount = 0; // search components for install location if still empty // the performance of this is very bad - without this the query is sub-second @@ -316,11 +316,11 @@ private void get_msi_information(RegistryApplicationKey appKey, RegistryKey key) //} } }, - "Failed to open subkeys for '{0}', likely due to permissions".format_with(hklm.Name), + "Failed to open subkeys for '{0}', likely due to permissions".FormatWith(hklm.Name), logWarningInsteadOfError: true); } - private string set_if_empty(string current, string proposed) + private string SetIfEmpty(string current, string proposed) { if (string.IsNullOrWhiteSpace(current)) return proposed; @@ -331,16 +331,7 @@ private string set_if_empty(string current, string proposed) private Regex _programFilesRegex = new Regex(@"(?\w)[\:\?]\\(?[Pp]rogram\s[Ff]iles|[Pp]rogram\s[Ff]iles\s\(x86\))\\(?:[Mm]icrosoft[^\\]*|[Cc]ommon\s[Ff]iles|IIS|MSBuild|[Rr]eference\s[Aa]ssemblies|[Ww]indows[^\\]*|(?[^\\]+))\\", RegexOptions.Compiled); private StringBuilder _userDataKey = new StringBuilder(); - private string get_install_location_estimate(string componentPath) - { - var match = _programFilesRegex.Match(componentPath); - if (!match.Success) return string.Empty; - if (string.IsNullOrWhiteSpace(match.Groups["Name"].Value)) return string.Empty; - - return "{0}:\\{1}\\{2}".format_with(match.Groups["Drive"].Value, match.Groups["ProgFiles"].Value, match.Groups["Name"].Value); - } - - private string get_msi_user_data_key(string name) + private string GetMsiUserDataKey(string name) { _userDataKey.Clear(); var match = _guidRegex.Match(name); @@ -348,7 +339,7 @@ private string get_msi_user_data_key(string name) for (int i = 0; i < 3; i++) { - var fullGroup = match.Groups["ReverseFull{0}".format_with(i + 1)]; + var fullGroup = match.Groups["ReverseFull{0}".FormatWith(i + 1)]; if (fullGroup != null) { _userDataKey.Append(fullGroup.Value.ToCharArray().Reverse().ToArray()); @@ -356,54 +347,54 @@ private string get_msi_user_data_key(string name) } for (int i = 0; i < 2; i++) { - var pairsGroup = match.Groups["ReversePairs{0}".format_with(i + 1)]; + var pairsGroup = match.Groups["ReversePairs{0}".FormatWith(i + 1)]; if (pairsGroup != null) { var pairValue = pairsGroup.Value; for (int j = 0; j < pairValue.Length - 1; j++) { - _userDataKey.Append("{1}{0}".format_with(pairValue[j], pairValue[j + 1])); + _userDataKey.Append("{1}{0}".FormatWith(pairValue[j], pairValue[j + 1])); j++; } } } - return _userDataKey.to_string(); + return _userDataKey.ToStringSafe(); } - public Registry get_installer_key_differences(Registry before, Registry after) + public Registry GetInstallerKeysChanged(Registry before, Registry after) { //var difference = after.RegistryKeys.Where(r => !before.RegistryKeys.Contains(r)).ToList(); return new Registry(after.User, after.RegistryKeys.Except(before.RegistryKeys).ToList()); } - public void save_to_file(Registry snapshot, string filePath) + public void SaveRegistrySnapshot(Registry snapshot, string filePath) { - _xmlService.serialize(snapshot, filePath); + _xmlService.Serialize(snapshot, filePath); } - public bool installer_value_exists(string keyPath, string value) + public bool InstallerKeyExists(string keyPath) { - return get_installer_keys().RegistryKeys.Any(k => k.KeyPath == keyPath); + return GetInstallerKeys().RegistryKeys.Any(k => k.KeyPath == keyPath); } - public Registry read_from_file(string filePath) + public Registry ReadRegistrySnapshot(string filePath) { - if (!_fileSystem.file_exists(filePath)) + if (!_fileSystem.FileExists(filePath)) { return null; } - return _xmlService.deserialize(filePath, 2); + return _xmlService.Deserialize(filePath, 2); } - private void get_values(RegistryKey key, string subKeyName, IList values, bool expandValues) + private void GetValues(RegistryKey key, string subKeyName, IList values, bool expandValues) { if (key != null) { - var subKey = FaultTolerance.try_catch_with_logging_exception( + var subKey = FaultTolerance.TryCatchWithLoggingException( () => key.OpenSubKey(subKeyName, RegistryKeyPermissionCheck.ReadSubTree, RegistryRights.ReadKey), - "Could not open uninstall subkey for key '{0}'".format_with(key.Name), + "Could not open uninstall subkey for key '{0}'".FormatWith(key.Name), logWarningInsteadOfError: true); if (subKey != null) @@ -414,36 +405,36 @@ private void get_values(RegistryKey key, string subKeyName, IList get_environment_values() + public IEnumerable GetEnvironmentValues() { IList environmentValues = new List(); - get_values(open_key(RegistryHive.CurrentUser, RegistryView.Default), USER_ENVIRONMENT_REGISTRY_KEY_NAME, environmentValues, expandValues: false); - get_values(open_key(RegistryHive.LocalMachine, RegistryView.Default), MACHINE_ENVIRONMENT_REGISTRY_KEY_NAME, environmentValues, expandValues: false); + GetValues(OpenKey(RegistryHive.CurrentUser, RegistryView.Default), UserEnvironmentRegistryKeyName, environmentValues, expandValues: false); + GetValues(OpenKey(RegistryHive.LocalMachine, RegistryView.Default), MachineEnvironmentRegistryKeyName, environmentValues, expandValues: false); return environmentValues; } - public IEnumerable get_added_changed_environment_differences(IEnumerable before, IEnumerable after) + public IEnumerable GetNewAndModifiedEnvironmentValues(IEnumerable before, IEnumerable after) { return after.Except(before).ToList(); } - public IEnumerable get_removed_environment_differences(IEnumerable before, IEnumerable after) + public IEnumerable GetRemovedEnvironmentValues(IEnumerable before, IEnumerable after) { var removals = new List(); - foreach (var beforeValue in before.or_empty_list_if_null()) + foreach (var beforeValue in before.OrEmpty()) { - var afterValue = after.FirstOrDefault(a => a.Name.is_equal_to(beforeValue.Name) && a.ParentKeyName.is_equal_to(beforeValue.ParentKeyName)); + var afterValue = after.FirstOrDefault(a => a.Name.IsEqualTo(beforeValue.Name) && a.ParentKeyName.IsEqualTo(beforeValue.ParentKeyName)); if (afterValue == null) { removals.Add(beforeValue); @@ -453,7 +444,7 @@ public IEnumerable get_removed_environment_differences(IEn return removals; } - public RegistryKey get_key(RegistryHive hive, string subKeyPath) + public RegistryKey GetKey(RegistryHive hive, string subKeyPath) { IList keyLocations = new List(); if (Environment.Is64BitOperatingSystem) @@ -478,9 +469,9 @@ public RegistryKey get_key(RegistryHive hive, string subKeyPath) return null; } - public static GenericRegistryValue get_value(RegistryHiveType hive, string subKeyPath, string registryValue) + public static GenericRegistryValue GetRegistryValue(RegistryHiveType hive, string subKeyPath, string registryValue) { - var hiveActual = (RegistryHive)Enum.Parse(typeof(RegistryHive), hive.to_string(), ignoreCase: true); + var hiveActual = (RegistryHive)Enum.Parse(typeof(RegistryHive), hive.ToStringSafe(), ignoreCase: true); IList keyLocations = new List(); if (Environment.Is64BitOperatingSystem) { @@ -498,7 +489,7 @@ public static GenericRegistryValue get_value(RegistryHiveType hive, string subKe var key = topLevelRegistryKey.OpenSubKey(subKeyPath, RegistryKeyPermissionCheck.ReadSubTree, RegistryRights.ReadKey); if (key != null) { - value = FaultTolerance.try_catch_with_logging_exception( + value = FaultTolerance.TryCatchWithLoggingException( () => { if (key.GetValueNames().Contains(registryValue, StringComparer.InvariantCultureIgnoreCase)) @@ -507,14 +498,14 @@ public static GenericRegistryValue get_value(RegistryHiveType hive, string subKe { Name = registryValue, ParentKeyName = key.Name, - Type = (RegistryValueKindType)Enum.Parse(typeof(RegistryValueKindType), key.GetValueKind(registryValue).to_string(), ignoreCase: true), - Value = key.get_value_as_string(registryValue), + Type = (RegistryValueKindType)Enum.Parse(typeof(RegistryValueKindType), key.GetValueKind(registryValue).ToStringSafe(), ignoreCase: true), + Value = key.AsXmlSafeString(registryValue), }; } return null; }, - "Could not get registry value '{0}' from key '{1}'".format_with(registryValue, key.Name), + "Could not get registry value '{0}' from key '{1}'".FormatWith(registryValue, key.Name), logWarningInsteadOfError: true); if (value != null) break; @@ -524,6 +515,51 @@ public static GenericRegistryValue get_value(RegistryHiveType hive, string subKe return value; } - } +#pragma warning disable IDE1006 + [Obsolete("This overload is deprecated and will be removed in v3.")] + public Registry get_installer_keys() + => GetInstallerKeys(); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public void evaluate_keys(RegistryKey key, Registry snapshot) + => UpdateSnapshot(key, snapshot); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public Registry get_installer_key_differences(Registry before, Registry after) + => GetInstallerKeysChanged(before, after); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public void save_to_file(Registry snapshot, string filePath) + => SaveRegistrySnapshot(snapshot, filePath); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public bool installer_value_exists(string keyPath, string value) + => InstallerKeyExists(keyPath); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public Registry read_from_file(string filePath) + => ReadRegistrySnapshot(filePath); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public IEnumerable get_environment_values() + => GetEnvironmentValues(); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public IEnumerable get_added_changed_environment_differences(IEnumerable before, IEnumerable after) + => GetNewAndModifiedEnvironmentValues(before, after); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public IEnumerable get_removed_environment_differences(IEnumerable before, IEnumerable after) + => GetRemovedEnvironmentValues(before, after); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public RegistryKey get_key(RegistryHive hive, string subKeyPath) + => GetKey(hive, subKeyPath); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public static GenericRegistryValue get_value(RegistryHiveType hive, string subKeyPath, string registryValue) + => GetRegistryValue(hive, subKeyPath, registryValue); +#pragma warning restore IDE1006 + } } diff --git a/src/chocolatey/infrastructure.app/services/RubyGemsService.cs b/src/chocolatey/infrastructure.app/services/RubyGemsService.cs index 212fe8f7dc..6ffb618ef9 100644 --- a/src/chocolatey/infrastructure.app/services/RubyGemsService.cs +++ b/src/chocolatey/infrastructure.app/services/RubyGemsService.cs @@ -28,22 +28,25 @@ namespace chocolatey.infrastructure.app.services using results; using platforms; - public sealed class RubyGemsService : ISourceRunner + public sealed class RubyGemsService : IBootstrappableSourceRunner, IListSourceRunner, IInstallSourceRunner { private readonly ICommandExecutor _commandExecutor; private readonly INugetService _nugetService; - private const string PACKAGE_NAME_TOKEN = "{{packagename}}"; - private const string EXE_PATH = "cmd.exe"; - private const string APP_NAME = "Ruby Gems"; - public const string RUBY_PORTABLE_PACKAGE = "ruby.portable"; - public const string RUBY_PACKAGE = "ruby"; - public const string PACKAGE_NAME_GROUP = "PkgName"; - public static readonly Regex InstallingRegex = new Regex(@"Fetching:", RegexOptions.Compiled); - public static readonly Regex InstalledRegex = new Regex(@"Successfully installed", RegexOptions.Compiled); - public static readonly Regex ErrorNotFoundRegex = new Regex(@"ERROR: Could not find a valid gem", RegexOptions.Compiled); - public static readonly Regex PackageNameFetchingRegex = new Regex(@"Fetching: (?<{0}>.*)\-".format_with(PACKAGE_NAME_GROUP), RegexOptions.Compiled); - public static readonly Regex PackageNameInstalledRegex = new Regex(@"Successfully installed (?<{0}>.*)\-".format_with(PACKAGE_NAME_GROUP), RegexOptions.Compiled); - public static readonly Regex PackageNameErrorRegex = new Regex(@"'(?<{0}>[^']*)'".format_with(PACKAGE_NAME_GROUP), RegexOptions.Compiled); + + private const string PackageNameToken = "{{packagename}}"; + private const string ExePath = "cmd.exe"; + private const string AppName = "Ruby Gems"; + + public const string RubyPortalPackage = "ruby.portable"; + public const string RubyPackage = "ruby"; + public const string PackageNameGroup = "PkgName"; + + private static readonly Regex _installingRegex = new Regex(@"Fetching:", RegexOptions.Compiled); + private static readonly Regex _installedRegex = new Regex(@"Successfully installed", RegexOptions.Compiled); + private static readonly Regex _errorNotFoundRegex = new Regex(@"ERROR: Could not find a valid gem", RegexOptions.Compiled); + private static readonly Regex _packageNameFetchingRegex = new Regex(@"Fetching: (?<{0}>.*)\-".FormatWith(PackageNameGroup), RegexOptions.Compiled); + private static readonly Regex _packageNameInstalledRegex = new Regex(@"Successfully installed (?<{0}>.*)\-".FormatWith(PackageNameGroup), RegexOptions.Compiled); + private static readonly Regex _packageNameErrorRegex = new Regex(@"'(?<{0}>[^']*)'".FormatWith(PackageNameGroup), RegexOptions.Compiled); private readonly IDictionary _listArguments = new Dictionary(StringComparer.InvariantCultureIgnoreCase); private readonly IDictionary _installArguments = new Dictionary(StringComparer.InvariantCultureIgnoreCase); @@ -52,22 +55,22 @@ public RubyGemsService(ICommandExecutor commandExecutor, INugetService nugetServ { _commandExecutor = commandExecutor; _nugetService = nugetService; - set_cmd_args_dictionaries(); + SetupCommandArgsDictionaries(); } /// /// Set any command arguments dictionaries necessary for the service /// - private void set_cmd_args_dictionaries() + private void SetupCommandArgsDictionaries() { - set_list_dictionary(_listArguments); - set_install_dictionary(_installArguments); + SetupListDictionary(_listArguments); + SetupInstallDictionary(_installArguments); } /// /// Sets list dictionary /// - private void set_list_dictionary(IDictionary args) + private void SetupListDictionary(IDictionary args) { args.Add("_cmd_c_", new ExternalCommandArgument { ArgumentOption = "/c", Required = true }); args.Add("_gem_", new ExternalCommandArgument { ArgumentOption = "gem", Required = true }); @@ -77,7 +80,7 @@ private void set_list_dictionary(IDictionary ar /// /// Sets install dictionary /// - private void set_install_dictionary(IDictionary args) + private void SetupInstallDictionary(IDictionary args) { args.Add("_cmd_c_", new ExternalCommandArgument { ArgumentOption = "/c", Required = true }); args.Add("_gem_", new ExternalCommandArgument { ArgumentOption = "gem", Required = true }); @@ -85,7 +88,7 @@ private void set_install_dictionary(IDictionary args.Add("_package_name_", new ExternalCommandArgument { ArgumentOption = "package name ", - ArgumentValue = PACKAGE_NAME_TOKEN, + ArgumentValue = PackageNameToken, QuoteValue = false, UseValueOnly = true, Required = true @@ -108,16 +111,16 @@ private void set_install_dictionary(IDictionary public string SourceType { - get { return SourceTypes.RUBY; } + get { return SourceTypes.Ruby; } } - public void ensure_source_app_installed(ChocolateyConfiguration config, Action ensureAction) + public void EnsureSourceAppInstalled(ChocolateyConfiguration config, Action ensureAction) { - if (Platform.get_platform() != PlatformType.Windows) throw new NotImplementedException("This source is not supported on non-Windows systems"); + if (Platform.GetPlatform() != PlatformType.Windows) throw new NotImplementedException("This source is not supported on non-Windows systems"); var runnerConfig = new ChocolateyConfiguration { - PackageNames = RUBY_PORTABLE_PACKAGE, + PackageNames = RubyPortalPackage, Sources = ApplicationParameters.PackagesLocation, Debug = config.Debug, Force = config.Force, @@ -131,37 +134,32 @@ public void ensure_source_app_installed(ChocolateyConfiguration config, Action

p.Name.is_equal_to(RUBY_PACKAGE) || p.Name.is_equal_to(RUBY_PORTABLE_PACKAGE))) + if (!localPackages.Any(p => p.Name.IsEqualTo(RubyPackage) || p.Name.IsEqualTo(RubyPortalPackage))) { runnerConfig.Sources = ApplicationParameters.ChocolateyCommunityFeedSource; var prompt = config.PromptForConfirmation; config.PromptForConfirmation = false; - _nugetService.install_run(runnerConfig, ensureAction.Invoke); + _nugetService.Install(runnerConfig, ensureAction.Invoke); config.PromptForConfirmation = prompt; } } - public int count_run(ChocolateyConfiguration config) + public void ListDryRun(ChocolateyConfiguration config) { - throw new NotImplementedException("Count is not supported for this source runner."); + var args = ExternalCommandArgsBuilder.BuildArguments(config, _listArguments); + this.Log().Info("Would have run '{0} {1}'".FormatWith(ExePath.EscapeCurlyBraces(), args.EscapeCurlyBraces())); } - public void list_noop(ChocolateyConfiguration config) - { - var args = ExternalCommandArgsBuilder.build_arguments(config, _listArguments); - this.Log().Info("Would have run '{0} {1}'".format_with(EXE_PATH.escape_curly_braces(), args.escape_curly_braces())); - } - - public IEnumerable list_run(ChocolateyConfiguration config) + public IEnumerable List(ChocolateyConfiguration config) { var packageResults = new List(); - var args = ExternalCommandArgsBuilder.build_arguments(config, _listArguments); + var args = ExternalCommandArgsBuilder.BuildArguments(config, _listArguments); - Environment.ExitCode = _commandExecutor.execute( - EXE_PATH, + Environment.ExitCode = _commandExecutor.Execute( + ExePath, args, config.CommandExecutionTimeoutSeconds, stdOutAction: (s, e) => @@ -170,17 +168,17 @@ public IEnumerable list_run(ChocolateyConfiguration config) if (string.IsNullOrWhiteSpace(logMessage)) return; if (!config.QuietOutput) { - this.Log().Info(logMessage.escape_curly_braces()); + this.Log().Info(logMessage.EscapeCurlyBraces()); } else { - this.Log().Debug(() => "[{0}] {1}".format_with(APP_NAME, logMessage.escape_curly_braces())); + this.Log().Debug(() => "[{0}] {1}".FormatWith(AppName, logMessage.EscapeCurlyBraces())); } }, stdErrAction: (s, e) => { if (string.IsNullOrWhiteSpace(e.Data)) return; - this.Log().Error(() => "{0}".format_with(e.Data.escape_curly_braces())); + this.Log().Error(() => "{0}".FormatWith(e.Data.EscapeCurlyBraces())); }, updateProcessPath: false ); @@ -188,64 +186,64 @@ public IEnumerable list_run(ChocolateyConfiguration config) return packageResults; } - public void install_noop(ChocolateyConfiguration config, Action continueAction) + public void InstallDryRun(ChocolateyConfiguration config, Action continueAction) { - var args = ExternalCommandArgsBuilder.build_arguments(config, _installArguments); - args = args.Replace(PACKAGE_NAME_TOKEN, config.PackageNames.Replace(';', ',')); - this.Log().Info("Would have run '{0} {1}'".format_with(EXE_PATH.escape_curly_braces(), args.escape_curly_braces())); + var args = ExternalCommandArgsBuilder.BuildArguments(config, _installArguments); + args = args.Replace(PackageNameToken, config.PackageNames.Replace(';', ',')); + this.Log().Info("Would have run '{0} {1}'".FormatWith(ExePath.EscapeCurlyBraces(), args.EscapeCurlyBraces())); } - public ConcurrentDictionary install_run(ChocolateyConfiguration config, Action continueAction) + public ConcurrentDictionary Install(ChocolateyConfiguration config, Action continueAction) { - return install_run(config, continueAction, beforeModifyAction: null); + return Install(config, continueAction, beforeModifyAction: null); } - public ConcurrentDictionary install_run(ChocolateyConfiguration config, Action continueAction, Action beforeModifyAction) + public ConcurrentDictionary Install(ChocolateyConfiguration config, Action continueAction, Action beforeModifyAction) { var packageResults = new ConcurrentDictionary(StringComparer.InvariantCultureIgnoreCase); - var args = ExternalCommandArgsBuilder.build_arguments(config, _installArguments); + var args = ExternalCommandArgsBuilder.BuildArguments(config, _installArguments); foreach (var packageToInstall in config.PackageNames.Split(new[] { ApplicationParameters.PackageNamesSeparator }, StringSplitOptions.RemoveEmptyEntries)) { - var argsForPackage = args.Replace(PACKAGE_NAME_TOKEN, packageToInstall); - var exitCode = _commandExecutor.execute( - EXE_PATH, + var argsForPackage = args.Replace(PackageNameToken, packageToInstall); + var exitCode = _commandExecutor.Execute( + ExePath, argsForPackage, config.CommandExecutionTimeoutSeconds, (s, e) => { var logMessage = e.Data; if (string.IsNullOrWhiteSpace(logMessage)) return; - this.Log().Info(() => " [{0}] {1}".format_with(APP_NAME, logMessage.escape_curly_braces())); + this.Log().Info(() => " [{0}] {1}".FormatWith(AppName, logMessage.EscapeCurlyBraces())); - if (InstallingRegex.IsMatch(logMessage)) + if (_installingRegex.IsMatch(logMessage)) { - var packageName = get_value_from_output(logMessage, PackageNameFetchingRegex, PACKAGE_NAME_GROUP); + var packageName = GetValueFromOutput(logMessage, _packageNameFetchingRegex, PackageNameGroup); var results = packageResults.GetOrAdd(packageName, new PackageResult(packageName, null, null)); - this.Log().Info(ChocolateyLoggers.Important, "{0}".format_with(packageName)); + this.Log().Info(ChocolateyLoggers.Important, "{0}".FormatWith(packageName)); return; } //if (string.IsNullOrWhiteSpace(packageName)) return; - if (InstalledRegex.IsMatch(logMessage)) + if (_installedRegex.IsMatch(logMessage)) { - var packageName = get_value_from_output(logMessage, PackageNameInstalledRegex, PACKAGE_NAME_GROUP); + var packageName = GetValueFromOutput(logMessage, _packageNameInstalledRegex, PackageNameGroup); var results = packageResults.GetOrAdd(packageName, new PackageResult(packageName, null, null)); results.Messages.Add(new ResultMessage(ResultType.Note, packageName)); - this.Log().Info(ChocolateyLoggers.Important, " {0} has been installed successfully.".format_with(string.IsNullOrWhiteSpace(packageName) ? packageToInstall : packageName)); + this.Log().Info(ChocolateyLoggers.Important, " {0} has been installed successfully.".FormatWith(string.IsNullOrWhiteSpace(packageName) ? packageToInstall : packageName)); } }, (s, e) => { var logMessage = e.Data; if (string.IsNullOrWhiteSpace(logMessage)) return; - this.Log().Error("[{0}] {1}".format_with(APP_NAME, logMessage.escape_curly_braces())); + this.Log().Error("[{0}] {1}".FormatWith(AppName, logMessage.EscapeCurlyBraces())); - var packageName = get_value_from_output(logMessage, PackageNameErrorRegex, PACKAGE_NAME_GROUP); + var packageName = GetValueFromOutput(logMessage, _packageNameErrorRegex, PackageNameGroup); - if (ErrorNotFoundRegex.IsMatch(logMessage)) + if (_errorNotFoundRegex.IsMatch(logMessage)) { var results = packageResults.GetOrAdd(packageName, new PackageResult(packageName, null, null)); results.Messages.Add(new ResultMessage(ResultType.Error, packageName)); @@ -263,27 +261,6 @@ public ConcurrentDictionary install_run(ChocolateyConfigu return packageResults; } - public ConcurrentDictionary upgrade_noop(ChocolateyConfiguration config, Action continueAction) - { - this.Log().Warn(ChocolateyLoggers.Important, "{0} does not implement upgrade".format_with(APP_NAME)); - return new ConcurrentDictionary(StringComparer.InvariantCultureIgnoreCase); - } - - public ConcurrentDictionary upgrade_run(ChocolateyConfiguration config, Action continueAction, Action beforeUpgradeAction = null) - { - throw new NotImplementedException("{0} does not implement upgrade".format_with(APP_NAME)); - } - - public void uninstall_noop(ChocolateyConfiguration config, Action continueAction) - { - this.Log().Warn(ChocolateyLoggers.Important, "{0} does not implement uninstall".format_with(APP_NAME)); - } - - public ConcurrentDictionary uninstall_run(ChocolateyConfiguration config, Action continueAction, Action beforeUninstallAction = null) - { - throw new NotImplementedException("{0} does not implement uninstall".format_with(APP_NAME)); - } - ///

/// Grabs a value from the output based on the regex. /// @@ -291,7 +268,7 @@ public ConcurrentDictionary uninstall_run(ChocolateyConfi /// The regex. /// Name of the group. /// - private static string get_value_from_output(string output, Regex regex, string groupName) + private static string GetValueFromOutput(string output, Regex regex, string groupName) { var matchGroup = regex.Match(output).Groups[groupName]; if (matchGroup != null) @@ -301,5 +278,50 @@ private static string get_value_from_output(string output, Regex regex, string g return string.Empty; } + +#pragma warning disable IDE1006 + [Obsolete("This overload is deprecated and will be removed in v3.")] + public const string RUBY_PORTABLE_PACKAGE = "ruby.portable"; + [Obsolete("This overload is deprecated and will be removed in v3.")] + public const string RUBY_PACKAGE = "ruby"; + [Obsolete("This overload is deprecated and will be removed in v3.")] + public const string PACKAGE_NAME_GROUP = "PkgName"; + [Obsolete("This overload is deprecated and will be removed in v3.")] + public static readonly Regex InstallingRegex = _installingRegex; + [Obsolete("This overload is deprecated and will be removed in v3.")] + public static readonly Regex InstalledRegex = _installedRegex; + [Obsolete("This overload is deprecated and will be removed in v3.")] + public static readonly Regex ErrorNotFoundRegex = _errorNotFoundRegex; + [Obsolete("This overload is deprecated and will be removed in v3.")] + public static readonly Regex PackageNameFetchingRegex = _packageNameFetchingRegex; + [Obsolete("This overload is deprecated and will be removed in v3.")] + public static readonly Regex PackageNameInstalledRegex = _packageNameInstalledRegex; + [Obsolete("This overload is deprecated and will be removed in v3.")] + public static readonly Regex PackageNameErrorRegex = _packageNameErrorRegex; + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public void ensure_source_app_installed(ChocolateyConfiguration config, Action ensureAction) + => EnsureSourceAppInstalled(config, ensureAction); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public void list_noop(ChocolateyConfiguration config) + => ListDryRun(config); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public IEnumerable list_run(ChocolateyConfiguration config) + => List(config); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public void install_noop(ChocolateyConfiguration config, Action continueAction) + => InstallDryRun(config, continueAction); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public ConcurrentDictionary install_run(ChocolateyConfiguration config, Action continueAction) + => Install(config, continueAction); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public ConcurrentDictionary install_run(ChocolateyConfiguration config, Action continueAction, Action beforeModifyAction) + => Install(config, continueAction, beforeModifyAction); +#pragma warning restore IDE1006 } } diff --git a/src/chocolatey/infrastructure.app/services/RuleService.cs b/src/chocolatey/infrastructure.app/services/RuleService.cs index 2c6c40ad40..8478e83875 100644 --- a/src/chocolatey/infrastructure.app/services/RuleService.cs +++ b/src/chocolatey/infrastructure.app/services/RuleService.cs @@ -15,6 +15,7 @@ namespace chocolatey.infrastructure.app.services { + using System; using System.Collections.Generic; using System.Linq; using System.Threading; @@ -25,7 +26,7 @@ namespace chocolatey.infrastructure.app.services using NuGet.Configuration; using NuGet.Packaging; - public sealed class RuleService : IRuleService + public class RuleService : IRuleService { private readonly IMetadataRule[] _rules; @@ -34,15 +35,25 @@ public RuleService(IMetadataRule[] rules) _rules = rules; } - public IEnumerable validate_rules(string filePath) + public virtual IReadOnlyList GetAllAvailableRules() + { + return _rules.SelectMany(r => r.GetAvailableRules()) + .Distinct(new RuleIdEqualityComparer()) + .OrderBy(r => r.Severity) + .ThenBy(r => r.Id) + .ToList() + .AsReadOnly(); + } + + public virtual IEnumerable ValidateRules(string filePath) { - Ensure.that(() => filePath) - .is_not_null_or_whitespace() - .has_any_extension(NuGetConstants.PackageExtension, NuGetConstants.ManifestExtension); + Ensure.That(() => filePath) + .NotNullOrWhitespace() + .HasExtension(NuGetConstants.PackageExtension, NuGetConstants.ManifestExtension); var rules = filePath.EndsWith(NuGetConstants.PackageExtension) - ? get_rules_from_package_async(filePath).GetAwaiter().GetResult() - : get_rules_from_metadata(filePath); + ? GetRulesFromPackageAsync(filePath).GetAwaiter().GetResult() + : GetRulesFromMetadata(filePath); return rules .OrderBy(r => r.Severity) @@ -50,7 +61,7 @@ public IEnumerable validate_rules(string filePath) .ThenBy(r => r.Message); } - private async Task> get_rules_from_package_async(string filePath, CancellationToken token = default) + private async Task> GetRulesFromPackageAsync(string filePath, CancellationToken token = default) { using (var packageReader = new PackageArchiveReader(filePath)) { @@ -59,22 +70,22 @@ private async Task> get_rules_from_package_async(string // We add ToList here to ensure that the package // reader hasn't been disposed of before we return // any results. - return validate_nuspec(nuspecReader, _rules).ToList(); + return ValidateNuspec(nuspecReader, _rules).ToList(); } } - private IEnumerable get_rules_from_metadata(string filePath) + private IEnumerable GetRulesFromMetadata(string filePath) { var nuspecReader = new NuspecReader(filePath); - return validate_nuspec(nuspecReader, _rules); + return ValidateNuspec(nuspecReader, _rules); } - private static IEnumerable validate_nuspec(NuspecReader reader, IMetadataRule[] rules) + private static IEnumerable ValidateNuspec(NuspecReader reader, IMetadataRule[] rules) { foreach (var rule in rules) { - var validationResults = rule.validate(reader); + var validationResults = rule.Validate(reader); foreach (var result in validationResults.Where(v => v.Severity != RuleType.None)) { @@ -82,5 +93,24 @@ private static IEnumerable validate_nuspec(NuspecReader reader, IMet } } } + +#pragma warning disable IDE1006 + [Obsolete("This overload is deprecated and will be removed in v3.")] + public IEnumerable validate_rules(string filePath) + => ValidateRules(filePath); +#pragma warning restore IDE1006 + + private class RuleIdEqualityComparer : IEqualityComparer + { + public bool Equals(ImmutableRule x, ImmutableRule y) + { + return ReferenceEquals(x, y) || x.Id.IsEqualTo(x.Id); + } + + public int GetHashCode(ImmutableRule obj) + { + return obj.Id.GetHashCode(); + } + } } } diff --git a/src/chocolatey/infrastructure.app/services/ShimGenerationService.cs b/src/chocolatey/infrastructure.app/services/ShimGenerationService.cs index b73667bc03..0ebcc58130 100644 --- a/src/chocolatey/infrastructure.app/services/ShimGenerationService.cs +++ b/src/chocolatey/infrastructure.app/services/ShimGenerationService.cs @@ -28,9 +28,9 @@ public class ShimGenerationService : IShimGenerationService { private readonly IFileSystem _fileSystem; private readonly ICommandExecutor _commandExecutor; - private const string PATH_TOKEN = "{{path}}"; - private const string ICON_PATH_TOKEN = "{{icon_path}}"; - private const string OUTPUT_TOKEN = "{{output}}"; + private const string PathToken = "{{path}}"; + private const string IconPathToken = "{{icon_path}}"; + private const string OutputToken = "{{output}}"; private readonly string _shimGenExePath = ApplicationParameters.Tools.ShimGenExe; private readonly IDictionary _shimGenArguments = new Dictionary(StringComparer.InvariantCultureIgnoreCase); @@ -39,18 +39,18 @@ public ShimGenerationService(IFileSystem fileSystem, ICommandExecutor commandExe { _fileSystem = fileSystem; _commandExecutor = commandExecutor; - set_shimgen_args_dictionary(); + SetupShimgenArgsDictionary(); } /// /// Sets up shimgen arguments /// - private void set_shimgen_args_dictionary() + private void SetupShimgenArgsDictionary() { _shimGenArguments.Add("_file_path_", new ExternalCommandArgument { ArgumentOption = "--path=", - ArgumentValue = PATH_TOKEN, + ArgumentValue = PathToken, QuoteValue = true, Required = true }); @@ -58,7 +58,7 @@ private void set_shimgen_args_dictionary() _shimGenArguments.Add("_output_directory_", new ExternalCommandArgument { ArgumentOption = "--output=", - ArgumentValue = OUTPUT_TOKEN, + ArgumentValue = OutputToken, QuoteValue = true, Required = true }); @@ -66,7 +66,7 @@ private void set_shimgen_args_dictionary() _shimGenArguments.Add("_icon_path_", new ExternalCommandArgument { ArgumentOption = " --iconpath=", - ArgumentValue = ICON_PATH_TOKEN, + ArgumentValue = IconPathToken, QuoteValue = true, Required = true }); @@ -75,45 +75,45 @@ private void set_shimgen_args_dictionary() } - public void install(ChocolateyConfiguration configuration, PackageResult packageResult) + public void Install(ChocolateyConfiguration configuration, PackageResult packageResult) { - _fileSystem.create_directory_if_not_exists(ApplicationParameters.ShimsLocation); + _fileSystem.EnsureDirectoryExists(ApplicationParameters.ShimsLocation); - if (packageResult.InstallLocation.is_equal_to(ApplicationParameters.InstallLocation) || packageResult.InstallLocation.is_equal_to(ApplicationParameters.PackagesLocation)) + if (packageResult.InstallLocation.IsEqualTo(ApplicationParameters.InstallLocation) || packageResult.InstallLocation.IsEqualTo(ApplicationParameters.PackagesLocation)) { - var logMessage = "Install location is not specific enough, cannot run shimgen:{0} Erroneous install location captured as '{1}'".format_with(Environment.NewLine, packageResult.InstallLocation); + var logMessage = "Install location is not specific enough, cannot run shimgen:{0} Erroneous install location captured as '{1}'".FormatWith(Environment.NewLine, packageResult.InstallLocation); packageResult.Messages.Add(new ResultMessage(ResultType.Warn, logMessage)); - this.Log().Error(logMessage.escape_curly_braces()); + this.Log().Error(logMessage.EscapeCurlyBraces()); return; } //gather all .exes in the folder - var exeFiles = _fileSystem.get_files(packageResult.InstallLocation, pattern: "*.exe", option: SearchOption.AllDirectories); - foreach (string file in exeFiles.or_empty_list_if_null()) + var exeFiles = _fileSystem.GetFiles(packageResult.InstallLocation, pattern: "*.exe", option: SearchOption.AllDirectories); + foreach (string file in exeFiles.OrEmpty()) { - if (_fileSystem.file_exists(file + ".ignore")) continue; - bool isGui = _fileSystem.file_exists(file + ".gui"); + if (_fileSystem.FileExists(file + ".ignore")) continue; + bool isGui = _fileSystem.FileExists(file + ".gui"); //todo: #2586 v2 be able to determine gui automatically - var args = ExternalCommandArgsBuilder.build_arguments(configuration, _shimGenArguments); - var shimLocation = _fileSystem.combine_paths(ApplicationParameters.ShimsLocation, _fileSystem.get_file_name(file)); - var argsForPackage = args.Replace(PATH_TOKEN, file.Replace(ApplicationParameters.InstallLocation, "..\\")).Replace(OUTPUT_TOKEN, shimLocation).Replace(ICON_PATH_TOKEN, file); + var args = ExternalCommandArgsBuilder.BuildArguments(configuration, _shimGenArguments); + var shimLocation = _fileSystem.CombinePaths(ApplicationParameters.ShimsLocation, _fileSystem.GetFileName(file)); + var argsForPackage = args.Replace(PathToken, file.Replace(ApplicationParameters.InstallLocation, "..\\")).Replace(OutputToken, shimLocation).Replace(IconPathToken, file); if (isGui) { argsForPackage += " --gui"; } - var exitCode = _commandExecutor.execute( + var exitCode = _commandExecutor.Execute( _shimGenExePath, argsForPackage, configuration.CommandExecutionTimeoutSeconds, (s, e) => { if (string.IsNullOrWhiteSpace(e.Data)) return; - this.Log().Debug(() => " [ShimGen] {0}".format_with(e.Data.escape_curly_braces())); + this.Log().Debug(() => " [ShimGen] {0}".FormatWith(e.Data.EscapeCurlyBraces())); }, (s, e) => { if (string.IsNullOrWhiteSpace(e.Data)) return; - this.Log().Error(() => " [ShimGen] {0}".format_with(e.Data.escape_curly_braces())); + this.Log().Error(() => " [ShimGen] {0}".FormatWith(e.Data.EscapeCurlyBraces())); }, updateProcessPath: true ); @@ -124,24 +124,34 @@ public void install(ChocolateyConfiguration configuration, PackageResult package } else { - this.Log().Info(() => " ShimGen has successfully created a {0}shim for {1}".format_with(isGui ? "gui " : string.Empty, _fileSystem.get_file_name(file))); - this.Log().Debug(() => " Created: {0}{1} Targeting: {2}{1} IsGui:{3}{1}".format_with(shimLocation, Environment.NewLine, file, isGui)); + this.Log().Info(() => " ShimGen has successfully created a {0}shim for {1}".FormatWith(isGui ? "gui " : string.Empty, _fileSystem.GetFileName(file))); + this.Log().Debug(() => " Created: {0}{1} Targeting: {2}{1} IsGui:{3}{1}".FormatWith(shimLocation, Environment.NewLine, file, isGui)); } } } - public void uninstall(ChocolateyConfiguration configuration, PackageResult packageResult) + public void Uninstall(ChocolateyConfiguration configuration, PackageResult packageResult) { //gather all .exes in the folder - var exeFiles = _fileSystem.get_files(packageResult.InstallLocation, pattern: "*.exe", option: SearchOption.AllDirectories); - foreach (string file in exeFiles.or_empty_list_if_null()) + var exeFiles = _fileSystem.GetFiles(packageResult.InstallLocation, pattern: "*.exe", option: SearchOption.AllDirectories); + foreach (string file in exeFiles.OrEmpty()) { - if (_fileSystem.file_exists(file + ".ignore")) continue; + if (_fileSystem.FileExists(file + ".ignore")) continue; - var shimLocation = _fileSystem.combine_paths(ApplicationParameters.ShimsLocation, _fileSystem.get_file_name(file)); - this.Log().Debug(() => "Removing shim for {0} at '{1}".format_with(_fileSystem.get_file_name(file), shimLocation)); - _fileSystem.delete_file(shimLocation); + var shimLocation = _fileSystem.CombinePaths(ApplicationParameters.ShimsLocation, _fileSystem.GetFileName(file)); + this.Log().Debug(() => "Removing shim for {0} at '{1}".FormatWith(_fileSystem.GetFileName(file), shimLocation)); + _fileSystem.DeleteFile(shimLocation); } } + +#pragma warning disable IDE1006 + [Obsolete("This overload is deprecated and will be removed in v3.")] + public void install(ChocolateyConfiguration configuration, PackageResult packageResult) + => Install(configuration, packageResult); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public void uninstall(ChocolateyConfiguration configuration, PackageResult packageResult) + => Uninstall(configuration, packageResult); +#pragma warning restore IDE1006 } } diff --git a/src/chocolatey/infrastructure.app/services/TemplateService.cs b/src/chocolatey/infrastructure.app/services/TemplateService.cs index ab47e833c7..c10014be5f 100644 --- a/src/chocolatey/infrastructure.app/services/TemplateService.cs +++ b/src/chocolatey/infrastructure.app/services/TemplateService.cs @@ -29,14 +29,11 @@ namespace chocolatey.infrastructure.app.services using tokens; using nuget; using NuGet.Common; - using NuGet.PackageManagement; - using NuGet.Protocol.Core.Types; - using NuGet.Versioning; using IFileSystem = filesystem.IFileSystem; public class TemplateService : ITemplateService { - private readonly UTF8Encoding utf8WithoutBOM = new UTF8Encoding(false); + private readonly UTF8Encoding _utf8WithoutBOM = new UTF8Encoding(false); private readonly IFileSystem _fileSystem; private readonly ILogger _nugetLogger; private readonly IXmlService _xmlService; @@ -59,39 +56,39 @@ public TemplateService(IFileSystem fileSystem, IXmlService xmlService, ILogger l _nugetLogger = logger; } - public void generate_noop(ChocolateyConfiguration configuration) + public void GenerateDryRun(ChocolateyConfiguration configuration) { - var templateLocation = _fileSystem.combine_paths(configuration.OutputDirectory ?? _fileSystem.get_current_directory(), configuration.NewCommand.Name); - this.Log().Info(() => "Would have generated a new package specification at {0}".format_with(templateLocation)); + var templateLocation = _fileSystem.CombinePaths(configuration.OutputDirectory ?? _fileSystem.GetCurrentDirectory(), configuration.NewCommand.Name); + this.Log().Info(() => "Would have generated a new package specification at {0}".FormatWith(templateLocation)); } - public void generate(ChocolateyConfiguration configuration) + public void Generate(ChocolateyConfiguration configuration) { var logger = ChocolateyLoggers.Normal; if (configuration.QuietOutput) logger = ChocolateyLoggers.LogFileOnly; - var packageLocation = _fileSystem.combine_paths(configuration.OutputDirectory ?? _fileSystem.get_current_directory(), configuration.NewCommand.Name); - if (_fileSystem.directory_exists(packageLocation) && !configuration.Force) + var packageLocation = _fileSystem.CombinePaths(configuration.OutputDirectory ?? _fileSystem.GetCurrentDirectory(), configuration.NewCommand.Name); + if (_fileSystem.DirectoryExists(packageLocation) && !configuration.Force) { throw new ApplicationException( - "The location for the template already exists. You can:{0} 1. Remove '{1}'{0} 2. Use --force{0} 3. Specify a different name".format_with(Environment.NewLine, packageLocation)); + "The location for the template already exists. You can:{0} 1. Remove '{1}'{0} 2. Use --force{0} 3. Specify a different name".FormatWith(Environment.NewLine, packageLocation)); } - if (configuration.RegularOutput) this.Log().Info(logger, () => "Creating a new package specification at {0}".format_with(packageLocation)); + if (configuration.RegularOutput) this.Log().Info(logger, () => "Creating a new package specification at {0}".FormatWith(packageLocation)); try { - _fileSystem.delete_directory_if_exists(packageLocation, recursive: true); + _fileSystem.DeleteDirectoryChecked(packageLocation, recursive: true); } catch (Exception ex) { - if (configuration.RegularOutput) this.Log().Warn(() => "{0}".format_with(ex.Message)); + if (configuration.RegularOutput) this.Log().Warn(() => "{0}".FormatWith(ex.Message)); } - _fileSystem.create_directory_if_not_exists(packageLocation); - var packageToolsLocation = _fileSystem.combine_paths(packageLocation, "tools"); - _fileSystem.create_directory_if_not_exists(packageToolsLocation); + _fileSystem.EnsureDirectoryExists(packageLocation); + var packageToolsLocation = _fileSystem.CombinePaths(packageLocation, "tools"); + _fileSystem.EnsureDirectoryExists(packageToolsLocation); var tokens = new TemplateValues(); - if (configuration.NewCommand.AutomaticPackage) tokens.set_auto(); + if (configuration.NewCommand.AutomaticPackage) tokens.SetAutomatic(); // now override those values foreach (var property in configuration.NewCommand.TemplateProperties) @@ -99,11 +96,11 @@ public void generate(ChocolateyConfiguration configuration) try { tokens.GetType().GetProperty(property.Key, BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.IgnoreCase).SetValue(tokens, property.Value, null); - this.Log().Debug(() => "Set token for '{0}' to '{1}'".format_with(property.Key, property.Value)); + this.Log().Debug(() => "Set token for '{0}' to '{1}'".FormatWith(property.Key, property.Value)); } catch (Exception) { - if (configuration.RegularOutput) this.Log().Debug("Property {0} will be added to additional properties.".format_with(property.Key)); + if (configuration.RegularOutput) this.Log().Debug("Property {0} will be added to additional properties.".FormatWith(property.Key)); tokens.AdditionalProperties.Add(property.Key, property.Value); } } @@ -111,11 +108,11 @@ public void generate(ChocolateyConfiguration configuration) this.Log().Debug(() => "Token Values after merge:"); foreach (var propertyInfo in tokens.GetType().GetProperties()) { - this.Log().Debug(() => " {0}={1}".format_with(propertyInfo.Name, propertyInfo.GetValue(tokens, null))); + this.Log().Debug(() => " {0}={1}".FormatWith(propertyInfo.Name, propertyInfo.GetValue(tokens, null))); } - foreach (var additionalProperty in tokens.AdditionalProperties.or_empty_list_if_null()) + foreach (var additionalProperty in tokens.AdditionalProperties.OrEmpty()) { - this.Log().Debug(() => " {0}={1}".format_with(additionalProperty.Key, additionalProperty.Value)); + this.Log().Debug(() => " {0}={1}".FormatWith(additionalProperty.Key, additionalProperty.Value)); } // Attempt to set the name of the template that will be used to generate the new package @@ -127,106 +124,106 @@ public void generate(ChocolateyConfiguration configuration) var defaultTemplateName = configuration.DefaultTemplateName; if (string.IsNullOrWhiteSpace(configuration.NewCommand.TemplateName) && !string.IsNullOrWhiteSpace(defaultTemplateName) && !configuration.NewCommand.UseOriginalTemplate) { - var defaultTemplateNameLocation = _fileSystem.combine_paths(ApplicationParameters.TemplatesLocation, defaultTemplateName); - if (!_fileSystem.directory_exists(defaultTemplateNameLocation)) + var defaultTemplateNameLocation = _fileSystem.CombinePaths(ApplicationParameters.TemplatesLocation, defaultTemplateName); + if (!_fileSystem.DirectoryExists(defaultTemplateNameLocation)) { - this.Log().Warn(() => "defaultTemplateName configuration value has been set to '{0}', but no template with that name exists in '{1}'. Reverting to default template.".format_with(defaultTemplateName, ApplicationParameters.TemplatesLocation)); + this.Log().Warn(() => "defaultTemplateName configuration value has been set to '{0}', but no template with that name exists in '{1}'. Reverting to default template.".FormatWith(defaultTemplateName, ApplicationParameters.TemplatesLocation)); } else { - this.Log().Debug(() => "Setting TemplateName to '{0}'".format_with(defaultTemplateName)); + this.Log().Debug(() => "Setting TemplateName to '{0}'".FormatWith(defaultTemplateName)); configuration.NewCommand.TemplateName = defaultTemplateName; } } - var defaultTemplateOverride = _fileSystem.combine_paths(ApplicationParameters.TemplatesLocation, "default"); - if (string.IsNullOrWhiteSpace(configuration.NewCommand.TemplateName) && (!_fileSystem.directory_exists(defaultTemplateOverride) || configuration.NewCommand.UseOriginalTemplate)) + var defaultTemplateOverride = _fileSystem.CombinePaths(ApplicationParameters.TemplatesLocation, "default"); + if (string.IsNullOrWhiteSpace(configuration.NewCommand.TemplateName) && (!_fileSystem.DirectoryExists(defaultTemplateOverride) || configuration.NewCommand.UseOriginalTemplate)) { - generate_file_from_template(configuration, tokens, NuspecTemplate.Template, _fileSystem.combine_paths(packageLocation, "{0}.nuspec".format_with(tokens.PackageNameLower)), utf8WithoutBOM); - generate_file_from_template(configuration, tokens, ChocolateyInstallTemplate.Template, _fileSystem.combine_paths(packageToolsLocation, "chocolateyinstall.ps1"), Encoding.UTF8); - generate_file_from_template(configuration, tokens, ChocolateyBeforeModifyTemplate.Template, _fileSystem.combine_paths(packageToolsLocation, "chocolateybeforemodify.ps1"), Encoding.UTF8); - generate_file_from_template(configuration, tokens, ChocolateyUninstallTemplate.Template, _fileSystem.combine_paths(packageToolsLocation, "chocolateyuninstall.ps1"), Encoding.UTF8); - generate_file_from_template(configuration, tokens, ChocolateyLicenseFileTemplate.Template, _fileSystem.combine_paths(packageToolsLocation, "LICENSE.txt"), Encoding.UTF8); - generate_file_from_template(configuration, tokens, ChocolateyVerificationFileTemplate.Template, _fileSystem.combine_paths(packageToolsLocation, "VERIFICATION.txt"), Encoding.UTF8); - generate_file_from_template(configuration, tokens, ChocolateyReadMeTemplate.Template, _fileSystem.combine_paths(packageLocation, "ReadMe.md"), Encoding.UTF8); - generate_file_from_template(configuration, tokens, ChocolateyTodoTemplate.Template, _fileSystem.combine_paths(packageLocation, "_TODO.txt"), Encoding.UTF8); + GenerateFileFromTemplate(configuration, tokens, NuspecTemplate.Template, _fileSystem.CombinePaths(packageLocation, "{0}.nuspec".FormatWith(tokens.PackageNameLower)), _utf8WithoutBOM); + GenerateFileFromTemplate(configuration, tokens, ChocolateyInstallTemplate.Template, _fileSystem.CombinePaths(packageToolsLocation, "chocolateyinstall.ps1"), Encoding.UTF8); + GenerateFileFromTemplate(configuration, tokens, ChocolateyBeforeModifyTemplate.Template, _fileSystem.CombinePaths(packageToolsLocation, "chocolateybeforemodify.ps1"), Encoding.UTF8); + GenerateFileFromTemplate(configuration, tokens, ChocolateyUninstallTemplate.Template, _fileSystem.CombinePaths(packageToolsLocation, "chocolateyuninstall.ps1"), Encoding.UTF8); + GenerateFileFromTemplate(configuration, tokens, ChocolateyLicenseFileTemplate.Template, _fileSystem.CombinePaths(packageToolsLocation, "LICENSE.txt"), Encoding.UTF8); + GenerateFileFromTemplate(configuration, tokens, ChocolateyVerificationFileTemplate.Template, _fileSystem.CombinePaths(packageToolsLocation, "VERIFICATION.txt"), Encoding.UTF8); + GenerateFileFromTemplate(configuration, tokens, ChocolateyReadMeTemplate.Template, _fileSystem.CombinePaths(packageLocation, "ReadMe.md"), Encoding.UTF8); + GenerateFileFromTemplate(configuration, tokens, ChocolateyTodoTemplate.Template, _fileSystem.CombinePaths(packageLocation, "_TODO.txt"), Encoding.UTF8); } else { configuration.NewCommand.TemplateName = string.IsNullOrWhiteSpace(configuration.NewCommand.TemplateName) ? "default" : configuration.NewCommand.TemplateName; - var templatePath = _fileSystem.combine_paths(ApplicationParameters.TemplatesLocation, configuration.NewCommand.TemplateName); - var templateParameterCachePath = _fileSystem.combine_paths(templatePath, _templateParameterCacheFilename); - if (!_fileSystem.directory_exists(templatePath)) throw new ApplicationException("Unable to find path to requested template '{0}'. Path should be '{1}'".format_with(configuration.NewCommand.TemplateName, templatePath)); + var templatePath = _fileSystem.CombinePaths(ApplicationParameters.TemplatesLocation, configuration.NewCommand.TemplateName); + var templateParameterCachePath = _fileSystem.CombinePaths(templatePath, _templateParameterCacheFilename); + if (!_fileSystem.DirectoryExists(templatePath)) throw new ApplicationException("Unable to find path to requested template '{0}'. Path should be '{1}'".FormatWith(configuration.NewCommand.TemplateName, templatePath)); - this.Log().Info(configuration.QuietOutput ? logger : ChocolateyLoggers.Important, "Generating package from custom template at '{0}'.".format_with(templatePath)); + this.Log().Info(configuration.QuietOutput ? logger : ChocolateyLoggers.Important, "Generating package from custom template at '{0}'.".FormatWith(templatePath)); // Create directory structure from template so as to include empty directories - foreach (var directory in _fileSystem.get_directories(templatePath, "*.*", SearchOption.AllDirectories)) + foreach (var directory in _fileSystem.GetDirectories(templatePath, "*.*", SearchOption.AllDirectories)) { var packageDirectoryLocation = directory.Replace(templatePath, packageLocation); - this.Log().Debug("Creating directory {0}".format_with(packageDirectoryLocation)); - _fileSystem.create_directory_if_not_exists(packageDirectoryLocation); + this.Log().Debug("Creating directory {0}".FormatWith(packageDirectoryLocation)); + _fileSystem.EnsureDirectoryExists(packageDirectoryLocation); } - foreach (var file in _fileSystem.get_files(templatePath, "*.*", SearchOption.AllDirectories)) + foreach (var file in _fileSystem.GetFiles(templatePath, "*.*", SearchOption.AllDirectories)) { var packageFileLocation = file.Replace(templatePath, packageLocation); - var fileExtension = _fileSystem.get_file_extension(packageFileLocation); + var fileExtension = _fileSystem.GetFileExtension(packageFileLocation); - if (fileExtension.is_equal_to(".nuspec")) + if (fileExtension.IsEqualTo(".nuspec")) { - packageFileLocation = _fileSystem.combine_paths(packageLocation, "{0}.nuspec".format_with(tokens.PackageNameLower)); - generate_file_from_template(configuration, tokens, _fileSystem.read_file(file), packageFileLocation, utf8WithoutBOM); + packageFileLocation = _fileSystem.CombinePaths(packageLocation, "{0}.nuspec".FormatWith(tokens.PackageNameLower)); + GenerateFileFromTemplate(configuration, tokens, _fileSystem.ReadFile(file), packageFileLocation, _utf8WithoutBOM); } else if (_templateBinaryExtensions.Contains(fileExtension)) { - this.Log().Debug(" Treating template file ('{0}') as binary instead of replacing templated values.".format_with(_fileSystem.get_file_name(file))); - _fileSystem.copy_file(file, packageFileLocation, overwriteExisting:true); + this.Log().Debug(" Treating template file ('{0}') as binary instead of replacing templated values.".FormatWith(_fileSystem.GetFileName(file))); + _fileSystem.CopyFile(file, packageFileLocation, overwriteExisting:true); } - else if (templateParameterCachePath.is_equal_to(file)) + else if (templateParameterCachePath.IsEqualTo(file)) { - this.Log().Debug("{0} is the parameter cache file, ignoring".format_with(file)); + this.Log().Debug("{0} is the parameter cache file, ignoring".FormatWith(file)); } else { - generate_file_from_template(configuration, tokens, _fileSystem.read_file(file), packageFileLocation, Encoding.UTF8); + GenerateFileFromTemplate(configuration, tokens, _fileSystem.ReadFile(file), packageFileLocation, Encoding.UTF8); } } } this.Log().Info(configuration.QuietOutput ? logger : ChocolateyLoggers.Important, - "Successfully generated {0}{1} package specification files{2} at '{3}'".format_with( + "Successfully generated {0}{1} package specification files{2} at '{3}'".FormatWith( configuration.NewCommand.Name, configuration.NewCommand.AutomaticPackage ? " (automatic)" : string.Empty, Environment.NewLine, packageLocation)); } - public void generate_file_from_template(ChocolateyConfiguration configuration, TemplateValues tokens, string template, string fileLocation, Encoding encoding) + public void GenerateFileFromTemplate(ChocolateyConfiguration configuration, TemplateValues tokens, string template, string fileLocation, Encoding encoding) { - template = TokenReplacer.replace_tokens(tokens, template); - template = TokenReplacer.replace_tokens(tokens.AdditionalProperties, template); + template = TokenReplacer.ReplaceTokens(tokens, template); + template = TokenReplacer.ReplaceTokens(tokens.AdditionalProperties, template); - if (configuration.RegularOutput) this.Log().Info(() => "Generating template to a file{0} at '{1}'".format_with(Environment.NewLine, fileLocation)); - this.Log().Debug(() => "{0}".format_with(template)); - _fileSystem.create_directory_if_not_exists(_fileSystem.get_directory_name(fileLocation)); - _fileSystem.write_file(fileLocation, template, encoding); + if (configuration.RegularOutput) this.Log().Info(() => "Generating template to a file{0} at '{1}'".FormatWith(Environment.NewLine, fileLocation)); + this.Log().Debug(() => "{0}".FormatWith(template)); + _fileSystem.EnsureDirectoryExists(_fileSystem.GetDirectoryName(fileLocation)); + _fileSystem.WriteFile(fileLocation, template, encoding); } - public void list_noop(ChocolateyConfiguration configuration) + public void ListDryRun(ChocolateyConfiguration configuration) { if (string.IsNullOrWhiteSpace(configuration.TemplateCommand.Name)) { - this.Log().Info(() => "Would have listed templates in {0}".format_with(ApplicationParameters.TemplatesLocation)); + this.Log().Info(() => "Would have listed templates in {0}".FormatWith(ApplicationParameters.TemplatesLocation)); } else { - this.Log().Info(() => "Would have listed information about {0}".format_with(configuration.TemplateCommand.Name)); + this.Log().Info(() => "Would have listed information about {0}".FormatWith(configuration.TemplateCommand.Name)); } } - public void list(ChocolateyConfiguration configuration) + public void List(ChocolateyConfiguration configuration) { - var templateDirList = _fileSystem.get_directories(ApplicationParameters.TemplatesLocation).ToList(); - var isBuiltInTemplateOverridden = templateDirList.Contains(_fileSystem.combine_paths(ApplicationParameters.TemplatesLocation, _builtInTemplateOverrideName)); - var isBuiltInOrDefaultTemplateDefault = string.IsNullOrWhiteSpace(configuration.DefaultTemplateName) || !templateDirList.Contains(_fileSystem.combine_paths(ApplicationParameters.TemplatesLocation, configuration.DefaultTemplateName)); + var templateDirList = _fileSystem.GetDirectories(ApplicationParameters.TemplatesLocation).ToList(); + var isBuiltInTemplateOverridden = templateDirList.Contains(_fileSystem.CombinePaths(ApplicationParameters.TemplatesLocation, _builtInTemplateOverrideName)); + var isBuiltInOrDefaultTemplateDefault = string.IsNullOrWhiteSpace(configuration.DefaultTemplateName) || !templateDirList.Contains(_fileSystem.CombinePaths(ApplicationParameters.TemplatesLocation, configuration.DefaultTemplateName)); if (string.IsNullOrWhiteSpace(configuration.TemplateCommand.Name)) { @@ -234,27 +231,27 @@ public void list(ChocolateyConfiguration configuration) { foreach (var templateDir in templateDirList) { - configuration.TemplateCommand.Name = _fileSystem.get_file_name(templateDir); - list_custom_template_info(configuration); + configuration.TemplateCommand.Name = _fileSystem.GetFileName(templateDir); + ListCustomTemplateInformation(configuration); } - this.Log().Info(configuration.RegularOutput ? "{0} Custom templates found at {1}{2}".format_with(templateDirList.Count(), ApplicationParameters.TemplatesLocation, Environment.NewLine) : string.Empty); + this.Log().Info(configuration.RegularOutput ? "{0} Custom templates found at {1}{2}".FormatWith(templateDirList.Count(), ApplicationParameters.TemplatesLocation, Environment.NewLine) : string.Empty); } else { - this.Log().Info(configuration.RegularOutput ? "No custom templates installed in {0}{1}".format_with(ApplicationParameters.TemplatesLocation, Environment.NewLine) : string.Empty); + this.Log().Info(configuration.RegularOutput ? "No custom templates installed in {0}{1}".FormatWith(ApplicationParameters.TemplatesLocation, Environment.NewLine) : string.Empty); } - list_built_in_template_info(configuration, isBuiltInTemplateOverridden, isBuiltInOrDefaultTemplateDefault); + ListBuiltinTemplateInformation(configuration, isBuiltInTemplateOverridden, isBuiltInOrDefaultTemplateDefault); } else { - if (templateDirList.Contains(_fileSystem.combine_paths(ApplicationParameters.TemplatesLocation, configuration.TemplateCommand.Name))) + if (templateDirList.Contains(_fileSystem.CombinePaths(ApplicationParameters.TemplatesLocation, configuration.TemplateCommand.Name))) { - list_custom_template_info(configuration); + ListCustomTemplateInformation(configuration); if (configuration.TemplateCommand.Name == _builtInTemplateName || configuration.TemplateCommand.Name == _builtInTemplateOverrideName) { - list_built_in_template_info(configuration, isBuiltInTemplateOverridden, isBuiltInOrDefaultTemplateDefault); + ListBuiltinTemplateInformation(configuration, isBuiltInTemplateOverridden, isBuiltInOrDefaultTemplateDefault); } } else @@ -262,41 +259,40 @@ public void list(ChocolateyConfiguration configuration) if (configuration.TemplateCommand.Name.ToLowerInvariant() == _builtInTemplateName || configuration.TemplateCommand.Name.ToLowerInvariant() == _builtInTemplateOverrideName) { // We know that the template is not overridden since the template directory was checked - list_built_in_template_info(configuration, isBuiltInTemplateOverridden, isBuiltInOrDefaultTemplateDefault); + ListBuiltinTemplateInformation(configuration, isBuiltInTemplateOverridden, isBuiltInOrDefaultTemplateDefault); } else { - throw new ApplicationException("Unable to find requested template '{0}'".format_with(configuration.TemplateCommand.Name)); + throw new ApplicationException("Unable to find requested template '{0}'".FormatWith(configuration.TemplateCommand.Name)); } } } } - protected void list_custom_template_info(ChocolateyConfiguration configuration) + protected void ListCustomTemplateInformation(ChocolateyConfiguration configuration) { - var packageRepositories = NugetCommon.GetRemoteRepositories(configuration, _nugetLogger, _fileSystem); + var packageResources = NugetCommon.GetRepositoryResources(configuration, _nugetLogger, _fileSystem); var sourceCacheContext = new ChocolateySourceCacheContext(configuration); - var pkg = NugetList.find_package( - "{0}.template".format_with(configuration.TemplateCommand.Name), + var pkg = NugetList.FindPackage( + "{0}.template".FormatWith(configuration.TemplateCommand.Name), configuration, _nugetLogger, sourceCacheContext, - NugetCommon.GetRepositoryResource(packageRepositories), - NugetCommon.GetRepositoryResource(packageRepositories)); + packageResources); var templateInstalledViaPackage = (pkg != null); - var pkgVersion = templateInstalledViaPackage ? pkg.Identity.Version.to_string() : "0.0.0"; - var pkgTitle = templateInstalledViaPackage ? pkg.Title : "{0} (Unmanaged)".format_with(configuration.TemplateCommand.Name); + var pkgVersion = templateInstalledViaPackage ? pkg.Identity.Version.ToStringSafe() : "0.0.0"; + var pkgTitle = templateInstalledViaPackage ? pkg.Title : "{0} (Unmanaged)".FormatWith(configuration.TemplateCommand.Name); var pkgSummary = templateInstalledViaPackage ? - (pkg.Summary != null && !string.IsNullOrWhiteSpace(pkg.Summary.to_string()) ? "{0}".format_with(pkg.Summary.escape_curly_braces().to_string()) : string.Empty) : string.Empty; - var pkgDescription = templateInstalledViaPackage ? pkg.Description.escape_curly_braces().Replace("\n ", "\n").Replace("\n", "\n ") : string.Empty; - var pkgFiles = " {0}".format_with(string.Join("{0} " - .format_with(Environment.NewLine), _fileSystem.get_files(_fileSystem - .combine_paths(ApplicationParameters.TemplatesLocation, configuration.TemplateCommand.Name), "*", SearchOption.AllDirectories))); + (pkg.Summary != null && !string.IsNullOrWhiteSpace(pkg.Summary.ToStringSafe()) ? "{0}".FormatWith(pkg.Summary.EscapeCurlyBraces().ToStringSafe()) : string.Empty) : string.Empty; + var pkgDescription = templateInstalledViaPackage ? pkg.Description.EscapeCurlyBraces().Replace("\n ", "\n").Replace("\n", "\n ") : string.Empty; + var pkgFiles = " {0}".FormatWith(string.Join("{0} " + .FormatWith(Environment.NewLine), _fileSystem.GetFiles(_fileSystem + .CombinePaths(ApplicationParameters.TemplatesLocation, configuration.TemplateCommand.Name), "*", SearchOption.AllDirectories))); var isOverridingBuiltIn = configuration.TemplateCommand.Name == _builtInTemplateOverrideName; var isDefault = string.IsNullOrWhiteSpace(configuration.DefaultTemplateName) ? isOverridingBuiltIn : (configuration.DefaultTemplateName == configuration.TemplateCommand.Name); - var templateParams = " {0}".format_with(string.Join("{0} ".format_with(Environment.NewLine), get_template_parameters(configuration, templateInstalledViaPackage))); + var templateParams = " {0}".FormatWith(string.Join("{0} ".FormatWith(Environment.NewLine), GetTemplateParameters(configuration, templateInstalledViaPackage))); if (configuration.RegularOutput) { @@ -311,49 +307,49 @@ protected void list_custom_template_info(ChocolateyConfiguration configuration) {7} List of Parameters: {8} -".format_with(configuration.TemplateCommand.Name, +".FormatWith(configuration.TemplateCommand.Name, pkgVersion, isDefault, - isOverridingBuiltIn ? "This template is overriding the built in template{0}".format_with(Environment.NewLine) : string.Empty, + isOverridingBuiltIn ? "This template is overriding the built in template{0}".FormatWith(Environment.NewLine) : string.Empty, pkgTitle, - string.IsNullOrEmpty(pkgSummary) ? "Template not installed as a package" : "Summary: {0}".format_with(pkgSummary), - string.IsNullOrEmpty(pkgDescription) ? string.Empty : "{0}Description:{0} {1}".format_with(Environment.NewLine, pkgDescription), + string.IsNullOrEmpty(pkgSummary) ? "Template not installed as a package" : "Summary: {0}".FormatWith(pkgSummary), + string.IsNullOrEmpty(pkgDescription) ? string.Empty : "{0}Description:{0} {1}".FormatWith(Environment.NewLine, pkgDescription), pkgFiles, templateParams)); } else { - this.Log().Info("{0} {1} {2}".format_with((isDefault ? '*' : ' '), configuration.TemplateCommand.Name, pkgVersion)); + this.Log().Info("{0} {1} {2}".FormatWith((isDefault ? '*' : ' '), configuration.TemplateCommand.Name, pkgVersion)); } } else { - this.Log().Info("{0}|{1}".format_with(configuration.TemplateCommand.Name, pkgVersion)); + this.Log().Info("{0}|{1}".FormatWith(configuration.TemplateCommand.Name, pkgVersion)); } } - protected void list_built_in_template_info(ChocolateyConfiguration configuration, bool isOverridden, bool isDefault) + protected void ListBuiltinTemplateInformation(ChocolateyConfiguration configuration, bool isOverridden, bool isDefault) { if (configuration.RegularOutput) { if (isOverridden) { - this.Log().Info("Built-in template overridden by 'default' template.{0}".format_with(Environment.NewLine)); + this.Log().Info("Built-in template overridden by 'default' template.{0}".FormatWith(Environment.NewLine)); } else { if (isDefault) { - this.Log().Info("Built-in template is default.{0}".format_with(Environment.NewLine)); + this.Log().Info("Built-in template is default.{0}".FormatWith(Environment.NewLine)); } else { - this.Log().Info("Built-in template is not default, it can be specified if the --built-in parameter is used{0}".format_with(Environment.NewLine)); + this.Log().Info("Built-in template is not default, it can be specified if the --built-in parameter is used{0}".FormatWith(Environment.NewLine)); } } if (configuration.Verbose) { - this.Log().Info("Help about the built-in template can be found with 'choco new --help'{0}".format_with(Environment.NewLine)); + this.Log().Info("Help about the built-in template can be found with 'choco new --help'{0}".FormatWith(Environment.NewLine)); } } else @@ -366,50 +362,88 @@ protected void list_built_in_template_info(ChocolateyConfiguration configuration } } - protected IEnumerable get_template_parameters(ChocolateyConfiguration configuration, bool templateInstalledViaPackage) + protected IEnumerable GetTemplateParameters(ChocolateyConfiguration configuration, bool templateInstalledViaPackage) { // If the template was installed via package, the cache file gets removed on upgrade, so the cache file would be up to date if it exists if (templateInstalledViaPackage) { - var templateDirectory = _fileSystem.combine_paths(ApplicationParameters.TemplatesLocation, configuration.TemplateCommand.Name); - var cacheFilePath = _fileSystem.combine_paths(templateDirectory, _templateParameterCacheFilename); + var templateDirectory = _fileSystem.CombinePaths(ApplicationParameters.TemplatesLocation, configuration.TemplateCommand.Name); + var cacheFilePath = _fileSystem.CombinePaths(templateDirectory, _templateParameterCacheFilename); - if (!_fileSystem.file_exists(cacheFilePath)) + if (!_fileSystem.FileExists(cacheFilePath)) { - _xmlService.serialize(get_template_parameters_from_files(configuration).ToList(), cacheFilePath); + _xmlService.Serialize(GetTemplateParametersFromFiles(configuration).ToList(), cacheFilePath); } - return _xmlService.deserialize>(cacheFilePath); + return _xmlService.Deserialize>(cacheFilePath); } // If the template is not installed via a package, always read the parameters directly as the template may have been updated manually - return get_template_parameters_from_files(configuration).ToList(); + return GetTemplateParametersFromFiles(configuration).ToList(); } - protected HashSet get_template_parameters_from_files(ChocolateyConfiguration configuration) + protected HashSet GetTemplateParametersFromFiles(ChocolateyConfiguration configuration) { - var filesList = _fileSystem.get_files(_fileSystem.combine_paths(ApplicationParameters.TemplatesLocation, configuration.TemplateCommand.Name), "*", SearchOption.AllDirectories); + var filesList = _fileSystem.GetFiles(_fileSystem.CombinePaths(ApplicationParameters.TemplatesLocation, configuration.TemplateCommand.Name), "*", SearchOption.AllDirectories); var parametersList = new HashSet(); foreach (var filePath in filesList) { - if (_templateBinaryExtensions.Contains(_fileSystem.get_file_extension(filePath))) + if (_templateBinaryExtensions.Contains(_fileSystem.GetFileExtension(filePath))) { - this.Log().Debug("{0} is a binary file, not reading parameters".format_with(filePath)); + this.Log().Debug("{0} is a binary file, not reading parameters".FormatWith(filePath)); continue; } - if (_fileSystem.get_file_name(filePath) == _templateParameterCacheFilename) + if (_fileSystem.GetFileName(filePath) == _templateParameterCacheFilename) { - this.Log().Debug("{0} is the parameter cache file, not reading parameters".format_with(filePath)); + this.Log().Debug("{0} is the parameter cache file, not reading parameters".FormatWith(filePath)); continue; } - var fileContents = _fileSystem.read_file(filePath); - parametersList.UnionWith(TokenReplacer.get_tokens(fileContents, "[[", "]]")); + var fileContents = _fileSystem.ReadFile(filePath); + parametersList.UnionWith(TokenReplacer.GetTokens(fileContents, "[[", "]]")); } return parametersList; } + +#pragma warning disable IDE1006 + [Obsolete("This overload is deprecated and will be removed in v3.")] + public void generate_noop(ChocolateyConfiguration configuration) + => GenerateDryRun(configuration); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public void generate(ChocolateyConfiguration configuration) + => Generate(configuration); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public void generate_file_from_template(ChocolateyConfiguration configuration, TemplateValues tokens, string template, string fileLocation, Encoding encoding) + => GenerateFileFromTemplate(configuration, tokens, template, fileLocation, encoding); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public void list_noop(ChocolateyConfiguration configuration) + => ListDryRun(configuration); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public void list(ChocolateyConfiguration configuration) + => List(configuration); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + protected void list_custom_template_info(ChocolateyConfiguration configuration) + => ListCustomTemplateInformation(configuration); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + protected void list_built_in_template_info(ChocolateyConfiguration configuration, bool isOverridden, bool isDefault) + => ListBuiltinTemplateInformation(configuration, isOverridden, isDefault); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + protected IEnumerable get_template_parameters(ChocolateyConfiguration configuration, bool templateInstalledViaPackage) + => GetTemplateParameters(configuration, templateInstalledViaPackage); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + protected HashSet get_template_parameters_from_files(ChocolateyConfiguration configuration) + => GetTemplateParametersFromFiles(configuration); +#pragma warning restore IDE1006 } } diff --git a/src/chocolatey/infrastructure.app/services/WindowsFeatureService.cs b/src/chocolatey/infrastructure.app/services/WindowsFeatureService.cs index 2700e757fa..3c44a8d8d2 100644 --- a/src/chocolatey/infrastructure.app/services/WindowsFeatureService.cs +++ b/src/chocolatey/infrastructure.app/services/WindowsFeatureService.cs @@ -37,19 +37,22 @@ namespace chocolatey.infrastructure.app.services /// Win 7 - https://technet.microsoft.com/en-us/library/dd744311.aspx /// Maybe Win2003/2008 - http://www.wincert.net/forum/files/file/8-deployment-image-servicing-and-management-dism/ | http://wincert.net/leli55PK/DISM/ /// - public sealed class WindowsFeatureService : ISourceRunner + public sealed class WindowsFeatureService : IBootstrappableSourceRunner, IListSourceRunner, ISearchableSourceRunner, IInstallSourceRunner, IUninstallSourceRunner { private readonly ICommandExecutor _commandExecutor; private readonly INugetService _nugetService; private readonly IFileSystem _fileSystem; - private const string ALL_TOKEN = "{{all}}"; - private const string PACKAGE_NAME_TOKEN = "{{packagename}}"; - private const string LOG_LEVEL_TOKEN = "{{loglevel}}"; - private const string LOG_LEVEL_INFO = "3"; - private const string LOG_LEVEL_DEBUG = "4"; - private const string FEATURES_VALUE = "/Get-Features"; - private const string FORMAT_VALUE = "/Format:Table"; + private const string AllToken = "{{all}}"; + private const string PackageNameToken = "{{packagename}}"; + private const string LogLevelToken = "{{loglevel}}"; + private const string LogLevelInfo = "3"; + private const string LogLevelDebug = "4"; + private const string FeaturesValue = "/Get-Features"; + private const string FormatValue = "/Format:Table"; private string _exePath = string.Empty; + private const string AppName = "Windows Features"; + + private const string PackageNameGroup = "PkgName"; private static readonly IList _exeLocations = new List { @@ -58,11 +61,9 @@ public sealed class WindowsFeatureService : ISourceRunner "dism.exe" }; - private const string APP_NAME = "Windows Features"; - public const string PACKAGE_NAME_GROUP = "PkgName"; - public static readonly Regex InstalledRegex = new Regex(@"The operation completed successfully.", RegexOptions.Compiled); - public static readonly Regex ErrorRegex = new Regex(@"Error:", RegexOptions.Compiled); - public static readonly Regex ErrorNotFoundRegex = new Regex(@"Feature name .* is unknown", RegexOptions.Compiled); + private static readonly Regex _installedRegex = new Regex(@"The operation completed successfully.", RegexOptions.Compiled); + private static readonly Regex _errorRegex = new Regex(@"Error:", RegexOptions.Compiled); + private static readonly Regex _errorNotFoundRegex = new Regex(@"Feature name .* is unknown", RegexOptions.Compiled); private readonly IDictionary _listArguments = new Dictionary(StringComparer.InvariantCultureIgnoreCase); private readonly IDictionary _installArguments = new Dictionary(StringComparer.InvariantCultureIgnoreCase); @@ -73,54 +74,54 @@ public WindowsFeatureService(ICommandExecutor commandExecutor, INugetService nug _commandExecutor = commandExecutor; _nugetService = nugetService; _fileSystem = fileSystem; - set_cmd_args_dictionaries(); + SetupCommandArgsDictionaries(); } /// /// Set any command arguments dictionaries necessary for the service /// - private void set_cmd_args_dictionaries() + private void SetupCommandArgsDictionaries() { - set_list_dictionary(_listArguments); - set_install_dictionary(_installArguments); - set_uninstall_dictionary(_uninstallArguments); + SetupListDictionary(_listArguments); + SetupInstallDictionary(_installArguments); + SetupUninstallDictionary(_uninstallArguments); } /// /// Sets list dictionary /// - private void set_list_dictionary(IDictionary args) + private void SetupListDictionary(IDictionary args) { - set_common_args(args); - args.Add("_features_", new ExternalCommandArgument { ArgumentOption = FEATURES_VALUE, Required = true }); - args.Add("_format_", new ExternalCommandArgument { ArgumentOption = FORMAT_VALUE, Required = true }); + AddCommonArguments(args); + args.Add("_features_", new ExternalCommandArgument { ArgumentOption = FeaturesValue, Required = true }); + args.Add("_format_", new ExternalCommandArgument { ArgumentOption = FormatValue, Required = true }); } /// /// Sets install dictionary /// - private void set_install_dictionary(IDictionary args) + private void SetupInstallDictionary(IDictionary args) { - set_common_args(args); + AddCommonArguments(args); args.Add("_feature_", new ExternalCommandArgument { ArgumentOption = "/Enable-Feature", Required = true }); args.Add("_package_name_", new ExternalCommandArgument { ArgumentOption = "/FeatureName:", - ArgumentValue = PACKAGE_NAME_TOKEN, + ArgumentValue = PackageNameToken, QuoteValue = false, Required = true }); // /All should be the final argument. - args.Add("_all_", new ExternalCommandArgument { ArgumentOption = ALL_TOKEN, Required = true }); + args.Add("_all_", new ExternalCommandArgument { ArgumentOption = AllToken, Required = true }); } /// /// Sets uninstall dictionary /// - private void set_uninstall_dictionary(IDictionary args) + private void SetupUninstallDictionary(IDictionary args) { - set_common_args(args); + AddCommonArguments(args); // uninstall feature completely in 8/2012+ - /Remove // would need /source to bring it back @@ -129,20 +130,20 @@ private void set_uninstall_dictionary(IDictionary args) + private void AddCommonArguments(IDictionary args) { args.Add("_online_", new ExternalCommandArgument { ArgumentOption = "/Online", Required = true }); args.Add("_english_", new ExternalCommandArgument { ArgumentOption = "/English", Required = true }); args.Add("_loglevel_", new ExternalCommandArgument { ArgumentOption = "/LogLevel=", - ArgumentValue = LOG_LEVEL_TOKEN, + ArgumentValue = LogLevelToken, QuoteValue = false, Required = true }); @@ -152,72 +153,67 @@ private void set_common_args(IDictionary args) public string SourceType { - get { return SourceTypes.WINDOWS_FEATURES; } + get { return SourceTypes.WindowsFeatures; } } - public void ensure_source_app_installed(ChocolateyConfiguration config, Action ensureAction) + public void EnsureSourceAppInstalled(ChocolateyConfiguration config, Action ensureAction) { - if (Platform.get_platform() != PlatformType.Windows) throw new NotImplementedException("This source is not supported on non-Windows systems"); - - set_executable_path_if_not_set(); - } + if (Platform.GetPlatform() != PlatformType.Windows) throw new NotImplementedException("This source is not supported on non-Windows systems"); - public int count_run(ChocolateyConfiguration config) - { - throw new NotImplementedException("Count is not supported for this source runner."); + EnsureExecutablePathSet(); } - public void set_executable_path_if_not_set() + private void EnsureExecutablePathSet() { if (!string.IsNullOrWhiteSpace(_exePath)) return; foreach (var location in _exeLocations) { - if (_fileSystem.file_exists(location)) + if (_fileSystem.FileExists(location)) { _exePath = location; break; } } - if (string.IsNullOrWhiteSpace(_exePath)) throw new FileNotFoundException("Unable to find suitable location for the executable. Searched the following locations: '{0}'".format_with(string.Join("; ", _exeLocations))); + if (string.IsNullOrWhiteSpace(_exePath)) throw new FileNotFoundException("Unable to find suitable location for the executable. Searched the following locations: '{0}'".FormatWith(string.Join("; ", _exeLocations))); } - public void list_noop(ChocolateyConfiguration config) + public void ListDryRun(ChocolateyConfiguration config) { - set_executable_path_if_not_set(); - var args = build_args(config, _listArguments); - this.Log().Info("Would have run '{0} {1}'".format_with(_exePath.escape_curly_braces(), args.escape_curly_braces())); + EnsureExecutablePathSet(); + var args = BuildArguments(config, _listArguments); + this.Log().Info("Would have run '{0} {1}'".FormatWith(_exePath.EscapeCurlyBraces(), args.EscapeCurlyBraces())); } - public IEnumerable list_run(ChocolateyConfiguration config) + public IEnumerable List(ChocolateyConfiguration config) { - set_executable_path_if_not_set(); - var args = build_args(config, _listArguments); + EnsureExecutablePathSet(); + var args = BuildArguments(config, _listArguments); var packageResults = new List(); - Environment.ExitCode = _commandExecutor.execute( + Environment.ExitCode = _commandExecutor.Execute( _exePath, args, config.CommandExecutionTimeoutSeconds, - _fileSystem.get_current_directory(), + _fileSystem.GetCurrentDirectory(), stdOutAction: (s, e) => { var logMessage = e.Data; if (string.IsNullOrWhiteSpace(logMessage)) return; if (!config.QuietOutput) { - this.Log().Info(logMessage.escape_curly_braces()); + this.Log().Info(logMessage.EscapeCurlyBraces()); } else { - this.Log().Debug(() => "[{0}] {1}".format_with(APP_NAME, logMessage.escape_curly_braces())); + this.Log().Debug(() => "[{0}] {1}".FormatWith(AppName, logMessage.EscapeCurlyBraces())); } }, stdErrAction: (s, e) => { if (string.IsNullOrWhiteSpace(e.Data)) return; - this.Log().Error(() => "{0}".format_with(e.Data.escape_curly_braces())); + this.Log().Error(() => "{0}".FormatWith(e.Data.EscapeCurlyBraces())); }, updateProcessPath: false, allowUseWindow: true @@ -226,53 +222,63 @@ public IEnumerable list_run(ChocolateyConfiguration config) return packageResults; } - public string build_args(ChocolateyConfiguration config, IDictionary argsDictionary) + public void SearchDryRun(ChocolateyConfiguration config) { - var args = ExternalCommandArgsBuilder.build_arguments(config, argsDictionary); + ListDryRun(config); + } + + public IEnumerable Search(ChocolateyConfiguration config) + { + return List(config); + } + + private string BuildArguments(ChocolateyConfiguration config, IDictionary argsDictionary) + { + var args = ExternalCommandArgsBuilder.BuildArguments(config, argsDictionary); // at least Windows 8/2012 if (config.Information.PlatformVersion.Major > 6 || (config.Information.PlatformVersion.Major == 6 && config.Information.PlatformVersion.Minor >= 2)) { - args = args.Replace(ALL_TOKEN, "/All"); + args = args.Replace(AllToken, "/All"); } else { - args = args.Replace(ALL_TOKEN, string.Empty); + args = args.Replace(AllToken, string.Empty); } if (!string.IsNullOrWhiteSpace(config.Input)) { - args = args.Replace(FEATURES_VALUE, "/Get-FeatureInfo").Replace(FORMAT_VALUE, "/FeatureName:{0}".format_with(config.Input)); + args = args.Replace(FeaturesValue, "/Get-FeatureInfo").Replace(FormatValue, "/FeatureName:{0}".FormatWith(config.Input)); } - args = args.Replace(LOG_LEVEL_TOKEN, config.Debug ? LOG_LEVEL_DEBUG : LOG_LEVEL_INFO); + args = args.Replace(LogLevelToken, config.Debug ? LogLevelDebug : LogLevelInfo); return args; } - public void install_noop(ChocolateyConfiguration config, Action continueAction) + public void InstallDryRun(ChocolateyConfiguration config, Action continueAction) { - set_executable_path_if_not_set(); - var args = build_args(config, _installArguments); - this.Log().Info("Would have run '{0} {1}'".format_with(_exePath.escape_curly_braces(), args.escape_curly_braces())); + EnsureExecutablePathSet(); + var args = BuildArguments(config, _installArguments); + this.Log().Info("Would have run '{0} {1}'".FormatWith(_exePath.EscapeCurlyBraces(), args.EscapeCurlyBraces())); } - public ConcurrentDictionary install_run(ChocolateyConfiguration config, Action continueAction) + public ConcurrentDictionary Install(ChocolateyConfiguration config, Action continueAction) { - return install_run(config, continueAction, beforeModifyAction: null); + return Install(config, continueAction, beforeModifyAction: null); } - public ConcurrentDictionary install_run(ChocolateyConfiguration config, Action continueAction, Action beforeModifyAction) + public ConcurrentDictionary Install(ChocolateyConfiguration config, Action continueAction, Action beforeModifyAction) { - set_executable_path_if_not_set(); - var args = build_args(config, _installArguments); + EnsureExecutablePathSet(); + var args = BuildArguments(config, _installArguments); var packageResults = new ConcurrentDictionary(StringComparer.InvariantCultureIgnoreCase); foreach (var packageToInstall in config.PackageNames.Split(new[] { ApplicationParameters.PackageNamesSeparator }, StringSplitOptions.RemoveEmptyEntries)) { var packageName = packageToInstall; var results = packageResults.GetOrAdd(packageToInstall, new PackageResult(packageName, null, null)); - var argsForPackage = args.Replace(PACKAGE_NAME_TOKEN, packageName); + var argsForPackage = args.Replace(PackageNameToken, packageName); //todo: #2574 detect windows feature is already enabled /* @@ -283,33 +289,33 @@ public ConcurrentDictionary install_run(ChocolateyConfigu "@ */ - var exitCode = _commandExecutor.execute( + var exitCode = _commandExecutor.Execute( _exePath, argsForPackage, config.CommandExecutionTimeoutSeconds, - _fileSystem.get_current_directory(), + _fileSystem.GetCurrentDirectory(), (s, e) => { var logMessage = e.Data; if (string.IsNullOrWhiteSpace(logMessage)) return; - this.Log().Info(() => " [{0}] {1}".format_with(APP_NAME, logMessage.escape_curly_braces())); + this.Log().Info(() => " [{0}] {1}".FormatWith(AppName, logMessage.EscapeCurlyBraces())); - if (ErrorRegex.IsMatch(logMessage) || ErrorNotFoundRegex.IsMatch(logMessage)) + if (_errorRegex.IsMatch(logMessage) || _errorNotFoundRegex.IsMatch(logMessage)) { results.Messages.Add(new ResultMessage(ResultType.Error, packageName)); } - if (InstalledRegex.IsMatch(logMessage)) + if (_installedRegex.IsMatch(logMessage)) { results.Messages.Add(new ResultMessage(ResultType.Note, packageName)); - this.Log().Info(ChocolateyLoggers.Important, " {0} has been installed successfully.".format_with(string.IsNullOrWhiteSpace(packageName) ? packageToInstall : packageName)); + this.Log().Info(ChocolateyLoggers.Important, " {0} has been installed successfully.".FormatWith(string.IsNullOrWhiteSpace(packageName) ? packageToInstall : packageName)); } }, (s, e) => { var logMessage = e.Data; if (string.IsNullOrWhiteSpace(logMessage)) return; - this.Log().Error("[{0}] {1}".format_with(APP_NAME, logMessage.escape_curly_braces())); + this.Log().Error("[{0}] {1}".FormatWith(AppName, logMessage.EscapeCurlyBraces())); results.Messages.Add(new ResultMessage(ResultType.Error, logMessage)); }, @@ -326,37 +332,24 @@ public ConcurrentDictionary install_run(ChocolateyConfigu return packageResults; } - public ConcurrentDictionary upgrade_noop(ChocolateyConfiguration config, Action continueAction) - { - set_executable_path_if_not_set(); - this.Log().Warn(ChocolateyLoggers.Important, "{0} does not implement upgrade".format_with(APP_NAME)); - return new ConcurrentDictionary(StringComparer.InvariantCultureIgnoreCase); - } - - public ConcurrentDictionary upgrade_run(ChocolateyConfiguration config, Action continueAction, Action beforeUpgradeAction = null) - { - set_executable_path_if_not_set(); - throw new NotImplementedException("{0} does not implement upgrade".format_with(APP_NAME)); - } - - public void uninstall_noop(ChocolateyConfiguration config, Action continueAction) + public void UninstallDryRun(ChocolateyConfiguration config, Action continueAction) { - set_executable_path_if_not_set(); - var args = build_args(config, _uninstallArguments); - this.Log().Info("Would have run '{0} {1}'".format_with(_exePath.escape_curly_braces(), args.escape_curly_braces())); + EnsureExecutablePathSet(); + var args = BuildArguments(config, _uninstallArguments); + this.Log().Info("Would have run '{0} {1}'".FormatWith(_exePath.EscapeCurlyBraces(), args.EscapeCurlyBraces())); } - public ConcurrentDictionary uninstall_run(ChocolateyConfiguration config, Action continueAction, Action beforeUninstallAction = null) + public ConcurrentDictionary Uninstall(ChocolateyConfiguration config, Action continueAction, Action beforeUninstallAction = null) { - set_executable_path_if_not_set(); - var args = build_args(config, _uninstallArguments); + EnsureExecutablePathSet(); + var args = BuildArguments(config, _uninstallArguments); var packageResults = new ConcurrentDictionary(StringComparer.InvariantCultureIgnoreCase); foreach (var packageToInstall in config.PackageNames.Split(new[] { ApplicationParameters.PackageNamesSeparator }, StringSplitOptions.RemoveEmptyEntries)) { var packageName = packageToInstall; var results = packageResults.GetOrAdd(packageToInstall, new PackageResult(packageName, null, null)); - var argsForPackage = args.Replace(PACKAGE_NAME_TOKEN, packageName); + var argsForPackage = args.Replace(PackageNameToken, packageName); //todo: #2574 detect windows feature is already disabled /* @@ -367,33 +360,33 @@ public ConcurrentDictionary uninstall_run(ChocolateyConfi "@ */ - var exitCode = _commandExecutor.execute( + var exitCode = _commandExecutor.Execute( _exePath, argsForPackage, config.CommandExecutionTimeoutSeconds, - _fileSystem.get_current_directory(), + _fileSystem.GetCurrentDirectory(), (s, e) => { var logMessage = e.Data; if (string.IsNullOrWhiteSpace(logMessage)) return; - this.Log().Info(() => " [{0}] {1}".format_with(APP_NAME, logMessage.escape_curly_braces())); + this.Log().Info(() => " [{0}] {1}".FormatWith(AppName, logMessage.EscapeCurlyBraces())); - if (ErrorRegex.IsMatch(logMessage) || ErrorNotFoundRegex.IsMatch(logMessage)) + if (_errorRegex.IsMatch(logMessage) || _errorNotFoundRegex.IsMatch(logMessage)) { results.Messages.Add(new ResultMessage(ResultType.Error, packageName)); } - if (InstalledRegex.IsMatch(logMessage)) + if (_installedRegex.IsMatch(logMessage)) { results.Messages.Add(new ResultMessage(ResultType.Note, packageName)); - this.Log().Info(ChocolateyLoggers.Important, " {0} has been uninstalled successfully.".format_with(string.IsNullOrWhiteSpace(packageName) ? packageToInstall : packageName)); + this.Log().Info(ChocolateyLoggers.Important, " {0} has been uninstalled successfully.".FormatWith(string.IsNullOrWhiteSpace(packageName) ? packageToInstall : packageName)); } }, (s, e) => { var logMessage = e.Data; if (string.IsNullOrWhiteSpace(logMessage)) return; - this.Log().Error("[{0}] {1}".format_with(APP_NAME, logMessage.escape_curly_braces())); + this.Log().Error("[{0}] {1}".FormatWith(AppName, logMessage.EscapeCurlyBraces())); results.Messages.Add(new ResultMessage(ResultType.Error, logMessage)); }, @@ -409,5 +402,56 @@ public ConcurrentDictionary uninstall_run(ChocolateyConfi return packageResults; } + +#pragma warning disable IDE1006 + [Obsolete("This overload is deprecated and will be removed in v3.")] + public const string PACKAGE_NAME_GROUP = PackageNameGroup; + [Obsolete("This overload is deprecated and will be removed in v3.")] + public static readonly Regex InstalledRegex = _installedRegex; + [Obsolete("This overload is deprecated and will be removed in v3.")] + public static readonly Regex ErrorRegex = _errorRegex; + [Obsolete("This overload is deprecated and will be removed in v3.")] + public static readonly Regex ErrorNotFoundRegex = _errorNotFoundRegex; + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public void ensure_source_app_installed(ChocolateyConfiguration config, Action ensureAction) + => EnsureSourceAppInstalled(config, ensureAction); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public void set_executable_path_if_not_set() + => EnsureExecutablePathSet(); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public void list_noop(ChocolateyConfiguration config) + => ListDryRun(config); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public IEnumerable list_run(ChocolateyConfiguration config) + => List(config); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public string build_args(ChocolateyConfiguration config, IDictionary argsDictionary) + => BuildArguments(config, argsDictionary); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public void install_noop(ChocolateyConfiguration config, Action continueAction) + => InstallDryRun(config, continueAction); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public ConcurrentDictionary install_run(ChocolateyConfiguration config, Action continueAction) + => Install(config, continueAction); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public ConcurrentDictionary install_run(ChocolateyConfiguration config, Action continueAction, Action beforeModifyAction) + => Install(config, continueAction, beforeModifyAction); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public void uninstall_noop(ChocolateyConfiguration config, Action continueAction) + => UninstallDryRun(config, continueAction); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public ConcurrentDictionary uninstall_run(ChocolateyConfiguration config, Action continueAction, Action beforeUninstallAction = null) + => Uninstall(config, continueAction, beforeUninstallAction); +#pragma warning restore IDE1006 } } diff --git a/src/chocolatey/infrastructure.app/tasks/RemovePendingPackagesTask.cs b/src/chocolatey/infrastructure.app/tasks/RemovePendingPackagesTask.cs index 64b567f81c..9200b4c2e2 100644 --- a/src/chocolatey/infrastructure.app/tasks/RemovePendingPackagesTask.cs +++ b/src/chocolatey/infrastructure.app/tasks/RemovePendingPackagesTask.cs @@ -32,8 +32,8 @@ public class RemovePendingPackagesTask : ITask private readonly IFileSystem _fileSystem; private readonly IDateTimeService _dateTimeService; private IDisposable _subscription; - private const int PENDING_FILE_AGE_SECONDS = 10; - private const string PENDING_SKIP_FILE = ".chocolateyPendingSkip"; + private const int PendingFileAgeSeconds = 10; + private const string PendingSkipFile = ".chocolateyPendingSkip"; public RemovePendingPackagesTask(IFileSystem fileSystem) : this(fileSystem, new SystemDateTimeUtcService()) { @@ -45,59 +45,69 @@ public RemovePendingPackagesTask(IFileSystem fileSystem, IDateTimeService dateTi _dateTimeService = dateTimeService; } - public void initialize() + public void Initialize() { - _subscription = EventManager.subscribe(handle_message, null, null); - this.Log().Debug(ChocolateyLoggers.Verbose, () => "{0} is now ready and waiting for {1}.".format_with(GetType().Name, typeof(PreRunMessage).Name)); + _subscription = EventManager.Subscribe(HandleMessage, null, null); + this.Log().Debug(ChocolateyLoggers.Verbose, () => "{0} is now ready and waiting for {1}.".FormatWith(GetType().Name, typeof(PreRunMessage).Name)); } - public void shutdown() + public void Shutdown() { if (_subscription != null) _subscription.Dispose(); } - private void handle_message(PreRunMessage message) + private void HandleMessage(PreRunMessage message) { this.Log().Debug(ChocolateyLoggers.Verbose, "[Pending] Removing all pending packages that should not be considered installed..."); - var pendingFiles = _fileSystem.get_files(ApplicationParameters.PackagesLocation, ApplicationParameters.PackagePendingFileName).ToList(); - foreach (var pendingFile in pendingFiles.or_empty_list_if_null()) + var pendingFiles = _fileSystem.GetFiles(ApplicationParameters.PackagesLocation, ApplicationParameters.PackagePendingFileName).ToList(); + foreach (var pendingFile in pendingFiles.OrEmpty()) { - var packageFolder = _fileSystem.get_directory_name(pendingFile); - string packageFolderName = _fileSystem.get_directory_info_for(packageFolder).Name; + var packageFolder = _fileSystem.GetDirectoryName(pendingFile); + string packageFolderName = _fileSystem.GetDirectoryInfo(packageFolder).Name; - var pendingSkipFiles = _fileSystem.get_files(packageFolder, PENDING_SKIP_FILE).ToList(); + var pendingSkipFiles = _fileSystem.GetFiles(packageFolder, PendingSkipFile).ToList(); if (pendingSkipFiles.Count != 0) { - this.Log().Warn("Pending file found for {0}, but a {1} file was also found. Skipping removal".format_with(packageFolderName, PENDING_SKIP_FILE)); + this.Log().Warn("Pending file found for {0}, but a {1} file was also found. Skipping removal".FormatWith(packageFolderName, PendingSkipFile)); continue; } try { //attempt to open the pending file. If it is locked, continue - var file = _fileSystem.open_file_exclusive(pendingFile); + var file = _fileSystem.OpenFileExclusive(pendingFile); file.Close(); file.Dispose(); } catch (Exception) { - this.Log().Debug("Pending file found for {0}, but the file is locked by another process.".format_with(packageFolderName)); + this.Log().Debug("Pending file found for {0}, but the file is locked by another process.".FormatWith(packageFolderName)); continue; } // wait for the file to be at least x seconds old // this allows commands running from the package for configuring sources, etc - var fileInfo = _fileSystem.get_file_info_for(pendingFile); - if (fileInfo.CreationTimeUtc.AddSeconds(PENDING_FILE_AGE_SECONDS) > _dateTimeService.get_current_date_time()) + var fileInfo = _fileSystem.GetFileInfoFor(pendingFile); + if (fileInfo.CreationTimeUtc.AddSeconds(PendingFileAgeSeconds) > _dateTimeService.GetCurrentDateTime()) { - this.Log().Debug("Pending file found for {0}, but the file is not {1} seconds old yet.".format_with(packageFolderName, PENDING_FILE_AGE_SECONDS)); + this.Log().Debug("Pending file found for {0}, but the file is not {1} seconds old yet.".FormatWith(packageFolderName, PendingFileAgeSeconds)); continue; } - this.Log().Warn("[Pending] Removing incomplete install for '{0}'".format_with(packageFolderName)); - FaultTolerance.retry(2, () => _fileSystem.delete_directory_if_exists(packageFolder, recursive: true, overrideAttributes: true, isSilent: true), 500, isSilent: true); + this.Log().Warn("[Pending] Removing incomplete install for '{0}'".FormatWith(packageFolderName)); + FaultTolerance.Retry(2, () => _fileSystem.DeleteDirectoryChecked(packageFolder, recursive: true, overrideAttributes: true, isSilent: true), 500, isSilent: true); } } + +#pragma warning disable IDE1006 + [Obsolete("This overload is deprecated and will be removed in v3.")] + public void initialize() + => Initialize(); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public void shutdown() + => Shutdown(); +#pragma warning restore IDE1006 } } diff --git a/src/chocolatey/infrastructure.app/templates/ChocolateyBeforeModifyTemplate.cs b/src/chocolatey/infrastructure.app/templates/ChocolateyBeforeModifyTemplate.cs index 2e67e089a5..afffc99af2 100644 --- a/src/chocolatey/infrastructure.app/templates/ChocolateyBeforeModifyTemplate.cs +++ b/src/chocolatey/infrastructure.app/templates/ChocolateyBeforeModifyTemplate.cs @@ -19,7 +19,7 @@ namespace chocolatey.infrastructure.app.templates public class ChocolateyBeforeModifyTemplate { public static string Template = - @"# This runs in 0.9.10+ before upgrade and uninstall. + @"# This runs before upgrade or uninstall. # Use this file to do things like stop services prior to upgrade or uninstall. # NOTE: It is an anti-pattern to call chocolateyUninstall.ps1 from here. If you # need to uninstall an MSI prior to upgrade, put the functionality in this diff --git a/src/chocolatey/infrastructure.app/templates/ChocolateyInstallTemplate.cs b/src/chocolatey/infrastructure.app/templates/ChocolateyInstallTemplate.cs index 5989bdffe5..e945fa2a1e 100644 --- a/src/chocolatey/infrastructure.app/templates/ChocolateyInstallTemplate.cs +++ b/src/chocolatey/infrastructure.app/templates/ChocolateyInstallTemplate.cs @@ -49,7 +49,7 @@ public class ChocolateyInstallTemplate softwareName = '[[PackageName]]*' #part or all of the Display Name as you see it in Programs and Features. It should be enough to be unique - # Checksums are now required as of 0.10.0. + # Checksums are required for packages which will be hosted on the Chocolatey Community Repository. # To determine checksums, you can get that from the original site if provided. # You can also use checksum.exe (choco install checksum) and use it # e.g. checksum -t sha256 -f path\to\file diff --git a/src/chocolatey/infrastructure.app/templates/ChocolateyReadMeTemplate.cs b/src/chocolatey/infrastructure.app/templates/ChocolateyReadMeTemplate.cs index 00e3baa48b..7dac594a22 100644 --- a/src/chocolatey/infrastructure.app/templates/ChocolateyReadMeTemplate.cs +++ b/src/chocolatey/infrastructure.app/templates/ChocolateyReadMeTemplate.cs @@ -82,75 +82,75 @@ Chocolatey makes a number of environment variables available (You can access any * TEMP/TMP - Overridden to the CacheLocation, but may be the same as the original TEMP folder * ChocolateyInstall - Top level folder where Chocolatey is installed - * ChocolateyPackageName - The name of the package, equivalent to the `` field in the nuspec (0.9.9+) - * ChocolateyPackageTitle - The title of the package, equivalent to the `` field in the nuspec (0.10.1+) - * ChocolateyPackageVersion - The version of the package, equivalent to the `<version />` field in the nuspec (0.9.9+) + * ChocolateyPackageName - The name of the package, equivalent to the `<id />` field in the nuspec + * ChocolateyPackageTitle - The title of the package, equivalent to the `<title />` field in the nuspec + * ChocolateyPackageVersion - The version of the package, equivalent to the `<version />` field in the nuspec * ChocolateyPackageFolder - The top level location of the package folder - the folder where Chocolatey has downloaded and extracted the NuGet package, typically `C:\ProgramData\chocolatey\lib\packageName`. #### Advanced Environment Variables The following are more advanced settings: - * ChocolateyPackageParameters - Parameters to use with packaging, not the same as install arguments (which are passed directly to the native installer). Based on `--package-parameters`. (0.9.8.22+) - * CHOCOLATEY_VERSION - The version of Choco you normally see. Use if you are 'lighting' things up based on choco version. (0.9.9+) - Otherwise take a dependency on the specific version you need. - * ChocolateyForceX86 = If available and set to 'true', then user has requested 32bit version. (0.9.9+) - Automatically handled in built in Choco functions. - * OS_PLATFORM - Like Windows, macOS, Linux. (0.9.9+) - * OS_VERSION - The version of OS, like 6.1 something something for Windows. (0.9.9+) - * OS_NAME - The reported name of the OS. (0.9.9+) - * USER_NAME = The user name (0.10.6+) - * USER_DOMAIN = The user domain name (could also be local computer name) (0.10.6+) - * IS_PROCESSELEVATED = Is the process elevated? (0.9.9+) - * IS_SYSTEM = Is the user the system account? (0.10.6+) - * IS_REMOTEDESKTOP = Is the user in a terminal services session? (0.10.6+) - * ChocolateyToolsLocation - formerly 'ChocolateyBinRoot' ('ChocolateyBinRoot' will be removed with Chocolatey v2.0.0), this is where tools being installed outside of Chocolatey packaging will go. (0.9.10+) + * ChocolateyPackageParameters - Parameters to use with packaging, not the same as install arguments (which are passed directly to the native installer). Based on `--package-parameters`. + * CHOCOLATEY_VERSION - The version of Choco you normally see. Use if you are 'lighting' things up based on choco version. Otherwise take a dependency on the specific version you need. + * ChocolateyForceX86 = If available and set to 'true', then user has requested 32bit version. Automatically handled in built in Choco functions. + * OS_PLATFORM - Like Windows, macOS, Linux. + * OS_VERSION - The version of OS, like 10.0 something something for Windows. + * OS_NAME - The reported name of the OS. + * USER_NAME = The user name + * USER_DOMAIN = The user domain name (could also be local computer name) + * IS_PROCESSELEVATED = Is the process elevated? + * IS_SYSTEM = Is the user the system account? + * IS_REMOTEDESKTOP = Is the user in a terminal services session? + * ChocolateyToolsLocation - formerly 'ChocolateyBinRoot' ('ChocolateyBinRoot' will be removed with Chocolatey v2.0.0), this is where tools being installed outside of Chocolatey packaging will go. #### Set By Options and Configuration Some environment variables are set based on options that are passed, configuration and/or features that are turned on: - * ChocolateyEnvironmentDebug - Was `--debug` passed? If using the built-in PowerShell host, this is always true (but only logs debug messages to console if `--debug` was passed) (0.9.10+) - * ChocolateyEnvironmentVerbose - Was `--verbose` passed? If using the built-in PowerShell host, this is always true (but only logs verbose messages to console if `--verbose` was passed). (0.9.10+) - * ChocolateyExitOnRebootDetected - Are we exiting on a detected reboot? Set by ` --exit-when-reboot-detected` or the feature `exitOnRebootDetected` (0.11.0+) - * ChocolateyForce - Was `--force` passed? (0.9.10+) - * ChocolateyForceX86 - Was `-x86` passed? (CHECK) - * ChocolateyRequestTimeout - How long before a web request will time out. Set by config `webRequestTimeoutSeconds` (CHECK) - * ChocolateyResponseTimeout - How long to wait for a download to complete? Set by config `commandExecutionTimeoutSeconds` (CHECK) - * ChocolateyPowerShellHost - Are we using the built-in PowerShell host? Set by `--use-system-powershell` or the feature `powershellHost` (0.9.10+) + * ChocolateyEnvironmentDebug - Was `--debug` passed? If using the built-in PowerShell host, this is always true (but only logs debug messages to console if `--debug` was passed) + * ChocolateyEnvironmentVerbose - Was `--verbose` passed? If using the built-in PowerShell host, this is always true (but only logs verbose messages to console if `--verbose` was passed). + * ChocolateyExitOnRebootDetected - Are we exiting on a detected reboot? Set by ` --exit-when-reboot-detected` or the feature `exitOnRebootDetected` + * ChocolateyForce - Was `--force` passed? + * ChocolateyForceX86 - Was `-x86` passed? + * ChocolateyRequestTimeout - How long before a web request will time out. Set by config `webRequestTimeoutSeconds` + * ChocolateyResponseTimeout - How long to wait for a download to complete? Set by config `commandExecutionTimeoutSeconds` + * ChocolateyPowerShellHost - Are we using the built-in PowerShell host? Set by `--use-system-powershell` or the feature `powershellHost` #### Business Edition Variables - * ChocolateyInstallArgumentsSensitive - Encrypted arguments passed from command line `--install-arguments-sensitive` that are not logged anywhere. (0.10.1+ and licensed editions 1.6.0+) - * ChocolateyPackageParametersSensitive - Package parameters passed from command line `--package-parameters-sensitive` that are not logged anywhere. (0.10.1+ and licensed editions 1.6.0+) + * ChocolateyInstallArgumentsSensitive - Encrypted arguments passed from command line `--install-arguments-sensitive` that are not logged anywhere. + * ChocolateyPackageParametersSensitive - Package parameters passed from command line `--package-parameters-sensitive` that are not logged anywhere. * ChocolateyLicensedVersion - What version is the licensed edition on? * ChocolateyLicenseType - What edition / type of the licensed edition is installed? - * USER_CONTEXT - The original user context - different when self-service is used (Licensed v1.10.0+) + * USER_CONTEXT - The original user context - different when self-service is used (Licensed) #### Experimental Environment Variables The following are experimental or use not recommended: - * OS_IS64BIT = This may not return correctly - it may depend on the process the app is running under (0.9.9+) - * CHOCOLATEY_VERSION_PRODUCT = the version of Choco that may match CHOCOLATEY_VERSION but may be different (0.9.9+) - based on git describe - * IS_ADMIN = Is the user an administrator? But doesn't tell you if the process is elevated. (0.9.9+) - * IS_REMOTE = Is the user in a remote session? (0.10.6+) + * OS_IS64BIT = This may not return correctly - it may depend on the process the app is running under + * CHOCOLATEY_VERSION_PRODUCT = the version of Choco that may match CHOCOLATEY_VERSION but may be different - based on git describe + * IS_ADMIN = Is the user an administrator? But doesn't tell you if the process is elevated. + * IS_REMOTE = Is the user in a remote session? #### Not Useful Or Anti-Pattern If Used - * ChocolateyInstallOverride = Not for use in package automation scripts. Based on `--override-arguments` being passed. (0.9.9+) - * ChocolateyInstallArguments = The installer arguments meant for the native installer. You should use chocolateyPackageParameters instead. Based on `--install-arguments` being passed. (0.9.9+) - * ChocolateyIgnoreChecksums - Was `--ignore-checksums` passed or the feature `checksumFiles` turned off? (0.9.9.9+) - * ChocolateyAllowEmptyChecksums - Was `--allow-empty-checksums` passed or the feature `allowEmptyChecksums` turned on? (0.10.0+) - * ChocolateyAllowEmptyChecksumsSecure - Was `--allow-empty-checksums-secure` passed or the feature `allowEmptyChecksumsSecure` turned on? (0.10.0+) - * ChocolateyChecksum32 - Was `--download-checksum` passed? (0.10.0+) - * ChocolateyChecksumType32 - Was `--download-checksum-type` passed? (0.10.0+) - * ChocolateyChecksum64 - Was `--download-checksum-x64` passed? (0.10.0)+ - * ChocolateyChecksumType64 - Was `--download-checksum-type-x64` passed? (0.10.0)+ - * ChocolateyPackageExitCode - The exit code of the script that just ran - usually set by `Set-PowerShellExitCode` (CHECK) + * ChocolateyInstallOverride = Not for use in package automation scripts. Based on `--override-arguments` being passed. + * ChocolateyInstallArguments = The installer arguments meant for the native installer. You should use chocolateyPackageParameters instead. Based on `--install-arguments` being passed. + * ChocolateyIgnoreChecksums - Was `--ignore-checksums` passed or the feature `checksumFiles` turned off? + * ChocolateyAllowEmptyChecksums - Was `--allow-empty-checksums` passed or the feature `allowEmptyChecksums` turned on? + * ChocolateyAllowEmptyChecksumsSecure - Was `--allow-empty-checksums-secure` passed or the feature `allowEmptyChecksumsSecure` turned on? + * ChocolateyChecksum32 - Was `--download-checksum` passed? + * ChocolateyChecksumType32 - Was `--download-checksum-type` passed? + * ChocolateyChecksum64 - Was `--download-checksum-x64` passed? + * ChocolateyChecksumType64 - Was `--download-checksum-type-x64` passed? + * ChocolateyPackageExitCode - The exit code of the script that just ran - usually set by `Set-PowerShellExitCode` * ChocolateyLastPathUpdate - Set by Chocolatey as part of install, but not used for anything in particular in packaging. - * ChocolateyProxyLocation - The explicit proxy location as set in the configuration `proxy` (0.9.9.9+) - * ChocolateyDownloadCache - Use available download cache? Set by `--skip-download-cache`, `--use-download-cache`, or feature `downloadCache` (0.9.10+ and licensed editions 1.1.0+) - * ChocolateyProxyBypassList - Explicitly set locations to ignore in configuration `proxyBypassList` (0.10.4+) - * ChocolateyProxyBypassOnLocal - Should the proxy bypass on local connections? Set based on configuration `proxyBypassOnLocal` (0.10.4+) - * http_proxy - Set by original `http_proxy` passthrough, or same as `ChocolateyProxyLocation` if explicitly set. (0.10.4+) - * https_proxy - Set by original `https_proxy` passthrough, or same as `ChocolateyProxyLocation` if explicitly set. (0.10.4+) - * no_proxy- Set by original `no_proxy` passthrough, or same as `ChocolateyProxyBypassList` if explicitly set. (0.10.4+) + * ChocolateyProxyLocation - The explicit proxy location as set in the configuration `proxy` + * ChocolateyDownloadCache - Use available download cache? Set by `--skip-download-cache`, `--use-download-cache`, or feature `downloadCache` + * ChocolateyProxyBypassList - Explicitly set locations to ignore in configuration `proxyBypassList` + * ChocolateyProxyBypassOnLocal - Should the proxy bypass on local connections? Set based on configuration `proxyBypassOnLocal` + * http_proxy - Set by original `http_proxy` passthrough, or same as `ChocolateyProxyLocation` if explicitly set. + * https_proxy - Set by original `https_proxy` passthrough, or same as `ChocolateyProxyLocation` if explicitly set. + * no_proxy- Set by original `no_proxy` passthrough, or same as `ChocolateyProxyBypassList` if explicitly set. "; } diff --git a/src/chocolatey/infrastructure.app/templates/ChocolateyUninstallTemplate.cs b/src/chocolatey/infrastructure.app/templates/ChocolateyUninstallTemplate.cs index 5057904ac8..777622739c 100644 --- a/src/chocolatey/infrastructure.app/templates/ChocolateyUninstallTemplate.cs +++ b/src/chocolatey/infrastructure.app/templates/ChocolateyUninstallTemplate.cs @@ -55,11 +55,6 @@ public class ChocolateyUninstallTemplate #validExitCodes= @(0) #please insert other valid exit codes here } -# Get-UninstallRegistryKey is new to 0.9.10, if supporting 0.9.9.x and below, -# take a dependency on ""chocolatey-core.extension"" in your nuspec file. -# This is only a fuzzy search if $softwareName includes '*'. Otherwise it is -# exact. In the case of versions in key names, we recommend removing the version -# and using '*'. [array]$key = Get-UninstallRegistryKey -SoftwareName $packageArgs['softwareName'] if ($key.Count -eq 1) { @@ -98,7 +93,7 @@ public class ChocolateyUninstallTemplate ## OTHER POWERSHELL FUNCTIONS ## https://docs.chocolatey.org/en-us/create/functions #Uninstall-ChocolateyZipPackage $packageName # Only necessary if you did not unpack to package directory - see https://docs.chocolatey.org/en-us/create/functions/uninstall-chocolateyzippackage -#Uninstall-ChocolateyEnvironmentVariable # 0.9.10+ - https://docs.chocolatey.org/en-us/create/functions/uninstall-chocolateyenvironmentvariable +#Uninstall-ChocolateyEnvironmentVariable - https://docs.chocolatey.org/en-us/create/functions/uninstall-chocolateyenvironmentvariable #Uninstall-BinFile # Only needed if you used Install-BinFile - see https://docs.chocolatey.org/en-us/create/functions/uninstall-binfile ## Remove any shortcuts you added in the install script. diff --git a/src/chocolatey/infrastructure.app/templates/NuspecTemplate.cs b/src/chocolatey/infrastructure.app/templates/NuspecTemplate.cs index af46d9319d..3bd2db1b5a 100644 --- a/src/chocolatey/infrastructure.app/templates/NuspecTemplate.cs +++ b/src/chocolatey/infrastructure.app/templates/NuspecTemplate.cs @@ -85,11 +85,7 @@ public class NuspecTemplate <dependency id="""" /> <dependency id=""chocolatey-core.extension"" version=""1.1.0"" /> </dependencies>--> - <!-- chocolatey-core.extension - https://community.chocolatey.org/packages/chocolatey-core.extension - - You want to use Get-UninstallRegistryKey on less than 0.9.10 (in chocolateyUninstall.ps1) - - You want to use Get-PackageParameters and on less than 0.11.0 - - You want to take advantage of other functions in the core community maintainer's team extension package - --> + <!-- chocolatey-core.extension - https://community.chocolatey.org/packages/chocolatey-core.extension --> <!--<provides>NOT YET IMPLEMENTED</provides>--> <!--<conflicts>NOT YET IMPLEMENTED</conflicts>--> diff --git a/src/chocolatey/infrastructure.app/templates/TemplateValues.cs b/src/chocolatey/infrastructure.app/templates/TemplateValues.cs index 91ce63335e..72054a07d4 100644 --- a/src/chocolatey/infrastructure.app/templates/TemplateValues.cs +++ b/src/chocolatey/infrastructure.app/templates/TemplateValues.cs @@ -23,11 +23,11 @@ public class TemplateValues { public TemplateValues() { - set_normal(); + SetNormal(); AdditionalProperties = new Dictionary<string, string>(StringComparer.InvariantCultureIgnoreCase); } - public void set_normal() + public void SetNormal() { PackageName = "__NAME_REPLACE__"; PackageVersion = "__REPLACE__"; @@ -45,7 +45,7 @@ public void set_normal() ChecksumType64 = "sha256"; } - public void set_auto() + public void SetAutomatic() { PackageName = "{{PackageName}}"; PackageVersion = "{{PackageVersion}}"; @@ -63,7 +63,7 @@ public void set_auto() public string PackageNameLower { - get { return PackageName.to_lower(); } + get { return PackageName.ToLowerSafe(); } } public string PackageVersion { get; set; } @@ -84,5 +84,15 @@ public string PackageNameLower public static readonly string NamePropertyName = "PackageName"; public static readonly string VersionPropertyName = "PackageVersion"; public static readonly string MaintainerPropertyName = "MaintainerName"; + +#pragma warning disable IDE1006 + [Obsolete("This overload is deprecated and will be removed in v3.")] + public void set_normal() + => SetNormal(); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public void set_auto() + => SetAutomatic(); +#pragma warning restore IDE1006 } } diff --git a/src/chocolatey/infrastructure.app/utility/ArgumentsUtility.cs b/src/chocolatey/infrastructure.app/utility/ArgumentsUtility.cs index 7d45c70d3c..e11df001ed 100644 --- a/src/chocolatey/infrastructure.app/utility/ArgumentsUtility.cs +++ b/src/chocolatey/infrastructure.app/utility/ArgumentsUtility.cs @@ -16,32 +16,44 @@ namespace chocolatey.infrastructure.app.utility { + using System; + //todo: #2560 maybe find a better name/location for this public static class ArgumentsUtility { - public static bool arguments_contain_sensitive_information(string commandArguments) + public static bool SensitiveArgumentsProvided(string commandArguments) { //todo: #2561 this check is naive, we should switch to regex //this picks up cases where arguments are passed with '-' and '--' - return commandArguments.contains("-install-arguments-sensitive") - || commandArguments.contains("-package-parameters-sensitive") - || commandArguments.contains("apikey ") - || commandArguments.contains("config ") - || commandArguments.contains("push ") // push can be passed w/out parameters, it's fine to log it then - || commandArguments.contains("-p ") - || commandArguments.contains("-p=") - || commandArguments.contains("-password") - || commandArguments.contains("-cp ") - || commandArguments.contains("-cp=") - || commandArguments.contains("-certpassword") - || commandArguments.contains("-k ") - || commandArguments.contains("-k=") - || commandArguments.contains("-key ") - || commandArguments.contains("-key=") - || commandArguments.contains("-apikey") - || commandArguments.contains("-api-key") + return commandArguments.ContainsSafe("-install-arguments-sensitive") + || commandArguments.ContainsSafe("-package-parameters-sensitive") + || commandArguments.ContainsSafe("apikey ") + || commandArguments.ContainsSafe("config ") + || commandArguments.ContainsSafe("push ") // push can be passed w/out parameters, it's fine to log it then + || commandArguments.ContainsSafe("-p ") + || commandArguments.ContainsSafe("-p=") + || commandArguments.ContainsSafe("-password") + || commandArguments.ContainsSafe("-cp ") + || commandArguments.ContainsSafe("-cp=") + || commandArguments.ContainsSafe("-certpassword") + || commandArguments.ContainsSafe("-k ") + || commandArguments.ContainsSafe("-k=") + || commandArguments.ContainsSafe("-key ") + || commandArguments.ContainsSafe("-key=") + || commandArguments.ContainsSafe("-apikey") + || commandArguments.ContainsSafe("-api-key") + || commandArguments.ContainsSafe("-u ") + || commandArguments.ContainsSafe("-u=") + || commandArguments.ContainsSafe("-user ") + || commandArguments.ContainsSafe("-user=") ; } + +#pragma warning disable IDE1006 + [Obsolete("This overload is deprecated and will be removed in v3.")] + public static bool arguments_contain_sensitive_information(string commandArguments) + => SensitiveArgumentsProvided(commandArguments); +#pragma warning restore IDE1006 } } diff --git a/src/chocolatey/infrastructure.app/utility/PackageUtility.cs b/src/chocolatey/infrastructure.app/utility/PackageUtility.cs index 2c437339d2..78b52f0425 100644 --- a/src/chocolatey/infrastructure.app/utility/PackageUtility.cs +++ b/src/chocolatey/infrastructure.app/utility/PackageUtility.cs @@ -28,19 +28,19 @@ public class PackageUtility /// <param name="config">The configuration.</param> /// <param name="packageName">Name of the package.</param> /// <returns>true if the package is a dependency, false if the package is the one specified or a virtual/semi-virtual</returns> - public static bool package_is_a_dependency(ChocolateyConfiguration config, string packageName) + public static bool PackageIdHasDependencySuffix(ChocolateyConfiguration config, string packageName) { if (string.IsNullOrWhiteSpace(config.PackageNames)) return true; if (string.IsNullOrWhiteSpace(packageName)) return true; - foreach (var package in config.PackageNames.Split(new[] { ApplicationParameters.PackageNamesSeparator }, StringSplitOptions.RemoveEmptyEntries).or_empty_list_if_null()) + foreach (var package in config.PackageNames.Split(new[] { ApplicationParameters.PackageNamesSeparator }, StringSplitOptions.RemoveEmptyEntries).OrEmpty()) { - if (packageName.is_equal_to(package) - || packageName.contains(package + ".") - || (package.contains(packageName) - && (package.contains(".nupkg") - || package.contains(".nuspec") - || package.contains("{0}".format_with(Platform.get_platform() == PlatformType.Windows ? "\\" : "/")) + if (packageName.IsEqualTo(package) + || packageName.ContainsSafe(package + ".") + || (package.ContainsSafe(packageName) + && (package.ContainsSafe(".nupkg") + || package.ContainsSafe(".nuspec") + || package.ContainsSafe("{0}".FormatWith(Platform.GetPlatform() == PlatformType.Windows ? "\\" : "/")) ) ) ) @@ -51,5 +51,11 @@ public static bool package_is_a_dependency(ChocolateyConfiguration config, strin return true; } + +#pragma warning disable IDE1006 + [Obsolete("This overload is deprecated and will be removed in v3.")] + public static bool package_is_a_dependency(ChocolateyConfiguration config, string packageName) + => PackageIdHasDependencySuffix(config, packageName); +#pragma warning restore IDE1006 } } diff --git a/src/chocolatey/infrastructure.app/validations/GlobalConfigurationValidation.cs b/src/chocolatey/infrastructure.app/validations/GlobalConfigurationValidation.cs index c0e28e11c9..6c7f8aa495 100644 --- a/src/chocolatey/infrastructure.app/validations/GlobalConfigurationValidation.cs +++ b/src/chocolatey/infrastructure.app/validations/GlobalConfigurationValidation.cs @@ -16,6 +16,7 @@ namespace chocolatey.infrastructure.app.validations { + using System; using System.Collections.Generic; using configuration; using infrastructure.validations; @@ -28,12 +29,12 @@ namespace chocolatey.infrastructure.app.validations /// </summary> public class GlobalConfigurationValidation : IValidation { - public ICollection<ValidationResult> validate(ChocolateyConfiguration config) + public ICollection<ValidationResult> Validate(ChocolateyConfiguration config) { this.Log().Debug("Global Configuration Validation Checks:"); var validationResults = new List<ValidationResult>(); - check_usage_of_package_exit_code(config, validationResults); + ValidateUseOfPackageExitCode(config, validationResults); if (validationResults.Count == 0) { @@ -48,7 +49,7 @@ public ICollection<ValidationResult> validate(ChocolateyConfiguration config) return validationResults; } - private void check_usage_of_package_exit_code(ChocolateyConfiguration config, ICollection<ValidationResult> validationResults) + private void ValidateUseOfPackageExitCode(ChocolateyConfiguration config, ICollection<ValidationResult> validationResults) { var validationStatusResult = ValidationStatus.Checked; // In order for a Chocolatey execution to correctly halt @@ -65,7 +66,7 @@ private void check_usage_of_package_exit_code(ChocolateyConfiguration config, IC usePackageExitCodes feature enabled. Use the following command: choco feature enable -name={0} to enable this feature (exit code 1). -".format_with(ApplicationParameters.Features.UsePackageExitCodes), +".FormatWith(ApplicationParameters.Features.UsePackageExitCodes), Status = ValidationStatus.Error, ExitCode = 1 }; @@ -80,7 +81,13 @@ to enable this feature (exit code 1). validationResults.Add(validationResult); } - this.Log().Debug(" - Package Exit Code / Exit On Reboot = {0}".format_with(validationStatusResult.to_string())); + this.Log().Debug(" - Package Exit Code / Exit On Reboot = {0}".FormatWith(validationStatusResult.ToStringSafe())); } + +#pragma warning disable IDE1006 + [Obsolete("This overload is deprecated and will be removed in v3.")] + public ICollection<ValidationResult> validate(ChocolateyConfiguration config) + => Validate(config); +#pragma warning restore IDE1006 } } diff --git a/src/chocolatey/infrastructure.app/validations/SystemStateValidation.cs b/src/chocolatey/infrastructure.app/validations/SystemStateValidation.cs index 52971023c9..f8c3ff19f0 100644 --- a/src/chocolatey/infrastructure.app/validations/SystemStateValidation.cs +++ b/src/chocolatey/infrastructure.app/validations/SystemStateValidation.cs @@ -36,12 +36,12 @@ public SystemStateValidation(IPendingRebootService pendingRebootService) _pendingRebootService = pendingRebootService; } - public ICollection<ValidationResult> validate(ChocolateyConfiguration config) + public ICollection<ValidationResult> Validate(ChocolateyConfiguration config) { this.Log().Debug("System State Validation Checks:"); var validationResults = new List<ValidationResult>(); - check_system_pending_reboot(config, validationResults); + ValidateSystemPendingReboot(config, validationResults); if (validationResults.Count == 0) { @@ -56,9 +56,9 @@ public ICollection<ValidationResult> validate(ChocolateyConfiguration config) return validationResults; } - private void check_system_pending_reboot(ChocolateyConfiguration config, ICollection<ValidationResult> validationResults) + private void ValidateSystemPendingReboot(ChocolateyConfiguration config, ICollection<ValidationResult> validationResults) { - var result = _pendingRebootService.is_pending_reboot(config); + var result = _pendingRebootService.IsRebootPending(config); if (result) { @@ -71,7 +71,7 @@ private void check_system_pending_reboot(ChocolateyConfiguration config, ICollec Message = @"A pending system reboot request has been detected, however, this is being ignored due to the current command being used '{0}'. It is recommended that you reboot at your earliest convenience. -".format_with(config.CommandName), +".FormatWith(config.CommandName), Status = ValidationStatus.Warning, ExitCode = 0 }); @@ -86,7 +86,7 @@ being ignored due to the current Chocolatey configuration. If you using: choco feature enable -name={0} or pass the option --exit-when-reboot-detected. -".format_with(ApplicationParameters.Features.ExitOnRebootDetected), +".FormatWith(ApplicationParameters.Features.ExitOnRebootDetected), Status = ValidationStatus.Warning, ExitCode = 0 }); @@ -97,12 +97,18 @@ or pass the option --exit-when-reboot-detected. validationResults.Add(new ValidationResult { - Message = "A pending system reboot has been detected (exit code {0}).".format_with(ApplicationParameters.ExitCodes.ErrorFailNoActionReboot), + Message = "A pending system reboot has been detected (exit code {0}).".FormatWith(ApplicationParameters.ExitCodes.ErrorFailNoActionReboot), Status = ValidationStatus.Error, ExitCode = ApplicationParameters.ExitCodes.ErrorFailNoActionReboot }); } } } + +#pragma warning disable IDE1006 + [Obsolete("This overload is deprecated and will be removed in v3.")] + public ICollection<ValidationResult> validate(ChocolateyConfiguration config) + => Validate(config); +#pragma warning restore IDE1006 } } diff --git a/src/chocolatey/infrastructure/adapters/Assembly.cs b/src/chocolatey/infrastructure/adapters/Assembly.cs index 9a0472a7c9..999eb6348a 100644 --- a/src/chocolatey/infrastructure/adapters/Assembly.cs +++ b/src/chocolatey/infrastructure/adapters/Assembly.cs @@ -21,8 +21,6 @@ namespace chocolatey.infrastructure.adapters using System.IO; using System.Reflection; - // ReSharper disable InconsistentNaming - public sealed class Assembly : IAssembly { private readonly System.Reflection.Assembly _assembly; @@ -130,7 +128,7 @@ public static IAssembly GetEntryAssembly() return new Assembly(System.Reflection.Assembly.GetEntryAssembly()); } - public static IAssembly set_assembly(System.Reflection.Assembly value) + public static IAssembly SetAssembly(System.Reflection.Assembly value) { return new Assembly(value); } @@ -139,7 +137,11 @@ public static implicit operator Assembly(System.Reflection.Assembly value) { return new Assembly(value); } - } - // ReSharper restore InconsistentNaming +#pragma warning disable IDE1006 + [Obsolete("This overload is deprecated and will be removed in v3.")] + public static IAssembly set_assembly(System.Reflection.Assembly value) + => SetAssembly(value); +#pragma warning restore IDE1006 + } } diff --git a/src/chocolatey/infrastructure/adapters/Console.cs b/src/chocolatey/infrastructure/adapters/Console.cs index 7ff34714ca..9bacb403f9 100644 --- a/src/chocolatey/infrastructure/adapters/Console.cs +++ b/src/chocolatey/infrastructure/adapters/Console.cs @@ -39,7 +39,7 @@ public string ReadLine(int timeoutMilliseconds) { if (!ApplicationParameters.AllowPrompts) return string.Empty; - return ReadLineTimeout.read(timeoutMilliseconds); + return ReadLineTimeout.Read(timeoutMilliseconds); } public System.ConsoleKeyInfo ReadKey(bool intercept) @@ -53,7 +53,7 @@ public System.ConsoleKeyInfo ReadKey(int timeoutMilliseconds) { if (!ApplicationParameters.AllowPrompts) return new System.ConsoleKeyInfo('\0', ConsoleKey.Enter, false, false, false); - return ReadKeyTimeout.read_key(timeoutMilliseconds); + return ReadKeyTimeout.ReadKey(timeoutMilliseconds); } public TextWriter Error { get { return System.Console.Error; } } @@ -62,7 +62,7 @@ public System.ConsoleKeyInfo ReadKey(int timeoutMilliseconds) public void Write(object value) { - System.Console.Write(value.to_string()); + System.Console.Write(value.ToStringSafe()); } public void WriteLine() @@ -109,7 +109,7 @@ public int BufferWidth { if (!IsOutputRedirected) return System.Console.BufferWidth; - return get_console_buffer().dwSize.X; //the current console window width + return GetConsoleBuffer().dwSize.X; //the current console window width } set { @@ -123,7 +123,7 @@ public int BufferHeight { if (!IsOutputRedirected) return System.Console.BufferHeight; - return get_console_buffer().dwSize.Y; //the current console window height + return GetConsoleBuffer().dwSize.Y; //the current console window height } set { @@ -166,7 +166,7 @@ public int CursorSize { if (!IsOutputRedirected) return System.Console.CursorSize; - return get_console_buffer().dwCursorPosition.Y; + return GetConsoleBuffer().dwCursorPosition.Y; } set { @@ -180,7 +180,7 @@ public int LargestWindowWidth { if (!IsOutputRedirected) return System.Console.LargestWindowWidth; - return get_console_buffer().dwMaximumWindowSize.X; //the max console window width + return GetConsoleBuffer().dwMaximumWindowSize.X; //the max console window width } } @@ -190,7 +190,7 @@ public int LargestWindowHeight { if (!IsOutputRedirected) return System.Console.LargestWindowHeight; - return get_console_buffer().dwMaximumWindowSize.Y; //the max console window height + return GetConsoleBuffer().dwMaximumWindowSize.Y; //the max console window height } } @@ -200,7 +200,7 @@ public int WindowWidth { if (!IsOutputRedirected) return System.Console.WindowWidth; - return get_console_buffer().dwSize.X; //the current console window width + return GetConsoleBuffer().dwSize.X; //the current console window width } set { @@ -214,7 +214,7 @@ public int WindowHeight { if (!IsOutputRedirected) return System.Console.WindowHeight; - return get_console_buffer().dwSize.Y; //the current console window height + return GetConsoleBuffer().dwSize.Y; //the current console window height } set { @@ -233,7 +233,7 @@ public int WindowLeft { if (!IsOutputRedirected) return System.Console.WindowLeft; - return get_console_buffer().srWindow.Left; + return GetConsoleBuffer().srWindow.Left; } set { @@ -247,7 +247,7 @@ public int WindowTop { if (!IsOutputRedirected) return System.Console.WindowTop; - return get_console_buffer().srWindow.Top; + return GetConsoleBuffer().srWindow.Top; } set { @@ -267,7 +267,7 @@ public bool IsOutputRedirected { get { - if (!is_windows()) return false; + if (!IsWindows()) return false; return FileType.Char != GetFileType(GetStdHandle(StdHandle.StdOut)); } @@ -280,7 +280,7 @@ public bool IsErrorRedirected { get { - if (!is_windows()) return false; + if (!IsWindows()) return false; return FileType.Char != GetFileType(GetStdHandle(StdHandle.StdErr)); } @@ -293,18 +293,18 @@ public bool IsInputRedirected { get { - if (!is_windows()) return false; + if (!IsWindows()) return false; return FileType.Char != GetFileType(GetStdHandle(StdHandle.StdIn)); } } - private bool is_windows() + private bool IsWindows() { - return Platform.get_platform() == PlatformType.Windows; + return Platform.GetPlatform() == PlatformType.Windows; } - private CONSOLE_SCREEN_BUFFER_INFO get_console_buffer() + private CONSOLE_SCREEN_BUFFER_INFO GetConsoleBuffer() { var defaultConsoleBuffer = new CONSOLE_SCREEN_BUFFER_INFO { @@ -315,7 +315,7 @@ private CONSOLE_SCREEN_BUFFER_INFO get_console_buffer() wAttributes = 0, }; - if (!is_windows()) return defaultConsoleBuffer; + if (!IsWindows()) return defaultConsoleBuffer; CONSOLE_SCREEN_BUFFER_INFO csbi; if (GetConsoleScreenBufferInfo(GetStdHandle(StdHandle.StdOut), out csbi)) diff --git a/src/chocolatey/infrastructure/adapters/Environment.cs b/src/chocolatey/infrastructure/adapters/Environment.cs index 8a6745bd25..26df791377 100644 --- a/src/chocolatey/infrastructure/adapters/Environment.cs +++ b/src/chocolatey/infrastructure/adapters/Environment.cs @@ -37,7 +37,7 @@ public bool Is64BitProcess get { // ARM64 bit architecture has a x86-32 emulator, so return false - if (System.Environment.GetEnvironmentVariable(ApplicationParameters.Environment.ProcessorArchitecture).to_string().is_equal_to(ApplicationParameters.Environment.ARM64_PROCESSOR_ARCHITECTURE)) + if (System.Environment.GetEnvironmentVariable(ApplicationParameters.Environment.ProcessorArchitecture).ToStringSafe().IsEqualTo(ApplicationParameters.Environment.Arm64ProcessorArchitecture)) { return false; } diff --git a/src/chocolatey/infrastructure/adapters/IDateTime.cs b/src/chocolatey/infrastructure/adapters/IDateTime.cs index 764c969e0d..c57fd6c544 100644 --- a/src/chocolatey/infrastructure/adapters/IDateTime.cs +++ b/src/chocolatey/infrastructure/adapters/IDateTime.cs @@ -16,8 +16,6 @@ namespace chocolatey.infrastructure.adapters { - // ReSharper disable InconsistentNaming - public interface IDateTime { /// <summary> @@ -38,6 +36,4 @@ public interface IDateTime /// <filterpriority>1</filterpriority> System.DateTime UtcNow { get; } } - - // ReSharper restore InconsistentNaming } diff --git a/src/chocolatey/infrastructure/adapters/IEncryptionUtility.cs b/src/chocolatey/infrastructure/adapters/IEncryptionUtility.cs index 1207b35629..ad9fda3ee8 100644 --- a/src/chocolatey/infrastructure/adapters/IEncryptionUtility.cs +++ b/src/chocolatey/infrastructure/adapters/IEncryptionUtility.cs @@ -16,10 +16,21 @@ namespace chocolatey.infrastructure.adapters { + using System; + public interface IEncryptionUtility { + string EncryptString(string cleartextValue); + string DecryptString(string encryptedString); + string GenerateUniqueToken(string caseInsensitiveKey); + +#pragma warning disable IDE1006 + [Obsolete("This overload is deprecated and will be removed in v3.")] string encrypt_string(string cleartextValue); + [Obsolete("This overload is deprecated and will be removed in v3.")] string decrypt_string(string encryptedString); + [Obsolete("This overload is deprecated and will be removed in v3.")] string generate_unique_token(string caseInsensitiveKey); +#pragma warning restore IDE1006 } } diff --git a/src/chocolatey/infrastructure/commandline/ExitScenarioHandler.cs b/src/chocolatey/infrastructure/commandline/ExitScenarioHandler.cs index 9b60627d46..641fa1afe2 100644 --- a/src/chocolatey/infrastructure/commandline/ExitScenarioHandler.cs +++ b/src/chocolatey/infrastructure/commandline/ExitScenarioHandler.cs @@ -48,7 +48,7 @@ private enum SignalControlType public static void SetHandler() { - if (Platform.get_platform() != PlatformType.Windows) return; + if (Platform.GetPlatform() != PlatformType.Windows) return; _handler += Handler; SetConsoleCtrlHandler(_handler, true); diff --git a/src/chocolatey/infrastructure/commandline/InteractivePrompt.cs b/src/chocolatey/infrastructure/commandline/InteractivePrompt.cs index 50679474d0..c732105fd5 100644 --- a/src/chocolatey/infrastructure/commandline/InteractivePrompt.cs +++ b/src/chocolatey/infrastructure/commandline/InteractivePrompt.cs @@ -28,10 +28,10 @@ namespace chocolatey.infrastructure.commandline public class InteractivePrompt { private static Lazy<IConsole> _console = new Lazy<IConsole>(() => new Console()); - private const int TIMEOUT_IN_SECONDS = 30; + private const int TimeoutInSeconds = 30; [EditorBrowsable(EditorBrowsableState.Never)] - public static void initialize_with(Lazy<IConsole> console) + public static void InitializeWith(Lazy<IConsole> console) { _console = console; } @@ -41,22 +41,22 @@ private static IConsole Console get { return _console.Value; } } - public static string prompt_for_confirmation(string prompt, IEnumerable<string> choices, string defaultChoice, bool requireAnswer, bool allowShortAnswer = true, bool shortPrompt = false, int repeat = 10, int timeoutInSeconds = 0) + public static string PromptForConfirmation(string prompt, IEnumerable<string> choices, string defaultChoice, bool requireAnswer, bool allowShortAnswer = true, bool shortPrompt = false, int repeat = 10, int timeoutInSeconds = 0) { if (repeat < 0) throw new ApplicationException("Too many bad attempts. Stopping before application crash."); - Ensure.that(() => prompt).is_not_null(); - Ensure.that(() => choices).is_not_null(); + Ensure.That(() => prompt).NotNull(); + Ensure.That(() => choices).NotNull(); Ensure - .that(() => choices) - .meets( + .That(() => choices) + .Meets( c => c.Count() > 0, (name, value) => { throw new ApplicationException("No choices passed in. Please ensure you pass choices"); }); if (!string.IsNullOrWhiteSpace(defaultChoice)) { Ensure - .that(() => choices) - .meets( + .That(() => choices) + .Meets( c => c.Contains(defaultChoice), (name, value) => { throw new ApplicationException("Default choice value must be one of the given choices."); }); } @@ -64,21 +64,21 @@ public static string prompt_for_confirmation(string prompt, IEnumerable<string> if (allowShortAnswer) { Ensure - .that(() => choices) - .meets( + .That(() => choices) + .Meets( c => !c.Any(String.IsNullOrWhiteSpace), (name, value) => { throw new ApplicationException("Some choices are empty. Please ensure you provide no empty choices."); }); Ensure - .that(() => choices) - .meets( + .That(() => choices) + .Meets( c => c.Select(entry => entry.FirstOrDefault()).Distinct().Count() == c.Count(), (name, value) => { throw new ApplicationException("Multiple choices have the same first letter. Please ensure you pass choices with different first letters."); }); } if (timeoutInSeconds > 0) { - "chocolatey".Log().Info(ChocolateyLoggers.Important, "For the question below, you have {0} seconds to make a selection.".format_with(timeoutInSeconds)); + "chocolatey".Log().Info(ChocolateyLoggers.Important, "For the question below, you have {0} seconds to make a selection.".FormatWith(timeoutInSeconds)); } if (shortPrompt) @@ -91,19 +91,19 @@ public static string prompt_for_confirmation(string prompt, IEnumerable<string> int counter = 1; IDictionary<int, string> choiceDictionary = new Dictionary<int, string>(); - foreach (var choice in choices.or_empty_list_if_null()) + foreach (var choice in choices.OrEmpty()) { choiceDictionary.Add(counter, choice); - "chocolatey".Log().Info(shortPrompt ? ChocolateyLoggers.LogFileOnly : ChocolateyLoggers.Normal," {0}) {1}{2}".format_with(counter, choice.to_string(), choice.is_equal_to(defaultChoice) ? " [Default - Press Enter]" : "")); + "chocolatey".Log().Info(shortPrompt ? ChocolateyLoggers.LogFileOnly : ChocolateyLoggers.Normal," {0}) {1}{2}".FormatWith(counter, choice.ToStringSafe(), choice.IsEqualTo(defaultChoice) ? " [Default - Press Enter]" : "")); if (shortPrompt) { - var choicePrompt = choice.is_equal_to(defaultChoice) ? + var choicePrompt = choice.IsEqualTo(defaultChoice) ? shortPrompt ? - "[[{0}]{1}]".format_with(choice.Substring(0, 1).ToUpperInvariant(), choice.Substring(1, choice.Length - 1)) : - "[{0}]".format_with(choice.ToUpperInvariant()) + "[[{0}]{1}]".FormatWith(choice.Substring(0, 1).ToUpperInvariant(), choice.Substring(1, choice.Length - 1)) : + "[{0}]".FormatWith(choice.ToUpperInvariant()) : shortPrompt ? - "[{0}]{1}".format_with(choice.Substring(0,1).ToUpperInvariant(), choice.Substring(1, choice.Length - 1)) : + "[{0}]{1}".FormatWith(choice.Substring(0,1).ToUpperInvariant(), choice.Substring(1, choice.Length - 1)) : choice; if (counter != 1) Console.Write("/"); @@ -120,7 +120,7 @@ public static string prompt_for_confirmation(string prompt, IEnumerable<string> if (string.IsNullOrWhiteSpace(selection) && !string.IsNullOrWhiteSpace(defaultChoice)) { - "chocolatey".Log().Info(ChocolateyLoggers.LogFileOnly, "Choosing default choice of '{0}'".format_with(defaultChoice.escape_curly_braces())); + "chocolatey".Log().Info(ChocolateyLoggers.LogFileOnly, "Choosing default choice of '{0}'".FormatWith(defaultChoice.EscapeCurlyBraces())); return defaultChoice; } @@ -131,26 +131,26 @@ public static string prompt_for_confirmation(string prompt, IEnumerable<string> var selectionFound = false; foreach (var pair in choiceDictionary) { - var value = pair.Value.to_string(); - if (value.is_equal_to(selection) || - (allowShortAnswer && value.Substring(0, 1).is_equal_to(selection)) || - (value.contains("-") && value.Substring(0, value.IndexOf("-")).trim_safe().is_equal_to(selection)) + var value = pair.Value.ToStringSafe(); + if (value.IsEqualTo(selection) || + (allowShortAnswer && value.Substring(0, 1).IsEqualTo(selection)) || + (value.ContainsSafe("-") && value.Substring(0, value.IndexOf("-")).TrimSafe().IsEqualTo(selection)) ) { selected = pair.Key; selectionFound = true; - "chocolatey".Log().Info(ChocolateyLoggers.LogFileOnly, "Choice selected: '{0}'".format_with(pair.Value.escape_curly_braces())); + "chocolatey".Log().Info(ChocolateyLoggers.LogFileOnly, "Choice selected: '{0}'".FormatWith(pair.Value.EscapeCurlyBraces())); break; } } if (!selectionFound) { - "chocolatey".Log().Error(ChocolateyLoggers.Important, "Timeout or your choice of '{0}' is not a valid selection.".format_with(selection.escape_curly_braces())); + "chocolatey".Log().Error(ChocolateyLoggers.Important, "Timeout or your choice of '{0}' is not a valid selection.".FormatWith(selection.EscapeCurlyBraces())); if (requireAnswer) { "chocolatey".Log().Warn(ChocolateyLoggers.Important, "You must select an answer"); - return prompt_for_confirmation(prompt, choices, defaultChoice, requireAnswer, allowShortAnswer, shortPrompt, repeat - 1); + return PromptForConfirmation(prompt, choices, defaultChoice, requireAnswer, allowShortAnswer, shortPrompt, repeat - 1); } return null; } @@ -159,18 +159,18 @@ public static string prompt_for_confirmation(string prompt, IEnumerable<string> return choiceDictionary[selected]; } - public static string get_password(bool interactive) + public static string GetPassword(bool interactive) { var password = string.Empty; var possibleNonInteractive = !interactive; - ConsoleKeyInfo info = possibleNonInteractive ? Console.ReadKey(TIMEOUT_IN_SECONDS * 1000) : Console.ReadKey(true); + ConsoleKeyInfo info = possibleNonInteractive ? Console.ReadKey(TimeoutInSeconds * 1000) : Console.ReadKey(true); while (info.Key != ConsoleKey.Enter) { if (info.Key != ConsoleKey.Backspace) { Console.Write("*"); password += info.KeyChar; - info = possibleNonInteractive ? Console.ReadKey(TIMEOUT_IN_SECONDS * 1000) : Console.ReadKey(true); + info = possibleNonInteractive ? Console.ReadKey(TimeoutInSeconds * 1000) : Console.ReadKey(true); } else if (info.Key == ConsoleKey.Backspace) { @@ -186,7 +186,7 @@ public static string get_password(bool interactive) // move the cursor to the left by one character again System.Console.SetCursorPosition(pos - 1, System.Console.CursorTop); } - info = possibleNonInteractive ? Console.ReadKey(TIMEOUT_IN_SECONDS * 1000) : Console.ReadKey(true); + info = possibleNonInteractive ? Console.ReadKey(TimeoutInSeconds * 1000) : Console.ReadKey(true); } } for (int i = 0; i < password.Length; i++) Console.Write("*"); @@ -194,5 +194,21 @@ public static string get_password(bool interactive) return password; } + + +#pragma warning disable IDE1006 + [Obsolete("This overload is deprecated and will be removed in v3.")] + [EditorBrowsable(EditorBrowsableState.Never)] + public static void initialize_with(Lazy<IConsole> console) + => InitializeWith(console); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public static string prompt_for_confirmation(string prompt, IEnumerable<string> choices, string defaultChoice, bool requireAnswer, bool allowShortAnswer = true, bool shortPrompt = false, int repeat = 10, int timeoutInSeconds = 0) + => PromptForConfirmation(prompt, choices, defaultChoice, requireAnswer, allowShortAnswer, shortPrompt, repeat, timeoutInSeconds); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public static string get_password(bool interactive) + => GetPassword(interactive); +#pragma warning restore IDE1006 } } diff --git a/src/chocolatey/infrastructure/commandline/Options.cs b/src/chocolatey/infrastructure/commandline/Options.cs index 07903eb2e2..39fd78de8f 100644 --- a/src/chocolatey/infrastructure/commandline/Options.cs +++ b/src/chocolatey/infrastructure/commandline/Options.cs @@ -824,7 +824,7 @@ protected virtual bool Parse (string argument, OptionContext c) } catch (Exception ex) { - "chocolatey".Log().Warn("Parsing {0} resulted in error (converted to warning):{1} {2}".format_with(argument, Environment.NewLine, ex.Message)); + "chocolatey".Log().Warn("Parsing {0} resulted in error (converted to warning):{1} {2}".FormatWith(argument, Environment.NewLine, ex.Message)); } return false; diff --git a/src/chocolatey/infrastructure/commandline/ReadKeyTimeout.cs b/src/chocolatey/infrastructure/commandline/ReadKeyTimeout.cs index 13ae4ed50b..df6132c53d 100644 --- a/src/chocolatey/infrastructure/commandline/ReadKeyTimeout.cs +++ b/src/chocolatey/infrastructure/commandline/ReadKeyTimeout.cs @@ -38,24 +38,24 @@ private ReadKeyTimeout() { _backgroundResponseReset = new AutoResetEvent(false); _foregroundResponseReset = new AutoResetEvent(false); - _responseThread = new Thread(console_read_key) + _responseThread = new Thread(ConsoleReadKey) { IsBackground = true }; _responseThread.Start(); } - private void console_read_key() + private void ConsoleReadKey() { while (true) { _backgroundResponseReset.WaitOne(); - _input = Console.ReadKey(intercept:true); + _input = Console.ReadKey(intercept: true); _foregroundResponseReset.Set(); } } - public static ConsoleKeyInfo read_key(int timeoutMilliseconds) + public static ConsoleKeyInfo ReadKey(int timeoutMilliseconds) { using (var readLine = new ReadKeyTimeout()) { @@ -63,7 +63,7 @@ public static ConsoleKeyInfo read_key(int timeoutMilliseconds) return readLine._foregroundResponseReset.WaitOne(timeoutMilliseconds) ? readLine._input - : new ConsoleKeyInfo('\0',ConsoleKey.Enter,false,false,false); + : new ConsoleKeyInfo('\0', ConsoleKey.Enter, false, false, false); } } @@ -79,5 +79,10 @@ public void Dispose() _foregroundResponseReset.Dispose(); } +#pragma warning disable IDE1006 + [Obsolete("This overload is deprecated and will be removed in v3.")] + public static ConsoleKeyInfo read_key(int timeoutMilliseconds) + => ReadKey(timeoutMilliseconds); +#pragma warning restore IDE1006 } } diff --git a/src/chocolatey/infrastructure/commandline/ReadLineTimeout.cs b/src/chocolatey/infrastructure/commandline/ReadLineTimeout.cs index 501d6ca7c3..5e75b48497 100644 --- a/src/chocolatey/infrastructure/commandline/ReadLineTimeout.cs +++ b/src/chocolatey/infrastructure/commandline/ReadLineTimeout.cs @@ -38,14 +38,14 @@ private ReadLineTimeout() { _backgroundResponseReset = new AutoResetEvent(false); _foregroundResponseReset = new AutoResetEvent(false); - _responseThread = new Thread(console_read) + _responseThread = new Thread(ConsoleRead) { IsBackground = true }; _responseThread.Start(); } - private void console_read() + private void ConsoleRead() { while (true) { @@ -55,7 +55,7 @@ private void console_read() } } - public static string read(int timeoutMilliseconds) + public static string Read(int timeoutMilliseconds) { using (var readLine = new ReadLineTimeout()) { @@ -78,5 +78,12 @@ public void Dispose() _foregroundResponseReset.Close(); _foregroundResponseReset.Dispose(); } + + +#pragma warning disable IDE1006 + [Obsolete("This overload is deprecated and will be removed in v3.")] + public static string read(int timeoutMilliseconds) + => Read(timeoutMilliseconds); +#pragma warning restore IDE1006 } } diff --git a/src/chocolatey/infrastructure/commands/CommandExecutor.cs b/src/chocolatey/infrastructure/commands/CommandExecutor.cs index 99bc063b9c..3eb526c3da 100644 --- a/src/chocolatey/infrastructure/commands/CommandExecutor.cs +++ b/src/chocolatey/infrastructure/commands/CommandExecutor.cs @@ -30,31 +30,31 @@ public sealed class CommandExecutor : ICommandExecutor { public CommandExecutor(IFileSystem fileSystem) { - file_system_initializer = new Lazy<IFileSystem>(() => fileSystem); + _fileSystem = new Lazy<IFileSystem>(() => fileSystem); } - private static Lazy<IFileSystem> file_system_initializer = new Lazy<IFileSystem>(() => new DotNetFileSystem()); + private static Lazy<IFileSystem> _fileSystem = new Lazy<IFileSystem>(() => new DotNetFileSystem()); - private static IFileSystem file_system + private static IFileSystem FileSystem { - get { return file_system_initializer.Value; } + get { return _fileSystem.Value; } } - private static Func<IProcess> initialize_process = () => new Process(); + private static Func<IProcess> _initializeProcess = () => new Process(); [EditorBrowsable(EditorBrowsableState.Never)] - public static void initialize_with(Lazy<IFileSystem> file_system, Func<IProcess> process_initializer) + public static void InitializeWith(Lazy<IFileSystem> fileSystem, Func<IProcess> processInitializer) { - file_system_initializer = file_system; - initialize_process = process_initializer; + _fileSystem = fileSystem; + _initializeProcess = processInitializer; } - public int execute(string process, string arguments, int waitForExitInSeconds) + public int Execute(string process, string arguments, int waitForExitInSeconds) { - return execute(process, arguments, waitForExitInSeconds, file_system.get_directory_name(file_system.get_current_assembly_path())); + return Execute(process, arguments, waitForExitInSeconds, FileSystem.GetDirectoryName(FileSystem.GetCurrentAssemblyPath())); } - public int execute( + public int Execute( string process, string arguments, int waitForExitInSeconds, @@ -63,10 +63,10 @@ public int execute( bool updateProcessPath = true ) { - return execute(process, + return Execute(process, arguments, waitForExitInSeconds, - file_system.get_directory_name(file_system.get_current_assembly_path()), + FileSystem.GetDirectoryName(FileSystem.GetCurrentAssemblyPath()), stdOutAction, stdErrAction, updateProcessPath, @@ -74,12 +74,12 @@ public int execute( ); } - public int execute(string process, string arguments, int waitForExitInSeconds, string workingDirectory) + public int Execute(string process, string arguments, int waitForExitInSeconds, string workingDirectory) { - return execute(process, arguments, waitForExitInSeconds, workingDirectory, null, null, updateProcessPath: true, allowUseWindow: false); + return Execute(process, arguments, waitForExitInSeconds, workingDirectory, null, null, updateProcessPath: true, allowUseWindow: false); } - public int execute(string process, + public int Execute(string process, string arguments, int waitForExitInSeconds, string workingDirectory, @@ -89,7 +89,7 @@ public int execute(string process, bool allowUseWindow ) { - return execute(process, + return Execute(process, arguments, waitForExitInSeconds, workingDirectory, @@ -101,7 +101,7 @@ bool allowUseWindow ); } - public int execute(string process, + public int Execute(string process, string arguments, int waitForExitInSeconds, string workingDirectory, @@ -112,7 +112,7 @@ public int execute(string process, bool waitForExit ) { - return execute_static(process, + return ExecuteStatic(process, arguments, waitForExitInSeconds, workingDirectory, @@ -124,7 +124,7 @@ bool waitForExit ); } - public static int execute_static(string process, + public static int ExecuteStatic(string process, string arguments, int waitForExitInSeconds, string workingDirectory, @@ -134,7 +134,7 @@ public static int execute_static(string process, bool allowUseWindow ) { - return execute_static(process, + return ExecuteStatic(process, arguments, waitForExitInSeconds, workingDirectory, @@ -146,7 +146,7 @@ bool allowUseWindow ); } - public static int execute_static(string process, + public static int ExecuteStatic(string process, string arguments, int waitForExitInSeconds, string workingDirectory, @@ -160,10 +160,10 @@ bool waitForExit int exitCode = -1; if (updateProcessPath) { - process = file_system.get_full_path(process); + process = FileSystem.GetFullPath(process); } - if (Platform.get_platform() != PlatformType.Windows) + if (Platform.GetPlatform() != PlatformType.Windows) { arguments = process + " " + arguments; process = "mono"; @@ -171,12 +171,12 @@ bool waitForExit if (string.IsNullOrWhiteSpace(workingDirectory)) { - workingDirectory = file_system.get_directory_name(file_system.get_current_assembly_path()); + workingDirectory = FileSystem.GetDirectoryName(FileSystem.GetCurrentAssemblyPath()); } - "chocolatey".Log().Debug(() => "Calling command ['\"{0}\" {1}']".format_with(process.escape_curly_braces(), arguments.escape_curly_braces())); + "chocolatey".Log().Debug(() => "Calling command ['\"{0}\" {1}']".FormatWith(process.EscapeCurlyBraces(), arguments.EscapeCurlyBraces())); - var psi = new ProcessStartInfo(process.remove_surrounding_quotes(), arguments) + var psi = new ProcessStartInfo(process.UnquoteSafe(), arguments) { UseShellExecute = false, WorkingDirectory = workingDirectory, @@ -186,12 +186,12 @@ bool waitForExit WindowStyle = ProcessWindowStyle.Minimized, }; - using (var p = initialize_process()) + using (var p = _initializeProcess()) { p.StartInfo = psi; if (stdOutAction == null) { - p.OutputDataReceived += log_output; + p.OutputDataReceived += LogOutput; } else { @@ -199,7 +199,7 @@ bool waitForExit } if (stdErrAction == null) { - p.ErrorDataReceived += log_error; + p.ErrorDataReceived += LogError; } else { @@ -224,7 +224,7 @@ bool waitForExit { "chocolatey".Log().Warn(ChocolateyLoggers.Important, () => @"Chocolatey timed out waiting for the command to finish. The timeout specified (or the default value) was '{0}' seconds. Perhaps try a - higher `--execution-timeout`? See `choco -h` for details.".format_with(waitForExitInSeconds)); + higher `--execution-timeout`? See `choco -h` for details.".FormatWith(waitForExitInSeconds)); } } else @@ -239,18 +239,98 @@ bool waitForExit } } - "chocolatey".Log().Debug(() => "Command ['\"{0}\" {1}'] exited with '{2}'".format_with(process.escape_curly_braces(), arguments.escape_curly_braces(), exitCode)); + "chocolatey".Log().Debug(() => "Command ['\"{0}\" {1}'] exited with '{2}'".FormatWith(process.EscapeCurlyBraces(), arguments.EscapeCurlyBraces(), exitCode)); return exitCode; } - private static void log_output(object sender, DataReceivedEventArgs e) + private static void LogOutput(object sender, DataReceivedEventArgs e) { - if (e != null) "chocolatey".Log().Info(e.Data.escape_curly_braces()); + if (e != null) "chocolatey".Log().Info(e.Data.EscapeCurlyBraces()); } - private static void log_error(object sender, DataReceivedEventArgs e) + private static void LogError(object sender, DataReceivedEventArgs e) { - if (e != null) "chocolatey".Log().Error(e.Data.escape_curly_braces()); + if (e != null) "chocolatey".Log().Error(e.Data.EscapeCurlyBraces()); } + + +#pragma warning disable IDE1006 + [Obsolete("This overload is deprecated and will be removed in v3.")] + [EditorBrowsable(EditorBrowsableState.Never)] + public static void initialize_with(Lazy<IFileSystem> file_system, Func<IProcess> process_initializer) + => InitializeWith(file_system, process_initializer); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public int execute(string process, string arguments, int waitForExitInSeconds) + => Execute(process, arguments, waitForExitInSeconds); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public int execute( + string process, + string arguments, + int waitForExitInSeconds, + Action<object, DataReceivedEventArgs> stdOutAction, + Action<object, DataReceivedEventArgs> stdErrAction, + bool updateProcessPath = true) + => Execute(process, arguments, waitForExitInSeconds, stdOutAction, stdErrAction, updateProcessPath); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public int execute(string process, string arguments, int waitForExitInSeconds, string workingDirectory) + => Execute(process, arguments, waitForExitInSeconds, workingDirectory); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public int execute(string process, + string arguments, + int waitForExitInSeconds, + string workingDirectory, + Action<object, DataReceivedEventArgs> stdOutAction, + Action<object, DataReceivedEventArgs> stdErrAction, + bool updateProcessPath, + bool allowUseWindow) + => Execute(process, arguments, waitForExitInSeconds, workingDirectory, stdOutAction, stdErrAction, updateProcessPath, allowUseWindow); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public int execute(string process, + string arguments, + int waitForExitInSeconds, + string workingDirectory, + Action<object, DataReceivedEventArgs> stdOutAction, + Action<object, DataReceivedEventArgs> stdErrAction, + bool updateProcessPath, + bool allowUseWindow, + bool waitForExit) + => Execute(process, arguments, waitForExitInSeconds, workingDirectory, stdOutAction, stdErrAction, updateProcessPath, allowUseWindow, waitForExit); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public static int execute_static(string process, + string arguments, + int waitForExitInSeconds, + string workingDirectory, + Action<object, DataReceivedEventArgs> stdOutAction, + Action<object, DataReceivedEventArgs> stdErrAction, + bool updateProcessPath, + bool allowUseWindow) + => ExecuteStatic(process, arguments, waitForExitInSeconds, workingDirectory, stdOutAction, stdErrAction, updateProcessPath, allowUseWindow); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public static int execute_static(string process, + string arguments, + int waitForExitInSeconds, + string workingDirectory, + Action<object, DataReceivedEventArgs> stdOutAction, + Action<object, DataReceivedEventArgs> stdErrAction, + bool updateProcessPath, + bool allowUseWindow, + bool waitForExit) + => ExecuteStatic(process, arguments, waitForExitInSeconds, workingDirectory, stdOutAction, stdErrAction, updateProcessPath, allowUseWindow, waitForExit); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + private static void log_output(object sender, DataReceivedEventArgs e) + => LogOutput(sender, e); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + private static void log_error(object sender, DataReceivedEventArgs e) + => LogError(sender, e); +#pragma warning restore IDE1006 } } diff --git a/src/chocolatey/infrastructure/commands/Execute.cs b/src/chocolatey/infrastructure/commands/Execute.cs index 5a5a4cfec1..1fe7040763 100644 --- a/src/chocolatey/infrastructure/commands/Execute.cs +++ b/src/chocolatey/infrastructure/commands/Execute.cs @@ -33,7 +33,7 @@ public sealed class Execute /// </summary> /// <param name="timeoutInSeconds">The timeout in seconds.</param> /// <returns></returns> - public static Execute with_timeout(int timeoutInSeconds) + public static Execute WithTimeout(int timeoutInSeconds) { return new Execute(TimeSpan.FromSeconds(timeoutInSeconds)); } @@ -43,7 +43,7 @@ public static Execute with_timeout(int timeoutInSeconds) /// </summary> /// <param name="timeout">The timeout.</param> /// <returns></returns> - public static Execute with_timeout(TimeSpan timeout) + public static Execute WithTimeout(TimeSpan timeout) { return new Execute(timeout); } @@ -60,7 +60,7 @@ private Execute(TimeSpan timespan) /// <param name="function">The function to execute.</param> /// <param name="timeoutDefaultValue">The timeout default value.</param> /// <returns>The results of the function if completes within timespan, otherwise returns the default value.</returns> - public T command<T>(Func<T> function, T timeoutDefaultValue) + public T Command<T>(Func<T> function, T timeoutDefaultValue) { if (function == null) return timeoutDefaultValue; @@ -83,7 +83,7 @@ public T command<T>(Func<T> function, T timeoutDefaultValue) cancelToken.Cancel(); this.Log().Warn(ChocolateyLoggers.Important,() => @"Chocolatey timed out waiting for the command to finish. The timeout specified (or the default value) was '{0}' seconds. Perhaps try a - higher `--execution-timeout`? See `choco -h` for details.".format_with(_timespan.TotalSeconds)); + higher `--execution-timeout`? See `choco -h` for details.".FormatWith(_timespan.TotalSeconds)); return timeoutDefaultValue; @@ -102,7 +102,7 @@ public T command<T>(Func<T> function, T timeoutDefaultValue) /// </summary> /// <param name="action">The action to perform.</param> /// <returns>True if it finishes executing, false otherwise.</returns> - public bool command(Action action) + public bool Command(Action action) { if (action == null) return false; @@ -128,11 +128,29 @@ public bool command(Action action) cancelToken.Cancel(); this.Log().Warn(ChocolateyLoggers.Important, () => @"Chocolatey timed out waiting for the command to finish. The timeout specified (or the default value) was '{0}' seconds. Perhaps try a - higher `--execution-timeout`? See `choco -h` for details.".format_with(_timespan.TotalSeconds)); + higher `--execution-timeout`? See `choco -h` for details.".FormatWith(_timespan.TotalSeconds)); } return completed; } + +#pragma warning disable IDE1006 + [Obsolete("This overload is deprecated and will be removed in v3.")] + public static Execute with_timeout(int timeoutInSeconds) + => WithTimeout(timeoutInSeconds); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public static Execute with_timeout(TimeSpan timeout) + => WithTimeout(timeout); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public T command<T>(Func<T> function, T timeoutDefaultValue) + => Command(function, timeoutDefaultValue); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public bool command(Action action) + => Command(action); +#pragma warning restore IDE1006 } } diff --git a/src/chocolatey/infrastructure/commands/ExternalCommandArgsBuilder.cs b/src/chocolatey/infrastructure/commands/ExternalCommandArgsBuilder.cs index e1c3cc2d3e..b018331af5 100644 --- a/src/chocolatey/infrastructure/commands/ExternalCommandArgsBuilder.cs +++ b/src/chocolatey/infrastructure/commands/ExternalCommandArgsBuilder.cs @@ -32,12 +32,12 @@ public static class ExternalCommandArgsBuilder /// <param name="properties">The properties object. Public properties are inspected for names and values based on exact matches in the configToArgNames dictionary.</param> /// <param name="configToArgNames">Dictionary of external commands set in the exact order in which you want to get back arguments. Keys should match exactly (casing as well) with the property names of the properties object.</param> /// <returns>A string containing the arguments merged from the configToArgNames dictionary and the properties object.</returns> - public static string build_arguments(object properties, IDictionary<string, ExternalCommandArgument> configToArgNames) + public static string BuildArguments(object properties, IDictionary<string, ExternalCommandArgument> configToArgNames) { var arguments = new StringBuilder(); var propValues = new Dictionary<string, string>(StringComparer.InvariantCultureIgnoreCase); - fill_args_dictionary(propValues, properties.GetType().GetProperties(), configToArgNames, properties, ""); + FillArgsDictionary(propValues, properties.GetType().GetProperties(), configToArgNames, properties, ""); foreach (var arg in configToArgNames) { @@ -49,7 +49,7 @@ public static string build_arguments(object properties, IDictionary<string, Exte { if (arg.Value.Required) { - var argValue = quote_arg_value_if_required(arg.Value).wrap_spaces_in_quotes(); + var argValue = QuoteArgumentValueIfRequired(arg.Value).QuoteIfContainsSpaces(); if (arg.Value.UseValueOnly) { @@ -67,16 +67,16 @@ public static string build_arguments(object properties, IDictionary<string, Exte return arguments.Remove(arguments.Length - 1, 1).ToString(); } - private static void fill_args_dictionary(Dictionary<string, string> propertyValues, IEnumerable<PropertyInfo> properties, IDictionary<string, ExternalCommandArgument> configToArgNames, object obj, string prepend) + private static void FillArgsDictionary(Dictionary<string, string> propertyValues, IEnumerable<PropertyInfo> properties, IDictionary<string, ExternalCommandArgument> configToArgNames, object obj, string prepend) { - foreach (var prop in properties.or_empty_list_if_null()) + foreach (var prop in properties.OrEmpty()) { //todo: #2587 need a better way of handling if (prop.Name == "MachineSources") continue; - if (prop.PropertyType.is_built_in_system_type()) + if (prop.PropertyType.IsBuiltinType()) { - var propName = "{0}{1}".format_with( + var propName = "{0}{1}".FormatWith( string.IsNullOrWhiteSpace(prepend) ? "" : prepend + ".", prop.Name ); @@ -85,8 +85,8 @@ private static void fill_args_dictionary(Dictionary<string, string> propertyValu { var arg = configToArgNames[propName]; var propType = prop.PropertyType; - var propValue = prop.GetValue(obj, null).to_string().wrap_spaces_in_quotes(); - if (propType == typeof (Boolean) && propValue.is_equal_to(bool.FalseString)) + var propValue = prop.GetValue(obj, null).ToStringSafe().QuoteIfContainsSpaces(); + if (propType == typeof (Boolean) && propValue.IsEqualTo(bool.FalseString)) { continue; } @@ -104,26 +104,40 @@ private static void fill_args_dictionary(Dictionary<string, string> propertyValu propertyValues.Add( propName, arg.UseValueOnly - ? "{0}".format_with(quote_arg_value_if_required(arg)) - : "{0}{1}".format_with(arg.ArgumentOption, quote_arg_value_if_required(arg)) + ? "{0}".FormatWith(QuoteArgumentValueIfRequired(arg)) + : "{0}{1}".FormatWith(arg.ArgumentOption, QuoteArgumentValueIfRequired(arg)) ); } } else { - fill_args_dictionary(propertyValues, prop.PropertyType.GetProperties(), configToArgNames, prop.GetValue(obj, null), prop.Name); + FillArgsDictionary(propertyValues, prop.PropertyType.GetProperties(), configToArgNames, prop.GetValue(obj, null), prop.Name); } } } - private static string quote_arg_value_if_required(ExternalCommandArgument argument) + private static string QuoteArgumentValueIfRequired(ExternalCommandArgument argument) { if (argument.QuoteValue && !argument.ArgumentValue.StartsWith("\"")) { - return "\"{0}\"".format_with(argument.ArgumentValue); + return "\"{0}\"".FormatWith(argument.ArgumentValue); } return argument.ArgumentValue; } + +#pragma warning disable IDE1006 + [Obsolete("This overload is deprecated and will be removed in v3.")] + public static string build_arguments(object properties, IDictionary<string, ExternalCommandArgument> configToArgNames) + => BuildArguments(properties, configToArgNames); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + private static void fill_args_dictionary(Dictionary<string, string> propertyValues, IEnumerable<PropertyInfo> properties, IDictionary<string, ExternalCommandArgument> configToArgNames, object obj, string prepend) + => FillArgsDictionary(propertyValues, properties, configToArgNames, obj, prepend); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + private static string quote_arg_value_if_required(ExternalCommandArgument argument) + => QuoteArgumentValueIfRequired(argument); +#pragma warning restore IDE1006 } } diff --git a/src/chocolatey/infrastructure/commands/ICommand.cs b/src/chocolatey/infrastructure/commands/ICommand.cs index 125e93bad1..3c62b649aa 100644 --- a/src/chocolatey/infrastructure/commands/ICommand.cs +++ b/src/chocolatey/infrastructure/commands/ICommand.cs @@ -16,6 +16,7 @@ namespace chocolatey.infrastructure.commands { + using System; using System.Collections.Generic; using app.configuration; using commandline; @@ -30,39 +31,62 @@ public interface ICommand /// </summary> /// <param name="optionSet">The option set.</param> /// <param name="configuration">The configuration.</param> - void configure_argument_parser(OptionSet optionSet, ChocolateyConfiguration configuration); + void ConfigureArgumentParser(OptionSet optionSet, ChocolateyConfiguration configuration); /// <summary> /// Handle the arguments that were not parsed by the argument parser and/or do additional parsing work /// </summary> /// <param name="unparsedArguments">The unparsed arguments.</param> /// <param name="configuration">The configuration.</param> - void handle_additional_argument_parsing(IList<string> unparsedArguments, ChocolateyConfiguration configuration); + void ParseAdditionalArguments(IList<string> unparsedArguments, ChocolateyConfiguration configuration); - void handle_validation(ChocolateyConfiguration configuration); + void Validate(ChocolateyConfiguration configuration); /// <summary> /// The specific help message for a particular command. /// </summary> /// <param name="configuration">The configuration.</param> - void help_message(ChocolateyConfiguration configuration); + void HelpMessage(ChocolateyConfiguration configuration); /// <summary> /// Runs in no op mode, which means it doesn't actually make any changes. /// </summary> /// <param name="configuration">The configuration.</param> - void noop(ChocolateyConfiguration configuration); + void DryRun(ChocolateyConfiguration configuration); /// <summary> /// Runs the command. /// </summary> /// <param name="config">The configuration.</param> - void run(ChocolateyConfiguration config); + void Run(ChocolateyConfiguration config); /// <summary> /// This command may require admin rights /// </summary> /// <returns></returns> + bool MayRequireAdminAccess(); + +#pragma warning disable IDE1006 + [Obsolete("This overload is deprecated and will be removed in v3.")] + void configure_argument_parser(OptionSet optionSet, ChocolateyConfiguration configuration); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + void handle_additional_argument_parsing(IList<string> unparsedArguments, ChocolateyConfiguration configuration); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + void handle_validation(ChocolateyConfiguration configuration); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + void help_message(ChocolateyConfiguration configuration); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + void noop(ChocolateyConfiguration configuration); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + void run(ChocolateyConfiguration config); + + [Obsolete("This overload is deprecated and will be removed in v3.")] bool may_require_admin_access(); +#pragma warning restore IDE1006 } } diff --git a/src/chocolatey/infrastructure/commands/ICommandExecutor.cs b/src/chocolatey/infrastructure/commands/ICommandExecutor.cs index 00e4c393db..276f4b0ac3 100644 --- a/src/chocolatey/infrastructure/commands/ICommandExecutor.cs +++ b/src/chocolatey/infrastructure/commands/ICommandExecutor.cs @@ -21,9 +21,49 @@ namespace chocolatey.infrastructure.commands public interface ICommandExecutor { + int Execute(string process, string arguments, int waitForExitInSeconds); + int Execute(string process, string arguments, int waitForExitInSeconds, string workingDirectory); + + int Execute( + string process, + string arguments, + int waitForExitInSeconds, + Action<object, DataReceivedEventArgs> stdOutAction, + Action<object, DataReceivedEventArgs> stdErrAction, + bool updateProcessPath + ); + + int Execute( + string process, + string arguments, + int waitForExitInSeconds, + string workingDirectory, + Action<object, DataReceivedEventArgs> stdOutAction, + Action<object, DataReceivedEventArgs> stdErrAction, + bool updateProcessPath, + bool allowUseWindow + ); + + int Execute( + string process, + string arguments, + int waitForExitInSeconds, + string workingDirectory, + Action<object, DataReceivedEventArgs> stdOutAction, + Action<object, DataReceivedEventArgs> stdErrAction, + bool updateProcessPath, + bool allowUseWindow, + bool waitForExit + ); + +#pragma warning disable IDE1006 + [Obsolete("This overload is deprecated and will be removed in v3.")] int execute(string process, string arguments, int waitForExitInSeconds); + + [Obsolete("This overload is deprecated and will be removed in v3.")] int execute(string process, string arguments, int waitForExitInSeconds, string workingDirectory); + [Obsolete("This overload is deprecated and will be removed in v3.")] int execute( string process, string arguments, @@ -32,7 +72,7 @@ int execute( Action<object, DataReceivedEventArgs> stdErrAction, bool updateProcessPath ); - + [Obsolete("This overload is deprecated and will be removed in v3.")] int execute( string process, string arguments, @@ -44,6 +84,7 @@ int execute( bool allowUseWindow ); + [Obsolete("This overload is deprecated and will be removed in v3.")] int execute( string process, string arguments, @@ -55,5 +96,6 @@ int execute( bool allowUseWindow, bool waitForExit ); +#pragma warning restore IDE1006 } } diff --git a/src/chocolatey/infrastructure/commands/IListCommand.cs b/src/chocolatey/infrastructure/commands/IListCommand.cs index 871900318e..33de9cc57c 100644 --- a/src/chocolatey/infrastructure/commands/IListCommand.cs +++ b/src/chocolatey/infrastructure/commands/IListCommand.cs @@ -16,16 +16,27 @@ namespace chocolatey.infrastructure.commands { + using System; using System.Collections.Generic; using app.configuration; public interface IListCommand : ICommand { + int Count(ChocolateyConfiguration config); + +#pragma warning disable IDE1006 + [Obsolete("This overload is deprecated and will be removed in v3.")] int count(ChocolateyConfiguration config); +#pragma warning restore IDE1006 } public interface IListCommand<out T> : IListCommand { + IEnumerable<T> List(ChocolateyConfiguration config); + +#pragma warning disable IDE1006 + [Obsolete("This overload is deprecated and will be removed in v3.")] IEnumerable<T> list(ChocolateyConfiguration config); +#pragma warning restore IDE1006 } } diff --git a/src/chocolatey/infrastructure/commands/PowershellExecutor.cs b/src/chocolatey/infrastructure/commands/PowershellExecutor.cs index 17fe5de40b..392e60be3f 100644 --- a/src/chocolatey/infrastructure/commands/PowershellExecutor.cs +++ b/src/chocolatey/infrastructure/commands/PowershellExecutor.cs @@ -45,7 +45,7 @@ public static bool AllowUseWindow private static string _powershell = string.Empty; - public static int execute( + public static int Execute( string command, IFileSystem fileSystem, int waitForExitSeconds, @@ -53,15 +53,15 @@ public static int execute( Action<object, DataReceivedEventArgs> stdErrAction ) { - if (string.IsNullOrWhiteSpace(_powershell)) _powershell = get_powershell_location(fileSystem); + if (string.IsNullOrWhiteSpace(_powershell)) _powershell = GetPowerShellLocation(fileSystem); //-NoProfile -NoLogo -ExecutionPolicy unrestricted -Command "[System.Threading.Thread]::CurrentThread.CurrentCulture = ''; [System.Threading.Thread]::CurrentThread.CurrentUICulture = '';& '%DIR%chocolatey.ps1' %PS_ARGS%" - string arguments = "-NoProfile -NoLogo -ExecutionPolicy Bypass -Command \"{0}\"".format_with(command); + string arguments = "-NoProfile -NoLogo -ExecutionPolicy Bypass -Command \"{0}\"".FormatWith(command); - return CommandExecutor.execute_static( + return CommandExecutor.ExecuteStatic( _powershell, arguments, waitForExitSeconds, - workingDirectory: fileSystem.get_directory_name(fileSystem.get_current_assembly_path()), + workingDirectory: fileSystem.GetDirectoryName(fileSystem.GetCurrentAssemblyPath()), stdOutAction: stdOutAction, stdErrAction: stdErrAction, updateProcessPath: true, @@ -69,17 +69,32 @@ Action<object, DataReceivedEventArgs> stdErrAction ); } - public static string get_powershell_location(IFileSystem fileSystem) + public static string GetPowerShellLocation(IFileSystem fileSystem) { foreach (var powershellLocation in _powershellLocations) { - if (fileSystem.file_exists(powershellLocation)) + if (fileSystem.FileExists(powershellLocation)) { return powershellLocation; } } - throw new FileNotFoundException("Unable to find suitable location for PowerShell. Searched the following locations: '{0}'".format_with(string.Join("; ", _powershellLocations))); + throw new FileNotFoundException("Unable to find suitable location for PowerShell. Searched the following locations: '{0}'".FormatWith(string.Join("; ", _powershellLocations))); } + +#pragma warning disable IDE1006 + [Obsolete("This overload is deprecated and will be removed in v3.")] + public static int execute( + string command, + IFileSystem fileSystem, + int waitForExitSeconds, + Action<object, DataReceivedEventArgs> stdOutAction, + Action<object, DataReceivedEventArgs> stdErrAction) + => Execute(command, fileSystem, waitForExitSeconds, stdOutAction, stdErrAction); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public static string get_powershell_location(IFileSystem fileSystem) + => GetPowerShellLocation(fileSystem); +#pragma warning restore IDE1006 } } diff --git a/src/chocolatey/infrastructure/configuration/Config.cs b/src/chocolatey/infrastructure/configuration/Config.cs index ccf56fd703..dd2b47b2ac 100644 --- a/src/chocolatey/infrastructure/configuration/Config.cs +++ b/src/chocolatey/infrastructure/configuration/Config.cs @@ -16,6 +16,7 @@ namespace chocolatey.infrastructure.configuration { + using System; using System.ComponentModel; using app.configuration; @@ -32,7 +33,7 @@ public sealed class Config /// </summary> /// <param name="configuration">The configuration.</param> [EditorBrowsable(EditorBrowsableState.Never)] - public static void initialize_with(ChocolateyConfiguration configuration) + public static void InitializeWith(ChocolateyConfiguration configuration) { _configuration = configuration; } @@ -47,9 +48,19 @@ public static void initialize_with(ChocolateyConfiguration configuration) /// cref="ChocolateyConfiguration" /> /// if one has not been. /// </returns> - public static ChocolateyConfiguration get_configuration_settings() + public static ChocolateyConfiguration GetConfigurationSettings() { return _configuration; } + +#pragma warning disable IDE1006 + [Obsolete("This overload is deprecated and will be removed in v3.")] + public static void initialize_with(ChocolateyConfiguration configuration) + => InitializeWith(configuration); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public static ChocolateyConfiguration get_configuration_settings() + => GetConfigurationSettings(); +#pragma warning restore IDE1006 } } diff --git a/src/chocolatey/infrastructure/cryptography/CryptoHashProvider.cs b/src/chocolatey/infrastructure/cryptography/CryptoHashProvider.cs index 81ac8f04df..a88e0bc929 100644 --- a/src/chocolatey/infrastructure/cryptography/CryptoHashProvider.cs +++ b/src/chocolatey/infrastructure/cryptography/CryptoHashProvider.cs @@ -27,19 +27,19 @@ namespace chocolatey.infrastructure.cryptography using Environment = System.Environment; using HashAlgorithm = adapters.HashAlgorithm; - public sealed class CryptoHashProvider : IHashProvider + public class CryptoHashProvider : IHashProvider { private readonly IFileSystem _fileSystem; private IHashAlgorithm _hashAlgorithm; - private const int ERROR_LOCK_VIOLATION = 33; - private const int ERROR_SHARING_VIOLATION = 32; + private const int ErrorLockViolation = 33; + private const int ErrorSharingViolation = 32; - public void set_hash_algorithm(CryptoHashProviderType algorithmType) + public void SetHashAlgorithm(CryptoHashProviderType algorithmType) { - _hashAlgorithm = get_hash_algorithm_static(algorithmType); + _hashAlgorithm = GetHashAlgorithmStatic(algorithmType); } - private static IHashAlgorithm get_hash_algorithm_static(CryptoHashProviderType algorithmType) + private static IHashAlgorithm GetHashAlgorithmStatic(CryptoHashProviderType algorithmType) { var fipsOnly = false; @@ -49,7 +49,7 @@ private static IHashAlgorithm get_hash_algorithm_static(CryptoHashProviderType a } catch (Exception ex) { - "chocolatey".Log().Debug("Unable to get FipsPolicy from CryptoConfig:{0} {1}".format_with(Environment.NewLine, ex.Message)); + "chocolatey".Log().Debug("Unable to get FipsPolicy from CryptoConfig:{0} {1}".FormatWith(Environment.NewLine, ex.Message)); } HashAlgorithm hashAlgorithm = null; @@ -75,7 +75,7 @@ private static IHashAlgorithm get_hash_algorithm_static(CryptoHashProviderType a public CryptoHashProvider(IFileSystem fileSystem) { _fileSystem = fileSystem; - set_hash_algorithm(CryptoHashProviderType.Sha256); + SetHashAlgorithm(CryptoHashProviderType.Sha256); } public CryptoHashProvider(IFileSystem fileSystem, IHashAlgorithm hashAlgorithm) @@ -84,21 +84,21 @@ public CryptoHashProvider(IFileSystem fileSystem, IHashAlgorithm hashAlgorithm) _hashAlgorithm = hashAlgorithm; } - public string hash_file(string filePath) + public string ComputeFileHash(string filePath) { - if (!_fileSystem.file_exists(filePath)) return string.Empty; + if (!_fileSystem.FileExists(filePath)) return string.Empty; try { - var hash = _hashAlgorithm.ComputeHash(_fileSystem.read_file_bytes(filePath)); + var hash = _hashAlgorithm.ComputeHash(_fileSystem.ReadFileBytes(filePath)); return BitConverter.ToString(hash).Replace("-", string.Empty); } catch (IOException ex) { - this.Log().Warn(() => "Error computing hash for '{0}'{1} Hash will be special code for locked file or file too big instead.{1} Captured error:{1} {2}".format_with(filePath, Environment.NewLine, ex.Message)); + this.Log().Warn(() => "Error computing hash for '{0}'{1} Hash will be special code for locked file or file too big instead.{1} Captured error:{1} {2}".FormatWith(filePath, Environment.NewLine, ex.Message)); - if (file_is_locked(ex)) + if (IsFileLocked(ex)) { return ApplicationParameters.HashProviderFileLocked; } @@ -108,21 +108,21 @@ public string hash_file(string filePath) } } - public string hash_byte_array(byte[] buffer) + public string ComputeByteArrayHash(byte[] buffer) { var hash = _hashAlgorithm.ComputeHash(buffer); return BitConverter.ToString(hash).Replace("-", string.Empty); } - public string hash_stream(Stream inputStream) + public string ComputeStreamHash(Stream inputStream) { var hash = _hashAlgorithm.ComputeHash(inputStream); return BitConverter.ToString(hash).Replace("-", string.Empty); } - private static bool file_is_locked(Exception exception) + private static bool IsFileLocked(Exception exception) { var errorCode = 0; @@ -130,18 +130,46 @@ private static bool file_is_locked(Exception exception) errorCode = hresult & ((1 << 16) - 1); - return errorCode == ERROR_SHARING_VIOLATION || errorCode == ERROR_LOCK_VIOLATION; + return errorCode == ErrorSharingViolation || errorCode == ErrorLockViolation; } - public static string hash_value(string originalText, CryptoHashProviderType providerType) + public static string ComputeStringHash(string originalText, CryptoHashProviderType providerType) { - - IHashAlgorithm hashAlgorithm = get_hash_algorithm_static(providerType); + IHashAlgorithm hashAlgorithm = GetHashAlgorithmStatic(providerType); if (hashAlgorithm == null) return string.Empty; var hash = hashAlgorithm.ComputeHash(Encoding.ASCII.GetBytes(originalText)); return BitConverter.ToString(hash).Replace("-", string.Empty); } +#pragma warning disable IDE1006 + [Obsolete("This overload is deprecated and will be removed in v3.")] + public void set_hash_algorithm(CryptoHashProviderType algorithmType) + => SetHashAlgorithm(algorithmType); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + private static IHashAlgorithm get_hash_algorithm_static(CryptoHashProviderType algorithmType) + => GetHashAlgorithmStatic(algorithmType); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public string hash_file(string filePath) + => ComputeFileHash(filePath); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public string hash_byte_array(byte[] buffer) + => ComputeByteArrayHash(buffer); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public string hash_stream(Stream inputStream) + => ComputeStreamHash(inputStream); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + private static bool file_is_locked(Exception exception) + => IsFileLocked(exception); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public static string hash_value(string originalText, CryptoHashProviderType providerType) + => ComputeStringHash(originalText, providerType); +#pragma warning restore IDE1006 } } diff --git a/src/chocolatey/infrastructure/cryptography/DefaultEncryptionUtility.cs b/src/chocolatey/infrastructure/cryptography/DefaultEncryptionUtility.cs index 71c8286c3e..f00f261159 100644 --- a/src/chocolatey/infrastructure/cryptography/DefaultEncryptionUtility.cs +++ b/src/chocolatey/infrastructure/cryptography/DefaultEncryptionUtility.cs @@ -26,7 +26,7 @@ public class DefaultEncryptionUtility : IEncryptionUtility { private readonly byte[] _entropyBytes = Encoding.UTF8.GetBytes("Chocolatey"); - public string encrypt_string(string cleartextValue) + public string EncryptString(string cleartextValue) { if (string.IsNullOrWhiteSpace(cleartextValue)) return null; @@ -38,7 +38,7 @@ public string encrypt_string(string cleartextValue) } catch (Exception ex) { - if (Platform.get_platform() != PlatformType.Windows && ex is CryptographicException) + if (Platform.GetPlatform() != PlatformType.Windows && ex is CryptographicException) { this.Log().Warn(@"Could not encrypt with LocalMachine scope. Falling back to CurrentUser scope for encryption. @@ -56,7 +56,7 @@ This is can be because the machine keyfile cannot be written as a normal user. return encryptedString; } - public string decrypt_string(string encryptedString) + public string DecryptString(string encryptedString) { var encryptedByteArray = Convert.FromBase64String(encryptedString); byte[] decryptedByteArray; @@ -67,7 +67,7 @@ public string decrypt_string(string encryptedString) } catch (Exception ex) { - if (Platform.get_platform() != PlatformType.Windows && ex is CryptographicException) + if (Platform.GetPlatform() != PlatformType.Windows && ex is CryptographicException) { this.Log().Warn(@"Could not decrypt with LocalMachine scope. Falling back to CurrentUser scope for decryption. @@ -83,13 +83,27 @@ public string decrypt_string(string encryptedString) return Encoding.UTF8.GetString(decryptedByteArray); } - public string generate_unique_token(string caseInsensitiveKey) + public string GenerateUniqueToken(string caseInsensitiveKey) { // SHA256 is case sensitive; given that our key is case insensitive, we upper case it var pathBytes = Encoding.UTF8.GetBytes(caseInsensitiveKey.ToUpperInvariant()); - var hashProvider = new NuGet.Common.CryptoHashProvider("SHA256"); + var hashProvider = new global::NuGet.Common.CryptoHashProvider("SHA256"); return Convert.ToBase64String(hashProvider.CalculateHash(pathBytes)).ToUpperInvariant(); } + +#pragma warning disable IDE1006 + [Obsolete("This overload is deprecated and will be removed in v3.")] + public string encrypt_string(string cleartextValue) + => EncryptString(cleartextValue); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public string decrypt_string(string encryptedString) + => DecryptString(encryptedString); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public string generate_unique_token(string caseInsensitiveKey) + => GenerateUniqueToken(caseInsensitiveKey); +#pragma warning restore IDE1006 } } diff --git a/src/chocolatey/infrastructure/cryptography/IHashProvider.cs b/src/chocolatey/infrastructure/cryptography/IHashProvider.cs index 9ca6221e78..16e18175f8 100644 --- a/src/chocolatey/infrastructure/cryptography/IHashProvider.cs +++ b/src/chocolatey/infrastructure/cryptography/IHashProvider.cs @@ -14,6 +14,7 @@ // See the License for the specific language governing permissions and // limitations under the License. +using System; using System.IO; namespace chocolatey.infrastructure.cryptography @@ -27,27 +28,41 @@ public interface IHashProvider /// Changes the algorithm /// </summary> /// <param name="algorithmType">Type of the algorithm.</param> - void set_hash_algorithm(CryptoHashProviderType algorithmType); + void SetHashAlgorithm(CryptoHashProviderType algorithmType); /// <summary> /// Returns a hash of the specified file path. /// </summary> /// <param name="filePath">The file path.</param> /// <returns>A computed hash of the file, based on the contents.</returns> - string hash_file(string filePath); + string ComputeFileHash(string filePath); /// <summary> /// Returns a hash of the specified stream. /// </summary> /// <param name="inputStream">The stream.</param> /// <returns>A computed hash of the stream, based on the contents.</returns> - string hash_stream(Stream inputStream); + string ComputeStreamHash(Stream inputStream); /// <summary> /// Returns a hash of the specified byte array. /// </summary> /// <param name="buffer">The byte array.</param> /// <returns>A computed hash of the array, based on the contents.</returns> + string ComputeByteArrayHash(byte[] buffer); + +#pragma warning disable IDE1006 + [Obsolete("This overload is deprecated and will be removed in v3.")] + void set_hash_algorithm(CryptoHashProviderType algorithmType); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + string hash_file(string filePath); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + string hash_stream(Stream inputStream); + + [Obsolete("This overload is deprecated and will be removed in v3.")] string hash_byte_array(byte[] buffer); +#pragma warning restore IDE1006 } } diff --git a/src/chocolatey/infrastructure/events/EventManager.cs b/src/chocolatey/infrastructure/events/EventManager.cs index 8c59315c4e..6323dd5f3e 100644 --- a/src/chocolatey/infrastructure/events/EventManager.cs +++ b/src/chocolatey/infrastructure/events/EventManager.cs @@ -29,7 +29,7 @@ public static class EventManager /// </summary> /// <param name="messageSubscriptionManager">The message subscription manager.</param> [EditorBrowsable(EditorBrowsableState.Never)] - public static void initialize_with(Func<IEventSubscriptionManagerService> messageSubscriptionManager) + public static void InitializeWith(Func<IEventSubscriptionManagerService> messageSubscriptionManager) { _messageSubscriptionManager = messageSubscriptionManager; } @@ -50,11 +50,11 @@ public static IEventSubscriptionManagerService ManagerService /// </summary> /// <typeparam name="Event">The type of the event.</typeparam> /// <param name="message">The message.</param> - public static void publish<Event>(Event message) where Event : class, IMessage + public static void Publish<Event>(Event message) where Event : class, IMessage { if (_messageSubscriptionManager != null) { - _messageSubscriptionManager().publish(message); + _messageSubscriptionManager().Publish(message); } } @@ -66,14 +66,28 @@ public static void publish<Event>(Event message) where Event : class, IMessage /// <param name="handleError">The handle error.</param> /// <param name="filter">The filter.</param> /// <returns>The subscription so that a service could unsubscribe</returns> - public static IDisposable subscribe<Event>(Action<Event> handleEvent, Action<Exception> handleError, Func<Event, bool> filter) where Event : class, IMessage + public static IDisposable Subscribe<Event>(Action<Event> handleEvent, Action<Exception> handleError, Func<Event, bool> filter) where Event : class, IMessage { if (_messageSubscriptionManager != null) { - return _messageSubscriptionManager().subscribe(handleEvent, handleError, filter); + return _messageSubscriptionManager().Subscribe(handleEvent, handleError, filter); } return null; } + +#pragma warning disable IDE1006 + [Obsolete("This overload is deprecated and will be removed in v3.")] + public static void initialize_with(Func<IEventSubscriptionManagerService> messageSubscriptionManager) + => InitializeWith(messageSubscriptionManager); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public static void publish<Event>(Event message) where Event : class, IMessage + => Publish(message); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public static IDisposable subscribe<Event>(Action<Event> handleEvent, Action<Exception> handleError, Func<Event, bool> filter) where Event : class, IMessage + => Subscribe(handleEvent,handleError, filter); +#pragma warning restore IDE1006 } } diff --git a/src/chocolatey/infrastructure/extractors/AssemblyFileExtractor.cs b/src/chocolatey/infrastructure/extractors/AssemblyFileExtractor.cs index e893825aa8..baec02c18d 100644 --- a/src/chocolatey/infrastructure/extractors/AssemblyFileExtractor.cs +++ b/src/chocolatey/infrastructure/extractors/AssemblyFileExtractor.cs @@ -16,6 +16,7 @@ namespace chocolatey.infrastructure.extractors { + using System; using System.Collections.Generic; using System.IO; using System.Text; @@ -39,20 +40,20 @@ public static class AssemblyFileExtractor /// if set to <c>true</c> [overwrite existing]. /// </param> /// <exception cref="System.IO.FileNotFoundException"></exception> - public static void extract_text_file_from_assembly(IFileSystem fileSystem, IAssembly assembly, string manifestLocation, string filePath, bool overwriteExisting = false) + public static void ExtractTextFileFromAssembly(IFileSystem fileSystem, IAssembly assembly, string manifestLocation, string filePath, bool overwriteExisting = false) { - if (overwriteExisting || !fileSystem.file_exists(filePath)) + if (overwriteExisting || !fileSystem.FileExists(filePath)) { - fileSystem.create_directory_if_not_exists(fileSystem.get_directory_name(filePath)); - var fileText = assembly.get_manifest_string(manifestLocation); + fileSystem.EnsureDirectoryExists(fileSystem.GetDirectoryName(filePath)); + var fileText = assembly.GetManifestString(manifestLocation); if (string.IsNullOrWhiteSpace(fileText)) { - string errorMessage = "Could not find a file in the manifest resource stream of '{0}' at '{1}'.".format_with(assembly.FullName, manifestLocation); + string errorMessage = "Could not find a file in the manifest resource stream of '{0}' at '{1}'.".FormatWith(assembly.FullName, manifestLocation); "chocolatey".Log().Error(() => errorMessage); throw new FileNotFoundException(errorMessage); } - fileSystem.write_file(filePath, fileText, Encoding.UTF8); + fileSystem.WriteFile(filePath, fileText, Encoding.UTF8); } } @@ -67,15 +68,15 @@ public static void extract_text_file_from_assembly(IFileSystem fileSystem, IAsse /// if set to <c>true</c> [overwrite existing]. /// </param> /// <param name="throwError">Throw an error if there are issues</param> - public static void extract_binary_file_from_assembly(IFileSystem fileSystem, IAssembly assembly, string manifestLocation, string filePath, bool overwriteExisting = false, bool throwError = true) + public static void ExtractBinaryFileFromAssembly(IFileSystem fileSystem, IAssembly assembly, string manifestLocation, string filePath, bool overwriteExisting = false, bool throwError = true) { - if (overwriteExisting || !fileSystem.file_exists(filePath)) + if (overwriteExisting || !fileSystem.FileExists(filePath)) { - FaultTolerance.try_catch_with_logging_exception( + FaultTolerance.TryCatchWithLoggingException( () => { - fileSystem.create_directory_if_not_exists(fileSystem.get_directory_name(filePath)); - fileSystem.write_file(filePath, () => assembly.get_manifest_stream(manifestLocation)); + fileSystem.EnsureDirectoryExists(fileSystem.GetDirectoryName(filePath)); + fileSystem.WriteFile(filePath, () => assembly.GetManifestStream(manifestLocation)); }, errorMessage:"Unable to extract binary", throwError: throwError, @@ -85,7 +86,7 @@ public static void extract_binary_file_from_assembly(IFileSystem fileSystem, IAs } } - public static void extract_all_resources_to_relative_directory(IFileSystem fileSystem, IAssembly assembly, string directoryPath, IList<string> relativeDirectories, string resourcesToInclude, bool overwriteExisting = false, bool logOutput = false, bool throwError = true) + public static void ExtractAssemblyResourcesToRelativeDirectory(IFileSystem fileSystem, IAssembly assembly, string directoryPath, IList<string> relativeDirectories, string resourcesToInclude, bool overwriteExisting = false, bool logOutput = false, bool throwError = true) { var resourceString = new StringBuilder(); foreach (var resourceName in assembly.GetManifestResourceNames()) @@ -102,19 +103,33 @@ public static void extract_all_resources_to_relative_directory(IFileSystem fileS resourceString.Replace(resourcesToInclude + ".", ""); foreach (var directory in relativeDirectories) { - resourceString.Replace("{0}".format_with(directory), "{0}{1}".format_with(directory, fileSystem.get_path_directory_separator_char())); + resourceString.Replace("{0}".FormatWith(directory), "{0}{1}".FormatWith(directory, fileSystem.GetPathDirectorySeparatorChar())); } // replacing \. with \ - resourceString.Replace("{0}.".format_with(fileSystem.get_path_directory_separator_char()), "{0}".format_with(fileSystem.get_path_directory_separator_char())); + resourceString.Replace("{0}.".FormatWith(fileSystem.GetPathDirectorySeparatorChar()), "{0}".FormatWith(fileSystem.GetPathDirectorySeparatorChar())); var fileLocation = resourceString.ToString(); //var fileLocation = fileSystem.combine_paths("", resourceString.ToString().Split('.')) + resourceName.Substring(fileExtensionLocation); - var filePath = fileSystem.combine_paths(directoryPath, fileLocation); - if (logOutput) "chocolatey".Log().Debug("Unpacking {0} to '{1}'".format_with(fileLocation, filePath)); - extract_binary_file_from_assembly(fileSystem, assembly, resourceName, filePath, overwriteExisting, throwError); + var filePath = fileSystem.CombinePaths(directoryPath, fileLocation); + if (logOutput) "chocolatey".Log().Debug("Unpacking {0} to '{1}'".FormatWith(fileLocation, filePath)); + ExtractBinaryFileFromAssembly(fileSystem, assembly, resourceName, filePath, overwriteExisting, throwError); } } + +#pragma warning disable IDE1006 + [Obsolete("This overload is deprecated and will be removed in v3.")] + public static void extract_text_file_from_assembly(IFileSystem fileSystem, IAssembly assembly, string manifestLocation, string filePath, bool overwriteExisting = false) + => ExtractTextFileFromAssembly(fileSystem, assembly, manifestLocation, filePath, overwriteExisting); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public static void extract_binary_file_from_assembly(IFileSystem fileSystem, IAssembly assembly, string manifestLocation, string filePath, bool overwriteExisting = false, bool throwError = true) + => ExtractBinaryFileFromAssembly(fileSystem, assembly, manifestLocation, filePath, overwriteExisting, throwError); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public static void extract_all_resources_to_relative_directory(IFileSystem fileSystem, IAssembly assembly, string directoryPath, IList<string> relativeDirectories, string resourcesToInclude, bool overwriteExisting = false, bool logOutput = false, bool throwError = true) + => ExtractAssemblyResourcesToRelativeDirectory(fileSystem, assembly, directoryPath, relativeDirectories, resourcesToInclude, overwriteExisting, logOutput, throwError); +#pragma warning restore IDE1006 } } diff --git a/src/chocolatey/infrastructure/filesystem/DotNetFileSystem.cs b/src/chocolatey/infrastructure/filesystem/DotNetFileSystem.cs index 9824290db3..410b765340 100644 --- a/src/chocolatey/infrastructure/filesystem/DotNetFileSystem.cs +++ b/src/chocolatey/infrastructure/filesystem/DotNetFileSystem.cs @@ -39,15 +39,15 @@ namespace chocolatey.infrastructure.filesystem /// <remarks>Normally we avoid regions, however this has so many methods that we are making an exception.</remarks> public sealed class DotNetFileSystem : IFileSystem { - private readonly int TIMES_TO_TRY_OPERATION = 3; - private static Lazy<IEnvironment> environment_initializer = new Lazy<IEnvironment>(() => new Environment()); - private const int MAX_PATH_FILE = 255; - private const int MAX_PATH_DIRECTORY = 248; + private readonly int _timesToTryOperation = 3; + private static Lazy<IEnvironment> _environmentInitializer = new Lazy<IEnvironment>(() => new Environment()); + private const int MaxPathFile = 255; + private const int MaxPathDirectory = 248; - private void allow_retries(Action action, bool isSilent = false) + private void AllowRetries(Action action, bool isSilent = false) { - FaultTolerance.retry( - TIMES_TO_TRY_OPERATION, + FaultTolerance.Retry( + _timesToTryOperation, action, waitDurationMilliseconds: 200, increaseRetryByMilliseconds: 100, @@ -55,35 +55,35 @@ private void allow_retries(Action action, bool isSilent = false) } [EditorBrowsable(EditorBrowsableState.Never)] - public void initialize_with(Lazy<IEnvironment> environment) + public void InitializeWith(Lazy<IEnvironment> environment) { - environment_initializer = environment; + _environmentInitializer = environment; } private static IEnvironment Environment { - get { return environment_initializer.Value; } + get { return _environmentInitializer.Value; } } #region Path - public string combine_paths(string leftItem, params string[] rightItems) + public string CombinePaths(string leftItem, params string[] rightItems) { if (leftItem == null) { var methodName = string.Empty; var stackFrame = new System.Diagnostics.StackFrame(1); if (stackFrame != null) methodName = stackFrame.GetMethod().Name; - throw new ApplicationException("Path to combine cannot be empty. Tried to combine null with '{0}'.{1}".format_with(string.Join(",", rightItems), string.IsNullOrWhiteSpace(methodName) ? string.Empty : " Method called from '{0}'".format_with(methodName))); + throw new ApplicationException("Path to combine cannot be empty. Tried to combine null with '{0}'.{1}".FormatWith(string.Join(",", rightItems), string.IsNullOrWhiteSpace(methodName) ? string.Empty : " Method called from '{0}'".FormatWith(methodName))); } - var combinedPath = Platform.get_platform() == PlatformType.Windows ? leftItem : leftItem.Replace('\\', '/'); + var combinedPath = Platform.GetPlatform() == PlatformType.Windows ? leftItem : leftItem.Replace('\\', '/'); foreach (var rightItem in rightItems) { - if (rightItem.Contains(":")) throw new ApplicationException("Cannot combine a path with ':' attempted to combine '{0}' with '{1}'".format_with(rightItem, combinedPath)); + if (rightItem.Contains(":")) throw new ApplicationException("Cannot combine a path with ':' attempted to combine '{0}' with '{1}'".FormatWith(rightItem, combinedPath)); - var rightSide = Platform.get_platform() == PlatformType.Windows ? rightItem : rightItem.Replace('\\', '/'); - if (rightSide.StartsWith(Path.DirectorySeparatorChar.to_string()) || rightSide.StartsWith(Path.AltDirectorySeparatorChar.to_string())) + var rightSide = Platform.GetPlatform() == PlatformType.Windows ? rightItem : rightItem.Replace('\\', '/'); + if (rightSide.StartsWith(Path.DirectorySeparatorChar.ToStringSafe()) || rightSide.StartsWith(Path.AltDirectorySeparatorChar.ToStringSafe())) { combinedPath = Path.Combine(combinedPath, rightSide.Substring(1)); } @@ -96,7 +96,7 @@ public string combine_paths(string leftItem, params string[] rightItems) return combinedPath; } - public string get_full_path(string path) + public string GetFullPath(string path) { if (string.IsNullOrWhiteSpace(path)) return path; @@ -110,41 +110,41 @@ public string get_full_path(string path) } } - public string get_temp_path() + public string GetTempPath() { var path = Path.GetTempPath(); - if (System.Environment.UserName.contains(ApplicationParameters.Environment.SystemUserName) || path.contains("config\\systemprofile")) + if (System.Environment.UserName.ContainsSafe(ApplicationParameters.Environment.SystemUserName) || path.ContainsSafe("config\\systemprofile")) { - path = System.Environment.ExpandEnvironmentVariables(System.Environment.GetEnvironmentVariable(ApplicationParameters.Environment.Temp, EnvironmentVariableTarget.Machine).to_string()); + path = System.Environment.ExpandEnvironmentVariables(System.Environment.GetEnvironmentVariable(ApplicationParameters.Environment.Temp, EnvironmentVariableTarget.Machine).ToStringSafe()); } return path; } - public char get_path_directory_separator_char() + public char GetPathDirectorySeparatorChar() { return Path.DirectorySeparatorChar; } - public char get_path_separator() + public char GetPathSeparator() { return Path.PathSeparator; } - public string get_executable_path(string executableName) + public string GetExecutablePath(string executableName) { if (string.IsNullOrWhiteSpace(executableName)) return string.Empty; - var isWindows = Platform.get_platform() == PlatformType.Windows; + var isWindows = Platform.GetPlatform() == PlatformType.Windows; IList<string> extensions = new List<string>(); - if (get_file_name_without_extension(executableName).is_equal_to(executableName) && isWindows) + if (GetFilenameWithoutExtension(executableName).IsEqualTo(executableName) && isWindows) { - var pathExtensions = Environment.GetEnvironmentVariable(ApplicationParameters.Environment.PathExtensions).to_string().Split(new[] { ApplicationParameters.Environment.EnvironmentSeparator }, StringSplitOptions.RemoveEmptyEntries); - foreach (var extension in pathExtensions.or_empty_list_if_null()) + var pathExtensions = Environment.GetEnvironmentVariable(ApplicationParameters.Environment.PathExtensions).ToStringSafe().Split(new[] { ApplicationParameters.Environment.EnvironmentSeparator }, StringSplitOptions.RemoveEmptyEntries); + foreach (var extension in pathExtensions.OrEmpty()) { - extensions.Add(extension.StartsWith(".") ? extension : ".{0}".format_with(extension)); + extensions.Add(extension.StartsWith(".") ? extension : ".{0}".FormatWith(extension)); } } @@ -155,16 +155,16 @@ public string get_executable_path(string executableName) // working directory, next to the running process, then among the // derivatives of Path and Pathext variables, applied in order. var searchPaths = new List<string>(); - searchPaths.Add(get_current_directory()); - searchPaths.Add(get_directory_name(get_current_assembly_path())); - searchPaths.AddRange(Environment.GetEnvironmentVariable(ApplicationParameters.Environment.Path).to_string().Split(new[] { get_path_separator() }, StringSplitOptions.RemoveEmptyEntries)); + searchPaths.Add(GetCurrentDirectory()); + searchPaths.Add(GetDirectoryName(GetCurrentAssemblyPath())); + searchPaths.AddRange(Environment.GetEnvironmentVariable(ApplicationParameters.Environment.Path).ToStringSafe().Split(new[] { GetPathSeparator() }, StringSplitOptions.RemoveEmptyEntries)); - foreach (var path in searchPaths.or_empty_list_if_null()) + foreach (var path in searchPaths.OrEmpty()) { - foreach (var extension in extensions.or_empty_list_if_null()) + foreach (var extension in extensions.OrEmpty()) { - var possiblePath = combine_paths(path, "{0}{1}".format_with(executableName, extension.to_lower())); - if (file_exists(possiblePath)) return possiblePath; + var possiblePath = CombinePaths(path, "{0}{1}".FormatWith(executableName, extension.ToLowerSafe())); + if (FileExists(possiblePath)) return possiblePath; } } @@ -173,28 +173,28 @@ public string get_executable_path(string executableName) return executableName; } - public string get_current_assembly_path() + public string GetCurrentAssemblyPath() { - return Assembly.GetExecutingAssembly().CodeBase.Replace(Platform.get_platform() == PlatformType.Windows ? "file:///" : "file://", string.Empty); + return Assembly.GetExecutingAssembly().CodeBase.Replace(Platform.GetPlatform() == PlatformType.Windows ? "file:///" : "file://", string.Empty); } #endregion #region File - public IEnumerable<string> get_files(string directoryPath, string pattern = "*.*", SearchOption option = SearchOption.TopDirectoryOnly) + public IEnumerable<string> GetFiles(string directoryPath, string pattern = "*.*", SearchOption option = SearchOption.TopDirectoryOnly) { if (string.IsNullOrWhiteSpace(directoryPath)) return new List<string>(); - if (!directory_exists(directoryPath)) + if (!DirectoryExists(directoryPath)) { - this.Log().Warn("Directory '{0}' does not exist.".format_with(directoryPath)); + this.Log().Warn("Directory '{0}' does not exist.".FormatWith(directoryPath)); return new List<string>(); } return Directory.EnumerateFiles(directoryPath, pattern, option); } - public IEnumerable<string> get_files(string directoryPath, string[] extensions, SearchOption option = SearchOption.TopDirectoryOnly) + public IEnumerable<string> GetFiles(string directoryPath, string[] extensions, SearchOption option = SearchOption.TopDirectoryOnly) { if (string.IsNullOrWhiteSpace(directoryPath)) return new List<string>(); @@ -202,7 +202,7 @@ public IEnumerable<string> get_files(string directoryPath, string[] extensions, .Where(f => extensions.Any(x => f.EndsWith(x, StringComparison.OrdinalIgnoreCase))); } - public bool file_exists(string filePath) + public bool FileExists(string filePath) { try { @@ -214,30 +214,30 @@ public bool file_exists(string filePath) } } - public string get_file_name(string filePath) + public string GetFileName(string filePath) { return Path.GetFileName(filePath); } - public string get_file_name_without_extension(string filePath) + public string GetFilenameWithoutExtension(string filePath) { - if (Platform.get_platform() == PlatformType.Windows) return Path.GetFileNameWithoutExtension(filePath); + if (Platform.GetPlatform() == PlatformType.Windows) return Path.GetFileNameWithoutExtension(filePath); return Path.GetFileNameWithoutExtension(filePath.Replace('\\', '/')); } - public string get_file_extension(string filePath) + public string GetFileExtension(string filePath) { - if (Platform.get_platform() == PlatformType.Windows) return Path.GetExtension(filePath); + if (Platform.GetPlatform() == PlatformType.Windows) return Path.GetExtension(filePath); return Path.GetExtension(filePath.Replace('\\', '/')); } - public dynamic get_file_info_for(string filePath) + public dynamic GetFileInfoFor(string filePath) { try { - if (!string.IsNullOrWhiteSpace(filePath) && filePath.Length >= MAX_PATH_FILE) + if (!string.IsNullOrWhiteSpace(filePath) && filePath.Length >= MaxPathFile) { return new Alphaleonis.Win32.Filesystem.FileInfo(filePath); } @@ -250,95 +250,100 @@ public dynamic get_file_info_for(string filePath) } } - public System.DateTime get_file_modified_date(string filePath) + public System.DateTime GetFileModifiedDate(string filePath) { return new FileInfo(filePath).LastWriteTime; } - public long get_file_size(string filePath) + public long GetFileSize(string filePath) { return new FileInfo(filePath).Length; } - public string get_file_version_for(string filePath) + public string GetFileVersionFor(string filePath) { - return FileVersionInfo.GetVersionInfo(get_full_path(filePath)).FileVersion; + return FileVersionInfo.GetVersionInfo(GetFullPath(filePath)).FileVersion; } - public bool is_system_file(dynamic file) + public bool IsSystemFile(dynamic file) { bool isSystemFile = ((file.Attributes & FileAttributes.System) == FileAttributes.System); if (!isSystemFile) { //check the directory to be sure - var directoryInfo = get_directory_info_for(file.DirectoryName); + var directoryInfo = GetDirectoryInfo(file.DirectoryName); isSystemFile = ((directoryInfo.Attributes & FileAttributes.System) == FileAttributes.System); } else { string fullName = file.FullName; - this.Log().Debug(ChocolateyLoggers.Verbose, () => "File \"{0}\" is a system file.".format_with(fullName)); + this.Log().Debug(ChocolateyLoggers.Verbose, () => "File \"{0}\" is a system file.".FormatWith(fullName)); } return isSystemFile; } - public bool is_readonly_file(dynamic file) + public bool IsReadOnlyFile(dynamic file) { bool isReadOnlyFile = ((file.Attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly); if (!isReadOnlyFile) { //check the directory to be sure - dynamic directoryInfo = get_directory_info_for(file.DirectoryName); + dynamic directoryInfo = GetDirectoryInfo(file.DirectoryName); isReadOnlyFile = ((directoryInfo.Attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly); } else { string fullName = file.FullName; - this.Log().Debug(ChocolateyLoggers.Verbose, () => "File \"{0}\" is a readonly file.".format_with(fullName)); + this.Log().Debug(ChocolateyLoggers.Verbose, () => "File \"{0}\" is a readonly file.".FormatWith(fullName)); } return isReadOnlyFile; } - public bool is_hidden_file(dynamic file) + public bool IsHiddenFile(dynamic file) { bool isHiddenFile = ((file.Attributes & FileAttributes.Hidden) == FileAttributes.Hidden); if (!isHiddenFile) { //check the directory to be sure - var directoryInfo = get_directory_info_for(file.DirectoryName); + var directoryInfo = GetDirectoryInfo(file.DirectoryName); isHiddenFile = ((directoryInfo.Attributes & FileAttributes.Hidden) == FileAttributes.Hidden); } else { string fullName = file.FullName; - this.Log().Debug(ChocolateyLoggers.Verbose, () => "File \"{0}\" is a hidden file.".format_with(fullName)); + this.Log().Debug(ChocolateyLoggers.Verbose, () => "File \"{0}\" is a hidden file.".FormatWith(fullName)); } return isHiddenFile; } - public bool is_encrypted_file(dynamic file) + public bool IsEncryptedFile(dynamic file) { bool isEncrypted = ((file.Attributes & FileAttributes.Encrypted) == FileAttributes.Encrypted); string fullName = file.FullName; - this.Log().Debug(ChocolateyLoggers.Verbose, () => "Is file \"{0}\" an encrypted file? {1}".format_with(fullName, isEncrypted.to_string())); + this.Log().Debug(ChocolateyLoggers.Verbose, () => "Is file \"{0}\" an encrypted file? {1}".FormatWith(fullName, isEncrypted.ToStringSafe())); return isEncrypted; } - public string get_file_date(dynamic file) + public string GetFileDate(dynamic file) { return file.CreationTime < file.LastWriteTime ? file.CreationTime.Date.ToString("yyyyMMdd") : file.LastWriteTime.Date.ToString("yyyyMMdd"); } - public void move_file(string filePath, string newFilePath) + public void MoveFile(string filePath, string newFilePath) + { + MoveFile(filePath, newFilePath, isSilent: false); + } + + public void MoveFile(string filePath, string newFilePath, bool isSilent) { - create_directory_if_not_exists(get_directory_name(newFilePath), ignoreError: true); + EnsureDirectoryExists(GetDirectoryName(newFilePath), ignoreError: true); - allow_retries( + AllowRetries( () => { try @@ -349,16 +354,21 @@ public void move_file(string filePath, string newFilePath) { Alphaleonis.Win32.Filesystem.File.Move(filePath, newFilePath); } - }); + }, isSilent: isSilent); //Thread.Sleep(10); } - public void copy_file(string sourceFilePath, string destinationFilePath, bool overwriteExisting) + public void CopyFile(string sourceFilePath, string destinationFilePath, bool overwriteExisting) { - this.Log().Debug(ChocolateyLoggers.Verbose, () => "Attempting to copy \"{0}\"{1} to \"{2}\".".format_with(sourceFilePath, Environment.NewLine, destinationFilePath)); - create_directory_if_not_exists(get_directory_name(destinationFilePath), ignoreError: true); + CopyFile(sourceFilePath, destinationFilePath, overwriteExisting, isSilent: false); + } - allow_retries( + public void CopyFile(string sourceFilePath, string destinationFilePath, bool overwriteExisting, bool isSilent) + { + this.Log().Debug(ChocolateyLoggers.Verbose, () => "Attempting to copy \"{0}\"{1} to \"{2}\".".FormatWith(sourceFilePath, Environment.NewLine, destinationFilePath)); + EnsureDirectoryExists(GetDirectoryName(destinationFilePath), ignoreError: true); + + AllowRetries( () => { try @@ -369,19 +379,19 @@ public void copy_file(string sourceFilePath, string destinationFilePath, bool ov { Alphaleonis.Win32.Filesystem.File.Copy(sourceFilePath, destinationFilePath, overwriteExisting); } - }); + }, isSilent: isSilent); } - public bool copy_file_unsafe(string sourceFilePath, string destinationFilePath, bool overwriteExisting) + public bool CopyFileUnsafe(string sourceFilePath, string destinationFilePath, bool overwriteExisting) { - if (Platform.get_platform() != PlatformType.Windows) + if (Platform.GetPlatform() != PlatformType.Windows) { - copy_file(sourceFilePath, destinationFilePath, overwriteExisting); + CopyFile(sourceFilePath, destinationFilePath, overwriteExisting); return true; } - this.Log().Debug(ChocolateyLoggers.Verbose, () => "Attempting to copy from \"{0}\" to \"{1}\".".format_with(sourceFilePath, destinationFilePath)); - create_directory_if_not_exists(get_directory_name(destinationFilePath), ignoreError: true); + this.Log().Debug(ChocolateyLoggers.Verbose, () => "Attempting to copy from \"{0}\" to \"{1}\".".FormatWith(sourceFilePath, destinationFilePath)); + EnsureDirectoryExists(GetDirectoryName(destinationFilePath), ignoreError: true); //Private Declare Function apiCopyFile Lib "kernel32" Alias "CopyFileA" _ int success = CopyFileW(sourceFilePath, destinationFilePath, overwriteExisting ? 0 : 1); @@ -393,11 +403,11 @@ public bool copy_file_unsafe(string sourceFilePath, string destinationFilePath, return success != 0; } - public void replace_file(string sourceFilePath, string destinationFilePath, string backupFilePath) + public void ReplaceFile(string sourceFilePath, string destinationFilePath, string backupFilePath) { - this.Log().Debug(ChocolateyLoggers.Verbose, () => "Attempting to replace \"{0}\"{1} with \"{2}\".{1} Backup placed at \"{3}\".".format_with(destinationFilePath, Environment.NewLine, sourceFilePath, backupFilePath)); + this.Log().Debug(ChocolateyLoggers.Verbose, () => "Attempting to replace \"{0}\"{1} with \"{2}\".{1} Backup placed at \"{3}\".".FormatWith(destinationFilePath, Environment.NewLine, sourceFilePath, backupFilePath)); - allow_retries( + AllowRetries( () => { try @@ -409,39 +419,39 @@ public void replace_file(string sourceFilePath, string destinationFilePath, stri //File.Replace(sourceFilePath, destinationFilePath, backupFilePath); // move existing file to backup location - if (!string.IsNullOrEmpty(backupFilePath) && file_exists(destinationFilePath)) + if (!string.IsNullOrEmpty(backupFilePath) && FileExists(destinationFilePath)) { try { - this.Log().Trace("Backing up '{0}' to '{1}'.".format_with(destinationFilePath, backupFilePath)); + this.Log().Trace("Backing up '{0}' to '{1}'.".FormatWith(destinationFilePath, backupFilePath)); - if (file_exists(backupFilePath)) + if (FileExists(backupFilePath)) { - this.Log().Trace("Deleting existing backup file at '{0}'.".format_with(backupFilePath)); - delete_file(backupFilePath); + this.Log().Trace("Deleting existing backup file at '{0}'.".FormatWith(backupFilePath)); + DeleteFile(backupFilePath); } - this.Log().Trace("Moving '{0}' to '{1}'.".format_with(destinationFilePath, backupFilePath)); - move_file(destinationFilePath, backupFilePath); + this.Log().Trace("Moving '{0}' to '{1}'.".FormatWith(destinationFilePath, backupFilePath)); + MoveFile(destinationFilePath, backupFilePath); } catch (Exception ex) { - this.Log().Debug("Error capturing backup of '{0}':{1} {2}".format_with(destinationFilePath, Environment.NewLine, ex.Message)); + this.Log().Debug("Error capturing backup of '{0}':{1} {2}".FormatWith(destinationFilePath, Environment.NewLine, ex.Message)); } } // copy source file to destination - this.Log().Trace("Copying '{0}' to '{1}'.".format_with(sourceFilePath, destinationFilePath)); - copy_file(sourceFilePath, destinationFilePath, overwriteExisting: true); + this.Log().Trace("Copying '{0}' to '{1}'.".FormatWith(sourceFilePath, destinationFilePath)); + CopyFile(sourceFilePath, destinationFilePath, overwriteExisting: true); // delete source file try { - this.Log().Trace("Removing '{0}'".format_with(sourceFilePath)); - delete_file(sourceFilePath); + this.Log().Trace("Removing '{0}'".FormatWith(sourceFilePath)); + DeleteFile(sourceFilePath); } catch (Exception ex) { - this.Log().Debug("Error removing '{0}':{1} {2}".format_with(sourceFilePath, Environment.NewLine, ex.Message)); + this.Log().Debug("Error removing '{0}':{1} {2}".FormatWith(sourceFilePath, Environment.NewLine, ex.Message)); } } catch (IOException) @@ -468,12 +478,17 @@ _In_ BOOL bFailIfExists // ReSharper restore InconsistentNaming - public void delete_file(string filePath) + public void DeleteFile(string filePath) { - this.Log().Debug(ChocolateyLoggers.Verbose, () => "Attempting to delete file \"{0}\".".format_with(filePath)); - if (file_exists(filePath)) + DeleteFile(filePath, isSilent: false); + } + + public void DeleteFile(string filePath, bool isSilent) + { + this.Log().Debug(ChocolateyLoggers.Verbose, () => "Attempting to delete file \"{0}\".".FormatWith(filePath)); + if (FileExists(filePath)) { - allow_retries( + AllowRetries( () => { try @@ -484,50 +499,50 @@ public void delete_file(string filePath) { Alphaleonis.Win32.Filesystem.File.Delete(filePath); } - }); + }, isSilent: isSilent); } } - public FileStream create_file(string filePath) + public FileStream CreateFile(string filePath) { return new FileStream(filePath, FileMode.OpenOrCreate); } - public string read_file(string filePath) + public string ReadFile(string filePath) { try { - return File.ReadAllText(filePath, get_file_encoding(filePath)); + return File.ReadAllText(filePath, GetFileEncoding(filePath)); } catch (IOException) { - return Alphaleonis.Win32.Filesystem.File.ReadAllText(filePath, get_file_encoding(filePath)); + return Alphaleonis.Win32.Filesystem.File.ReadAllText(filePath, GetFileEncoding(filePath)); } } - public byte[] read_file_bytes(string filePath) + public byte[] ReadFileBytes(string filePath) { return File.ReadAllBytes(filePath); } - public FileStream open_file_readonly(string filePath) + public FileStream OpenFileReadonly(string filePath) { return File.OpenRead(filePath); } - public FileStream open_file_exclusive(string filePath) + public FileStream OpenFileExclusive(string filePath) { return File.Open(filePath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None); } - public void write_file(string filePath, string fileText) + public void WriteFile(string filePath, string fileText) { - write_file(filePath, fileText, file_exists(filePath) ? get_file_encoding(filePath) : Encoding.UTF8); + WriteFile(filePath, fileText, FileExists(filePath) ? GetFileEncoding(filePath) : Encoding.UTF8); } - public void write_file(string filePath, string fileText, Encoding encoding) + public void WriteFile(string filePath, string fileText, Encoding encoding) { - allow_retries(() => + AllowRetries(() => { using (FileStream fileStream = File.Open(filePath, FileMode.OpenOrCreate, FileAccess.Write, FileShare.Read)) using (var streamWriter = new StreamWriter(fileStream, encoding)) @@ -540,7 +555,7 @@ public void write_file(string filePath, string fileText, Encoding encoding) }); } - public void write_file(string filePath, Func<Stream> getStream) + public void WriteFile(string filePath, Func<Stream> getStream) { using (Stream incomingStream = getStream()) using (Stream fileStream = File.Open(filePath, FileMode.OpenOrCreate, FileAccess.Write, FileShare.Read)) @@ -554,33 +569,33 @@ public void write_file(string filePath, Func<Stream> getStream) #region Directory - public string get_current_directory() + public string GetCurrentDirectory() { return Directory.GetCurrentDirectory(); } - public IEnumerable<string> get_directories(string directoryPath) + public IEnumerable<string> GetDirectories(string directoryPath) { - if (!directory_exists(directoryPath)) return new List<string>(); + if (!DirectoryExists(directoryPath)) return new List<string>(); return Directory.EnumerateDirectories(directoryPath); } - public IEnumerable<string> get_directories(string directoryPath, string pattern, SearchOption option = SearchOption.TopDirectoryOnly) + public IEnumerable<string> GetDirectories(string directoryPath, string pattern, SearchOption option = SearchOption.TopDirectoryOnly) { - if (!directory_exists(directoryPath)) return new List<string>(); + if (!DirectoryExists(directoryPath)) return new List<string>(); return Directory.EnumerateDirectories(directoryPath, pattern, option); } - public bool directory_exists(string directoryPath) + public bool DirectoryExists(string directoryPath) { return Directory.Exists(directoryPath); } - public string get_directory_name(string filePath) + public string GetDirectoryName(string filePath) { - if (Platform.get_platform() != PlatformType.Windows && !string.IsNullOrWhiteSpace(filePath)) + if (Platform.GetPlatform() != PlatformType.Windows && !string.IsNullOrWhiteSpace(filePath)) { filePath = filePath.Replace('\\', '/'); } @@ -595,11 +610,11 @@ public string get_directory_name(string filePath) } } - public dynamic get_directory_info_for(string directoryPath) + public dynamic GetDirectoryInfo(string directoryPath) { try { - if (!string.IsNullOrWhiteSpace(directoryPath) && directoryPath.Length >= MAX_PATH_DIRECTORY) + if (!string.IsNullOrWhiteSpace(directoryPath) && directoryPath.Length >= MaxPathDirectory) { return new Alphaleonis.Win32.Filesystem.DirectoryInfo(directoryPath); } @@ -612,11 +627,11 @@ public dynamic get_directory_info_for(string directoryPath) } } - public dynamic get_directory_info_from_file_path(string filePath) + public dynamic GetFileDirectoryInfo(string filePath) { try { - if (!string.IsNullOrWhiteSpace(filePath) && filePath.Length >= MAX_PATH_FILE) + if (!string.IsNullOrWhiteSpace(filePath) && filePath.Length >= MaxPathFile) { return new Alphaleonis.Win32.Filesystem.DirectoryInfo(filePath).Parent; } @@ -629,10 +644,10 @@ public dynamic get_directory_info_from_file_path(string filePath) } } - public void create_directory(string directoryPath) + public void CreateDirectory(string directoryPath) { - this.Log().Debug(ChocolateyLoggers.Verbose, () => "Attempting to create directory \"{0}\".".format_with(get_full_path(directoryPath))); - allow_retries( + this.Log().Debug(ChocolateyLoggers.Verbose, () => "Attempting to create directory \"{0}\".".FormatWith(GetFullPath(directoryPath))); + AllowRetries( () => { try @@ -646,18 +661,23 @@ public void create_directory(string directoryPath) }); } - public void move_directory(string directoryPath, string newDirectoryPath) + public void MoveDirectory(string directoryPath, string newDirectoryPath) + { + MoveDirectory(directoryPath, newDirectoryPath, useFileMoveFallback: true, isSilent: false); + } + + public void MoveDirectory(string directoryPath, string newDirectoryPath, bool useFileMoveFallback, bool isSilent) { if (string.IsNullOrWhiteSpace(directoryPath) || string.IsNullOrWhiteSpace(newDirectoryPath)) throw new ApplicationException("You must provide a directory to move from or to."); // Linux / macOS do not have a SystemDrive environment variable, instead, everything is under "/" - var systemDrive = Platform.get_platform() == PlatformType.Windows ? Environment.GetEnvironmentVariable("SystemDrive") : "/"; - if (combine_paths(directoryPath, "").is_equal_to(combine_paths(systemDrive, ""))) throw new ApplicationException("Cannot move or delete the root of the system drive"); + var systemDrive = Platform.GetPlatform() == PlatformType.Windows ? Environment.GetEnvironmentVariable("SystemDrive") : "/"; + if (CombinePaths(directoryPath, "").IsEqualTo(CombinePaths(systemDrive, ""))) throw new ApplicationException("Cannot move or delete the root of the system drive"); try { - this.Log().Debug(ChocolateyLoggers.Verbose, "Moving '{0}'{1} to '{2}'".format_with(directoryPath, Environment.NewLine, newDirectoryPath)); - allow_retries( + this.Log().Debug(ChocolateyLoggers.Verbose, "Moving '{0}'{1} to '{2}'".FormatWith(directoryPath, Environment.NewLine, newDirectoryPath)); + AllowRetries( () => { try @@ -668,102 +688,132 @@ public void move_directory(string directoryPath, string newDirectoryPath) { Alphaleonis.Win32.Filesystem.Directory.Move(directoryPath, newDirectoryPath); } - }); + }, isSilent: isSilent); } catch (Exception ex) { - this.Log().Warn(ChocolateyLoggers.Verbose, "Move failed with message:{0} {1}{0} Attempting backup move method.".format_with(Environment.NewLine, ex.Message)); + // If we don't want to use the fallback, we will just rethrow the exception. + if (!useFileMoveFallback) + { + throw; + } + + this.Log().Warn(ChocolateyLoggers.Verbose, "Move failed with message:{0} {1}{0} Attempting backup move method.".FormatWith(Environment.NewLine, ex.Message)); - create_directory_if_not_exists(newDirectoryPath, ignoreError: true); - foreach (var file in get_files(directoryPath, "*.*", SearchOption.AllDirectories).or_empty_list_if_null()) + EnsureDirectoryExists(newDirectoryPath, ignoreError: true); + foreach (var file in GetFiles(directoryPath, "*.*", SearchOption.AllDirectories).OrEmpty()) { var destinationFile = file.Replace(directoryPath, newDirectoryPath); - if (file_exists(destinationFile)) delete_file(destinationFile); + if (FileExists(destinationFile)) DeleteFile(destinationFile, isSilent); - create_directory_if_not_exists(get_directory_name(destinationFile), ignoreError: true); - this.Log().Debug(ChocolateyLoggers.Verbose, "Moving '{0}'{1} to '{2}'".format_with(file, Environment.NewLine, destinationFile)); - move_file(file, destinationFile); + EnsureDirectoryExists(GetDirectoryName(destinationFile), ignoreError: true); + this.Log().Debug(ChocolateyLoggers.Verbose, "Moving '{0}'{1} to '{2}'".FormatWith(file, Environment.NewLine, destinationFile)); + MoveFile(file, destinationFile, isSilent); } Thread.Sleep(1000); // let the moving files finish up - delete_directory_if_exists(directoryPath, recursive: true); + DeleteDirectoryChecked(directoryPath, recursive: true, overrideAttributes: false, isSilent: isSilent); } Thread.Sleep(2000); // sleep for enough time to allow the folder to be cleared } - public void copy_directory(string sourceDirectoryPath, string destinationDirectoryPath, bool overwriteExisting) + public void CopyDirectory(string sourceDirectoryPath, string destinationDirectoryPath, bool overwriteExisting) { - create_directory_if_not_exists(destinationDirectoryPath, ignoreError: true); + CopyDirectory(sourceDirectoryPath, destinationDirectoryPath, overwriteExisting, isSilent: false); + } + + public void CopyDirectory(string sourceDirectoryPath, string destinationDirectoryPath, bool overwriteExisting, bool isSilent) + { + EnsureDirectoryExists(destinationDirectoryPath, ignoreError: true); + + var exceptions = new List<Exception>(); - foreach (var file in get_files(sourceDirectoryPath, "*.*", SearchOption.AllDirectories).or_empty_list_if_null()) + foreach (var file in GetFiles(sourceDirectoryPath, "*.*", SearchOption.AllDirectories).OrEmpty()) { var destinationFile = file.Replace(sourceDirectoryPath, destinationDirectoryPath); - create_directory_if_not_exists(get_directory_name(destinationFile), ignoreError: true); + EnsureDirectoryExists(GetDirectoryName(destinationFile), ignoreError: true); //this.Log().Debug(ChocolateyLoggers.Verbose, "Copying '{0}' {1} to '{2}'".format_with(file, Environment.NewLine, destinationFile)); - copy_file(file, destinationFile, overwriteExisting); + + try + { + CopyFile(file, destinationFile, overwriteExisting, isSilent); + } + catch (Exception ex) + { + exceptions.Add(ex); + } } Thread.Sleep(1500); // sleep for enough time to allow the folder to finish copying + + if (exceptions.Count > 1) + { + throw new AggregateException("An exception occurred while copying files to '{0}'".FormatWith(destinationDirectoryPath), exceptions); + } + else if (exceptions.Count == 1) + { + throw exceptions[0]; + } } - public void create_directory_if_not_exists(string directoryPath) + public void EnsureDirectoryExists(string directoryPath) { - create_directory_if_not_exists(directoryPath, false); + EnsureDirectoryExists(directoryPath, false); } - public void create_directory_if_not_exists(string directoryPath, bool ignoreError) + private void EnsureDirectoryExists(string directoryPath, bool ignoreError) { - if (!directory_exists(directoryPath)) + if (!DirectoryExists(directoryPath)) { try { - create_directory(directoryPath); + CreateDirectory(directoryPath); } catch (SystemException e) { if (!ignoreError) { - this.Log().Error("Cannot create directory \"{0}\". Error was:{1}{2}", get_full_path(directoryPath), Environment.NewLine, e); + this.Log().Error("Cannot create directory \"{0}\". Error was:{1}{2}", GetFullPath(directoryPath), Environment.NewLine, e); throw; } } } } - public void delete_directory(string directoryPath, bool recursive) + public void DeleteDirectory(string directoryPath, bool recursive) { - delete_directory(directoryPath, recursive, overrideAttributes: false, isSilent: false); + DeleteDirectory(directoryPath, recursive, overrideAttributes: false, isSilent: false); } - public void delete_directory(string directoryPath, bool recursive, bool overrideAttributes) + public void DeleteDirectory(string directoryPath, bool recursive, bool overrideAttributes) { - delete_directory(directoryPath, recursive, overrideAttributes: overrideAttributes, isSilent: false); + DeleteDirectory(directoryPath, recursive, overrideAttributes: overrideAttributes, isSilent: false); } - public void delete_directory(string directoryPath, bool recursive, bool overrideAttributes, bool isSilent) + public void DeleteDirectory(string directoryPath, bool recursive, bool overrideAttributes, bool isSilent) { if (string.IsNullOrWhiteSpace(directoryPath)) throw new ApplicationException("You must provide a directory to delete."); // Linux / macOS do not have a SystemDrive environment variable, instead, everything is under "/" - var systemDrive = Platform.get_platform() == PlatformType.Windows ? Environment.GetEnvironmentVariable("SystemDrive") : "/"; - if (combine_paths(directoryPath, "").is_equal_to(combine_paths(systemDrive, ""))) throw new ApplicationException("Cannot move or delete the root of the system drive"); + var systemDrive = Platform.GetPlatform() == PlatformType.Windows ? Environment.GetEnvironmentVariable("SystemDrive") : "/"; + if (CombinePaths(directoryPath, "").IsEqualTo(CombinePaths(systemDrive, ""))) throw new ApplicationException("Cannot move or delete the root of the system drive"); if (overrideAttributes) { - foreach (var file in get_files(directoryPath, "*.*", SearchOption.AllDirectories)) + foreach (var file in GetFiles(directoryPath, "*.*", SearchOption.AllDirectories)) { - var filePath = get_full_path(file); - var fileInfo = get_file_info_for(filePath); + var filePath = GetFullPath(file); + var fileInfo = GetFileInfoFor(filePath); - if (is_system_file(fileInfo)) ensure_file_attribute_removed(filePath, FileAttributes.System); - if (is_readonly_file(fileInfo)) ensure_file_attribute_removed(filePath, FileAttributes.ReadOnly); - if (is_hidden_file(fileInfo)) ensure_file_attribute_removed(filePath, FileAttributes.Hidden); + if (IsSystemFile(fileInfo)) EnsureFileAttributeRemoved(filePath, FileAttributes.System); + if (IsReadOnlyFile(fileInfo)) EnsureFileAttributeRemoved(filePath, FileAttributes.ReadOnly); + if (IsHiddenFile(fileInfo)) EnsureFileAttributeRemoved(filePath, FileAttributes.Hidden); } } - if (!isSilent) this.Log().Debug(ChocolateyLoggers.Verbose, () => "Attempting to delete directory \"{0}\".".format_with(get_full_path(directoryPath))); - allow_retries( + if (!isSilent) this.Log().Debug(ChocolateyLoggers.Verbose, () => "Attempting to delete directory \"{0}\".".FormatWith(GetFullPath(directoryPath))); + AllowRetries( () => { try @@ -777,65 +827,65 @@ public void delete_directory(string directoryPath, bool recursive, bool override }, isSilent: isSilent); } - public void delete_directory_if_exists(string directoryPath, bool recursive) + public void DeleteDirectoryChecked(string directoryPath, bool recursive) { - delete_directory_if_exists(directoryPath, recursive, overrideAttributes: false, isSilent: false); + DeleteDirectoryChecked(directoryPath, recursive, overrideAttributes: false, isSilent: false); } - public void delete_directory_if_exists(string directoryPath, bool recursive, bool overrideAttributes) + public void DeleteDirectoryChecked(string directoryPath, bool recursive, bool overrideAttributes) { - delete_directory_if_exists(directoryPath, recursive, overrideAttributes: overrideAttributes, isSilent: false); + DeleteDirectoryChecked(directoryPath, recursive, overrideAttributes: overrideAttributes, isSilent: false); } - public void delete_directory_if_exists(string directoryPath, bool recursive, bool overrideAttributes, bool isSilent) + public void DeleteDirectoryChecked(string directoryPath, bool recursive, bool overrideAttributes, bool isSilent) { - if (directory_exists(directoryPath)) + if (DirectoryExists(directoryPath)) { - delete_directory(directoryPath, recursive, overrideAttributes, isSilent); + DeleteDirectory(directoryPath, recursive, overrideAttributes, isSilent); } } #endregion - public void ensure_file_attribute_set(string path, FileAttributes attributes) + public void EnsureFileAttributeSet(string path, FileAttributes attributes) { - if (directory_exists(path)) + if (DirectoryExists(path)) { - var directoryInfo = get_directory_info_for(path); + var directoryInfo = GetDirectoryInfo(path); if ((directoryInfo.Attributes & attributes) != attributes) { - this.Log().Debug(ChocolateyLoggers.Verbose, () => "Adding '{0}' attribute(s) to '{1}'.".format_with(attributes.to_string(), path)); + this.Log().Debug(ChocolateyLoggers.Verbose, () => "Adding '{0}' attribute(s) to '{1}'.".FormatWith(attributes.ToStringSafe(), path)); directoryInfo.Attributes |= attributes; } } - if (file_exists(path)) + if (FileExists(path)) { - var fileInfo = get_file_info_for(path); + var fileInfo = GetFileInfoFor(path); if ((fileInfo.Attributes & attributes) != attributes) { - this.Log().Debug(ChocolateyLoggers.Verbose, () => "Adding '{0}' attribute(s) to '{1}'.".format_with(attributes.to_string(), path)); + this.Log().Debug(ChocolateyLoggers.Verbose, () => "Adding '{0}' attribute(s) to '{1}'.".FormatWith(attributes.ToStringSafe(), path)); fileInfo.Attributes |= attributes; } } } - public void ensure_file_attribute_removed(string path, FileAttributes attributes) + public void EnsureFileAttributeRemoved(string path, FileAttributes attributes) { - if (directory_exists(path)) + if (DirectoryExists(path)) { - var directoryInfo = get_directory_info_for(path); + var directoryInfo = GetDirectoryInfo(path); if ((directoryInfo.Attributes & attributes) == attributes) { - this.Log().Debug(ChocolateyLoggers.Verbose, () => "Removing '{0}' attribute(s) from '{1}'.".format_with(attributes.to_string(), path)); + this.Log().Debug(ChocolateyLoggers.Verbose, () => "Removing '{0}' attribute(s) from '{1}'.".FormatWith(attributes.ToStringSafe(), path)); directoryInfo.Attributes &= ~attributes; } } - if (file_exists(path)) + if (FileExists(path)) { - var fileInfo = get_file_info_for(path); + var fileInfo = GetFileInfoFor(path); if ((fileInfo.Attributes & attributes) == attributes) { - this.Log().Debug(ChocolateyLoggers.Verbose, () => "Removing '{0}' attribute(s) from '{1}'.".format_with(attributes.to_string(), path)); + this.Log().Debug(ChocolateyLoggers.Verbose, () => "Removing '{0}' attribute(s) from '{1}'.".FormatWith(attributes.ToStringSafe(), path)); fileInfo.Attributes &= ~attributes; } } @@ -847,7 +897,7 @@ public void ensure_file_attribute_removed(string path, FileAttributes attributes /// <param name="filePath">Path to the file name</param> /// <returns>A best guess at the encoding of the file</returns> /// <remarks>http://www.west-wind.com/WebLog/posts/197245.aspx</remarks> - public Encoding get_file_encoding(string filePath) + public Encoding GetFileEncoding(string filePath) { // *** Use Default of Encoding.Default (Ansi CodePage) Encoding enc = Encoding.Default; @@ -868,5 +918,236 @@ public Encoding get_file_encoding(string filePath) return enc; } + + +#pragma warning disable IDE1006 + [Obsolete("This overload is deprecated and will be removed in v3.")] + public void initialize_with(Lazy<IEnvironment> environment) + => InitializeWith(environment); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public string combine_paths(string leftItem, params string[] rightItems) + => CombinePaths(leftItem, rightItems); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public string get_full_path(string path) + => GetFullPath(path); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public string get_temp_path() + => GetTempPath(); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public char get_path_directory_separator_char() + => GetPathDirectorySeparatorChar(); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public char get_path_separator() + => GetPathSeparator(); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public string get_executable_path(string executableName) + => GetExecutablePath(executableName); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public string get_current_assembly_path() + => GetCurrentAssemblyPath(); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public IEnumerable<string> get_files(string directoryPath, string pattern = "*.*", SearchOption option = SearchOption.TopDirectoryOnly) + => GetFiles(directoryPath, pattern, option); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public IEnumerable<string> get_files(string directoryPath, string[] extensions, SearchOption option = SearchOption.TopDirectoryOnly) + => GetFiles(directoryPath, extensions, option); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public bool file_exists(string filePath) + => FileExists(filePath); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public string get_file_name(string filePath) + => GetFileName( filePath); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public string get_file_name_without_extension(string filePath) + => GetFilenameWithoutExtension(filePath); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public string get_file_extension(string filePath) + => GetFileExtension(filePath); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public dynamic get_file_info_for(string filePath) + => GetFileInfoFor(filePath); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public System.DateTime get_file_modified_date(string filePath) + => GetFileModifiedDate(filePath); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public long get_file_size(string filePath) + => GetFileSize(filePath); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public string get_file_version_for(string filePath) + => GetFileVersionFor(filePath); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public bool is_system_file(dynamic file) + => IsSystemFile(file); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public bool is_readonly_file(dynamic file) + => IsReadOnlyFile(file); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public bool is_hidden_file(dynamic file) + => IsHiddenFile(file); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public bool is_encrypted_file(dynamic file) + => IsEncryptedFile(file); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public string get_file_date(dynamic file) + => GetFileDate(file); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public void move_file(string filePath, string newFilePath) + => MoveFile(filePath, newFilePath); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public void copy_file(string sourceFilePath, string destinationFilePath, bool overwriteExisting) + => CopyFile(sourceFilePath, destinationFilePath, overwriteExisting); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public bool copy_file_unsafe(string sourceFilePath, string destinationFilePath, bool overwriteExisting) + => CopyFileUnsafe(sourceFilePath, destinationFilePath, overwriteExisting); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public void replace_file(string sourceFilePath, string destinationFilePath, string backupFilePath) + => ReplaceFile(sourceFilePath, destinationFilePath, backupFilePath); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public void delete_file(string filePath) + => DeleteFile(filePath); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public FileStream create_file(string filePath) + => CreateFile(filePath); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public string read_file(string filePath) + => ReadFile(filePath); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public byte[] read_file_bytes(string filePath) + => ReadFileBytes(filePath); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public FileStream open_file_readonly(string filePath) + => OpenFileReadonly(filePath); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public FileStream open_file_exclusive(string filePath) + => OpenFileExclusive(filePath); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public void write_file(string filePath, string fileText) + => WriteFile(filePath, fileText); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public void write_file(string filePath, string fileText, Encoding encoding) + => WriteFile(filePath, fileText, encoding); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public void write_file(string filePath, Func<Stream> getStream) + => WriteFile(filePath, getStream); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public string get_current_directory() + => GetCurrentDirectory(); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public IEnumerable<string> get_directories(string directoryPath) + => GetDirectories(directoryPath); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public IEnumerable<string> get_directories(string directoryPath, string pattern, SearchOption option = SearchOption.TopDirectoryOnly) + => GetDirectories(directoryPath, pattern, option); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public bool directory_exists(string directoryPath) + => DirectoryExists(directoryPath); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public string get_directory_name(string filePath) + => GetDirectoryName(filePath); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public dynamic get_directory_info_for(string directoryPath) + => GetDirectoryInfo(directoryPath); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public dynamic get_directory_info_from_file_path(string filePath) + => GetFileDirectoryInfo(filePath); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public void create_directory(string directoryPath) + => CreateDirectory(directoryPath); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public void move_directory(string directoryPath, string newDirectoryPath) + => MoveDirectory(directoryPath, newDirectoryPath); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public void copy_directory(string sourceDirectoryPath, string destinationDirectoryPath, bool overwriteExisting) + => CopyDirectory(sourceDirectoryPath, destinationDirectoryPath, overwriteExisting); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public void create_directory_if_not_exists(string directoryPath) + => EnsureDirectoryExists(directoryPath); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public void create_directory_if_not_exists(string directoryPath, bool ignoreError) + => EnsureDirectoryExists(directoryPath, ignoreError); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public void delete_directory(string directoryPath, bool recursive) + => DeleteDirectory(directoryPath, recursive); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public void delete_directory(string directoryPath, bool recursive, bool overrideAttributes) + => DeleteDirectory(directoryPath, recursive, overrideAttributes); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public void delete_directory(string directoryPath, bool recursive, bool overrideAttributes, bool isSilent) + => DeleteDirectory(directoryPath, recursive, overrideAttributes, isSilent); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public void delete_directory_if_exists(string directoryPath, bool recursive) + => DeleteDirectoryChecked(directoryPath, recursive); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public void delete_directory_if_exists(string directoryPath, bool recursive, bool overrideAttributes) + => DeleteDirectoryChecked(directoryPath, recursive, overrideAttributes); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public void delete_directory_if_exists(string directoryPath, bool recursive, bool overrideAttributes, bool isSilent) + => DeleteDirectoryChecked(directoryPath, recursive, overrideAttributes, isSilent); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public void ensure_file_attribute_set(string path, FileAttributes attributes) + => EnsureFileAttributeSet(path, attributes); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public void ensure_file_attribute_removed(string path, FileAttributes attributes) + => EnsureFileAttributeRemoved(path, attributes); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public Encoding get_file_encoding(string filePath) + => GetFileEncoding(filePath); +#pragma warning restore IDE1006 } } diff --git a/src/chocolatey/infrastructure/filesystem/FileSystem.cs b/src/chocolatey/infrastructure/filesystem/FileSystem.cs index 5cd2b5e52b..e628c82348 100644 --- a/src/chocolatey/infrastructure/filesystem/FileSystem.cs +++ b/src/chocolatey/infrastructure/filesystem/FileSystem.cs @@ -16,11 +16,12 @@ namespace chocolatey.infrastructure.filesystem { + using System; using System.IO; public static class FileSystem { - public static byte[] read_binary_file_into_byte_array(string filePath) + public static byte[] ReadFileBytes(string filePath) { byte[] fileBytes = null; using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) @@ -33,5 +34,11 @@ public static byte[] read_binary_file_into_byte_array(string filePath) return fileBytes; } + +#pragma warning disable IDE1006 + [Obsolete("This overload is deprecated and will be removed in v3.")] + public static byte[] read_binary_file_into_byte_array(string filePath) + => ReadFileBytes(filePath); +#pragma warning restore IDE1006 } } diff --git a/src/chocolatey/infrastructure/filesystem/IFileSystem.cs b/src/chocolatey/infrastructure/filesystem/IFileSystem.cs index ee3fb6049b..661cb51754 100644 --- a/src/chocolatey/infrastructure/filesystem/IFileSystem.cs +++ b/src/chocolatey/infrastructure/filesystem/IFileSystem.cs @@ -34,25 +34,25 @@ public interface IFileSystem /// <param name="leftItem">The first path to combine. </param> /// <param name="rightItems">string array of all other paths to combine.</param> /// <returns>The combined paths.</returns> - string combine_paths(string leftItem, params string[] rightItems); + string CombinePaths(string leftItem, params string[] rightItems); /// <summary> /// Gets the full path. /// </summary> /// <param name="path">The file or directory for which to obtain absolute path information.</param> /// <returns>The fully qualified location of path, such as "C:\MyFile.txt".</returns> - string get_full_path(string path); + string GetFullPath(string path); /// <summary> /// Gets the path to the temporary folder for the current user. /// </summary> - string get_temp_path(); + string GetTempPath(); /// <summary> /// Gets the path directory separator character /// </summary> /// <returns></returns> - char get_path_directory_separator_char(); + char GetPathDirectorySeparatorChar(); /// <summary> /// Gets the path to an executable based on looking in current directory, next to the running process, then among the derivatives of Path and Pathext variables @@ -60,13 +60,13 @@ public interface IFileSystem /// <param name="executableName">Name of the executable.</param> /// <remarks>Based loosely on http://stackoverflow.com/a/5471032/18475</remarks> /// <returns></returns> - string get_executable_path(string executableName); + string GetExecutablePath(string executableName); /// <summary> /// Gets the location of the executing assembly /// </summary> /// <returns>The path to the executing assembly</returns> - string get_current_assembly_path(); + string GetCurrentAssemblyPath(); #endregion @@ -79,7 +79,7 @@ public interface IFileSystem /// <param name="pattern">The search pattern.</param> /// <param name="option">The option specifies whether the search operation should include all subdirectories or only the current directory.</param> /// <returns>Returns the names of files (including their paths).</returns> - IEnumerable<string> get_files(string directoryPath, string pattern = "*.*", SearchOption option = SearchOption.TopDirectoryOnly); + IEnumerable<string> GetFiles(string directoryPath, string pattern = "*.*", SearchOption option = SearchOption.TopDirectoryOnly); /// <summary> /// Gets a list of files inside an existing directory with extensions and optionally recursive search option. @@ -88,105 +88,113 @@ public interface IFileSystem /// <param name="extensions">The extensions.</param> /// <param name="option">The option.</param> /// <returns>Returns the names of files (including their paths).</returns> - IEnumerable<string> get_files(string directoryPath, string[] extensions, SearchOption option = SearchOption.TopDirectoryOnly); + IEnumerable<string> GetFiles(string directoryPath, string[] extensions, SearchOption option = SearchOption.TopDirectoryOnly); /// <summary> /// Does the file exist? /// </summary> /// <param name="filePath">The file to check.</param> /// <returns>Boolean - true if the caller has the required permissions and path contains the name of an existing file; otherwise, false.</returns> - bool file_exists(string filePath); + bool FileExists(string filePath); /// <summary> /// Returns the file name and extension of the specified path string. /// </summary> /// <param name="filePath">The file path.</param> /// <returns>The characters after the last directory character in path. If the last character of path is a directory or volume separator character, this method returns String.Empty. If path is Nothing, this method returns Nothing.</returns> - string get_file_name(string filePath); + string GetFileName(string filePath); /// <summary> /// Gets the file name without extension. /// </summary> /// <param name="filePath">The file path.</param> /// <returns>The string returned by get_file_name, minus the last period (.) and all characters following it.</returns> - string get_file_name_without_extension(string filePath); + string GetFilenameWithoutExtension(string filePath); /// <summary> /// Gets the extension (including the "."). /// </summary> /// <param name="filePath">The file path.</param> /// <returns>he extension of the specified path (including the period "."), or Nothing, or String.Empty. If path is Nothing, get_file_extension returns Nothing. If path does not have extension information, get_file_extension returns String.Empty.</returns> - string get_file_extension(string filePath); + string GetFileExtension(string filePath); /// <summary> /// Determines the file information given a path to an existing file /// </summary> /// <param name="filePath">Path to an existing file</param> /// <returns>FileInfo object or reimplementation of a FileInfo object that works with greater than 260 chars</returns> - dynamic get_file_info_for(string filePath); + dynamic GetFileInfoFor(string filePath); /// <summary> /// Gets the file mod date. /// </summary> /// <param name="filePath">The file path.</param> /// <returns>the modification date of the specified file.</returns> - DateTime get_file_modified_date(string filePath); + DateTime GetFileModifiedDate(string filePath); /// <summary> /// Gets the size of the file. /// </summary> /// <param name="filePath">The file path.</param> /// <returns>The size, in bytes, of the current file.</returns> - long get_file_size(string filePath); + long GetFileSize(string filePath); /// <summary> /// Determines the FileVersion of the file passed in /// </summary> /// <param name="filePath">Relative or full path to a file</param> /// <returns>A string representing the FileVersion of the passed in file</returns> - string get_file_version_for(string filePath); + string GetFileVersionFor(string filePath); /// <summary> /// Determines if a file is a system file /// </summary> /// <param name="file">File to check - FileInfo or some representation of FileInfo</param> /// <returns>True if the file has the System attribute marked, otherwise false</returns> - bool is_system_file(dynamic file); + bool IsSystemFile(dynamic file); /// <summary> /// Determines if a file is a read only file /// </summary> /// <param name="file">File to check - FileInfo or some representation of FileInfo</param> /// <returns>True if the file has the ReadOnly attribute marked, otherwise false</returns> - bool is_readonly_file(dynamic file); + bool IsReadOnlyFile(dynamic file); /// <summary> /// Determines if a file is a hidden file /// </summary> /// <param name="file">File to check - FileInfo or some representation of FileInfo</param> /// <returns>True if the file has the Hidden attribute marked, otherwise false</returns> - bool is_hidden_file(dynamic file); + bool IsHiddenFile(dynamic file); /// <summary> /// Determines if a file is encrypted or not /// </summary> /// <param name="file">File to check - FileInfo or some representation of FileInfo</param> /// <returns>True if the file has the Encrypted attribute marked, otherwise false</returns> - bool is_encrypted_file(dynamic file); + bool IsEncryptedFile(dynamic file); /// <summary> /// Determines the older of the file dates, Creation Date or Modified Date /// </summary> /// <param name="file">File to analyze - FileInfo or some representation of FileInfo</param> /// <returns>The oldest date on the file</returns> - string get_file_date(dynamic file); + string GetFileDate(dynamic file); /// <summary> /// Moves a specified file to a new location, providing the option to specify a new file name. /// </summary> /// <param name="filePath">The name of the file to move. </param> /// <param name="newFilePath">The new path for the file. </param> - void move_file(string filePath, string newFilePath); + void MoveFile(string filePath, string newFilePath); + + /// <summary> + /// Moves a specified file to a new location, providing the option to specify a new file name. + /// </summary> + /// <param name="filePath">The name of the file to move. </param> + /// <param name="newFilePath">The new path for the file. </param> + /// <param name="isSilent">Whether we should log retries or not.</param> + void MoveFile(string filePath, string newFilePath, bool isSilent); /// <summary> /// Copies an existing file to a new file. Overwriting a file of the same name is allowed. @@ -194,7 +202,16 @@ public interface IFileSystem /// <param name="sourceFilePath">The source file path. The file to copy.</param> /// <param name="destinationFilePath">The destination file path.</param> /// <param name="overwriteExisting">true if the destination file can be overwritten; otherwise, false.</param> - void copy_file(string sourceFilePath, string destinationFilePath, bool overwriteExisting); + void CopyFile(string sourceFilePath, string destinationFilePath, bool overwriteExisting); + + /// <summary> + /// Copies an existing file to a new file. Overwriting a file of the same name is allowed. + /// </summary> + /// <param name="sourceFilePath">The source file path. The file to copy.</param> + /// <param name="destinationFilePath">The destination file path.</param> + /// <param name="overwriteExisting">true if the destination file can be overwritten; otherwise, false.</param> + /// <param name="isSilent">Whether we should log retries or not.</param> + void CopyFile(string sourceFilePath, string destinationFilePath, bool overwriteExisting, bool isSilent); /// <summary> /// Copies a file from one directory to another using FFI @@ -203,7 +220,7 @@ public interface IFileSystem /// <param name="destinationFilePath">Where would you like it to go?</param> /// <param name="overwriteExisting">If there is an existing file already there, would you like to delete it?</param> /// <returns>true if copy was successful, otherwise false</returns> - bool copy_file_unsafe(string sourceFilePath, string destinationFilePath, bool overwriteExisting); + bool CopyFileUnsafe(string sourceFilePath, string destinationFilePath, bool overwriteExisting); /// <summary> /// Replace an existing file. @@ -211,55 +228,55 @@ public interface IFileSystem /// <param name="sourceFilePath">Where is the file now?</param> /// <param name="destinationFilePath">Where would you like it to go?</param> /// <param name="backupFilePath">Where should the existing file be placed? Null if nowhere.</param> - void replace_file(string sourceFilePath, string destinationFilePath, string backupFilePath); + void ReplaceFile(string sourceFilePath, string destinationFilePath, string backupFilePath); /// <summary> /// Deletes the specified file. /// </summary> /// <param name="filePath">The name of the file to be deleted. Wildcard characters are not supported.</param> - void delete_file(string filePath); + void DeleteFile(string filePath); /// <summary> /// Creates a file /// </summary> /// <param name="filePath">Path to the file name</param> /// <returns>A file stream object for use after creating the file</returns> - FileStream create_file(string filePath); + FileStream CreateFile(string filePath); /// <summary> /// Returns the contents of a file /// </summary> /// <param name="filePath">Path to the file name</param> /// <returns>A string of the file contents</returns> - string read_file(string filePath); + string ReadFile(string filePath); /// <summary> /// Returns the contents of a file as bytes. /// </summary> /// <param name="filePath">The filepath.</param> /// <returns>A byte array of the file contents</returns> - byte[] read_file_bytes(string filePath); + byte[] ReadFileBytes(string filePath); /// <summary> /// Opens a file /// </summary> /// <param name="filePath">Path to the file name</param> /// <returns>A file stream object for use after accessing the file</returns> - FileStream open_file_readonly(string filePath); + FileStream OpenFileReadonly(string filePath); /// <summary> /// Opens a file exclusively /// </summary> /// <param name="filePath">Path to the file name</param> /// <returns>A file stream object for use after accessing the file</returns> - FileStream open_file_exclusive(string filePath); + FileStream OpenFileExclusive(string filePath); /// <summary> /// Writes the file text to the specified path /// </summary> /// <param name="filePath">The file path</param> /// <param name="fileText">The file text</param> - void write_file(string filePath, string fileText); + void WriteFile(string filePath, string fileText); /// <summary> /// Writes the file text to the specified path @@ -267,14 +284,14 @@ public interface IFileSystem /// <param name="filePath">The file path</param> /// <param name="fileText">The file text</param> /// <param name="encoding">The encoding</param> - void write_file(string filePath, string fileText, Encoding encoding); + void WriteFile(string filePath, string fileText, Encoding encoding); /// <summary> /// Writes a stream to a specified file path. /// </summary> /// <param name="filePath">The file path.</param> /// <param name="getStream">A deferred function of getting the stream</param> - void write_file(string filePath, Func<Stream> getStream); + void WriteFile(string filePath, Func<Stream> getStream); #endregion @@ -284,14 +301,14 @@ public interface IFileSystem /// Gets the current working directory of the application. /// </summary> /// <returns>The path to the directory</returns> - string get_current_directory(); + string GetCurrentDirectory(); /// <summary> /// Gets the names of subdirectories (including their paths) in the specified directory. /// </summary> /// <param name="directoryPath">The path for which an array of subdirectory names is returned. </param> /// <returns>An array of the names of subdirectories in "directory".</returns> - IEnumerable<string> get_directories(string directoryPath); + IEnumerable<string> GetDirectories(string directoryPath); /// <summary> /// Gets a list of directories inside an existing directory by pattern, and optionally by recursive search option. @@ -300,48 +317,61 @@ public interface IFileSystem /// <param name="pattern">The search pattern.</param> /// <param name="option">The option specifies whether the search operation should include all subdirectories or only the current directory.</param> /// <returns>Returns the names of directories (including their paths).</returns> - IEnumerable<string> get_directories(string directoryPath, string pattern, SearchOption option = SearchOption.TopDirectoryOnly); + IEnumerable<string> GetDirectories(string directoryPath, string pattern, SearchOption option = SearchOption.TopDirectoryOnly); /// <summary> /// Determines whether the given path refers to an existing directory on disk. /// </summary> /// <param name="directoryPath">The path to test.</param> /// <returns>True if path refers to an existing directory; otherwise, false.</returns> - bool directory_exists(string directoryPath); + bool DirectoryExists(string directoryPath); /// <summary> /// Gets the name of the directory. /// </summary> /// <param name="filePath">The file path.</param> /// <returns>Directory information for path, or Nothing if path denotes a root directory or is null. Returns String.Empty if path does not contain directory information.</returns> - string get_directory_name(string filePath); + string GetDirectoryName(string filePath); /// <summary> /// Returns a DirectoryInfo object from a string /// </summary> /// <param name="directoryPath">Full path to the directory you want the directory information for</param> /// <returns>DirectoryInfo object or reimplementation of a DirectoryInfo object that works with greater than 248 chars</returns> - dynamic get_directory_info_for(string directoryPath); + dynamic GetDirectoryInfo(string directoryPath); /// <summary> /// Returns a DirectoryInfo object from a string to a filepath /// </summary> /// <param name="filePath">Full path to the file you want directory information for</param> /// <returns>DirectoryInfo object or reimplementation of a DirectoryInfo object that works with greater than 248 chars</returns> - dynamic get_directory_info_from_file_path(string filePath); + dynamic GetFileDirectoryInfo(string filePath); /// <summary> /// Creates all directories and subdirectories in the specified path. /// </summary> /// <param name="directoryPath">The directory path to create. </param> - void create_directory(string directoryPath); + void CreateDirectory(string directoryPath); /// <summary> /// Moves a specified directory to a new location, providing the option to specify a new directory name. + /// Will fall back to do a file move until the first file is unable to be moved. /// </summary> /// <param name="directoryPath">The path of the directory to move.</param> /// <param name="newDirectoryPath">The new path for the directory.</param> - void move_directory(string directoryPath, string newDirectoryPath); + void MoveDirectory(string directoryPath, string newDirectoryPath); + + /// <summary> + /// Moves a specified directory to a new location, providing the option to specify a new directory name. + /// Will fall back to do a file move until the firlst file is unable to be moved if <paramref name="useFileMoveFallback"/> + /// is <c>true</c> + /// </summary> + /// <param name="directoryPath">The path of the directory to move.</param> + /// <param name="newDirectoryPath">The new path for the directory.</param> + /// <param name="useFileMoveFallback">Whether a fallback to move each individual files should be used if directory move fails.</param> + /// <param name="isSilent">Whether we should log retries or not.</param> + /// <remarks>Any underlying exception will be rethrown if <paramref name="useFileMoveFallback"/> is set to <c>false</c>.</remarks> + void MoveDirectory(string directoryPath, string newDirectoryPath, bool useFileMoveFallback, bool isSilent); /// <summary> /// Copies an existing directory to a new directory. Overwriting a directory of the same name is allowed. @@ -349,20 +379,29 @@ public interface IFileSystem /// <param name="sourceDirectoryPath">The source file directory. The directory to copy.</param> /// <param name="destinationDirectoryPath">The destination directory path.</param> /// <param name="overwriteExisting">true if the destination directory can be overwritten; otherwise, false.</param> - void copy_directory(string sourceDirectoryPath, string destinationDirectoryPath, bool overwriteExisting); + void CopyDirectory(string sourceDirectoryPath, string destinationDirectoryPath, bool overwriteExisting); + + /// <summary> + /// Copies an existing directory to a new directory. Overwriting a directory of the same name is allowed. + /// </summary> + /// <param name="sourceDirectoryPath">The source file directory. The directory to copy.</param> + /// <param name="destinationDirectoryPath">The destination directory path.</param> + /// <param name="overwriteExisting">true if the destination directory can be overwritten; otherwise, false.</param> + /// <param name="isSilent">Whether we should log retries or not.</param> + void CopyDirectory(string sourceDirectoryPath, string destinationDirectoryPath, bool overwriteExisting, bool isSilent); /// <summary> /// Creates all directories and subdirectories in the specified path if they have not already been created. /// </summary> /// <param name="directoryPath">The directory path to create. </param> - void create_directory_if_not_exists(string directoryPath); + void EnsureDirectoryExists(string directoryPath); /// <summary> /// Deletes a directory /// </summary> /// <param name="directoryPath">Path to the directory</param> /// <param name="recursive">Would you like to delete the directories inside of this directory? Almost always true.</param> - void delete_directory(string directoryPath, bool recursive); + void DeleteDirectory(string directoryPath, bool recursive); /// <summary> /// Deletes a directory @@ -370,7 +409,7 @@ public interface IFileSystem /// <param name="directoryPath">The directory path.</param> /// <param name="recursive">Would you like to delete the directories inside of this directory? Almost always true.</param> /// <param name="overrideAttributes">Override the attributes, e.g. delete readonly and/or system files.</param> - void delete_directory(string directoryPath, bool recursive, bool overrideAttributes); + void DeleteDirectory(string directoryPath, bool recursive, bool overrideAttributes); /// <summary> /// Deletes a directory @@ -379,14 +418,14 @@ public interface IFileSystem /// <param name="recursive">Would you like to delete the directories inside of this directory? Almost always true.</param> /// <param name="overrideAttributes">Override the attributes, e.g. delete readonly and/or system files.</param> /// <param name="isSilent">Should this method be silent? false by default</param> - void delete_directory(string directoryPath, bool recursive, bool overrideAttributes, bool isSilent); + void DeleteDirectory(string directoryPath, bool recursive, bool overrideAttributes, bool isSilent); /// <summary> /// Deletes a directory if it exists /// </summary> /// <param name="directoryPath">The directory path.</param> /// <param name="recursive">Would you like to delete the directories inside of this directory? Almost always true.</param> - void delete_directory_if_exists(string directoryPath, bool recursive); + void DeleteDirectoryChecked(string directoryPath, bool recursive); /// <summary> /// Deletes a directory if it exists @@ -394,7 +433,7 @@ public interface IFileSystem /// <param name="directoryPath">The directory path.</param> /// <param name="recursive">Would you like to delete the directories inside of this directory? Almost always true.</param> /// <param name="overrideAttributes">Override the attributes, e.g. delete readonly and/or system files.</param> - void delete_directory_if_exists(string directoryPath, bool recursive, bool overrideAttributes); + void DeleteDirectoryChecked(string directoryPath, bool recursive, bool overrideAttributes); /// <summary> /// Deletes a directory if it exists @@ -403,7 +442,7 @@ public interface IFileSystem /// <param name="recursive">Would you like to delete the directories inside of this directory? Almost always true.</param> /// <param name="overrideAttributes">Override the attributes, e.g. delete readonly and/or system files.</param> /// <param name="isSilent">Should this method be silent? false by default</param> - void delete_directory_if_exists(string directoryPath, bool recursive, bool overrideAttributes, bool isSilent); + void DeleteDirectoryChecked(string directoryPath, bool recursive, bool overrideAttributes, bool isSilent); #endregion @@ -412,13 +451,175 @@ public interface IFileSystem /// </summary> /// <param name="path">The path.</param> /// <param name="attributes">The attributes.</param> - void ensure_file_attribute_set(string path, FileAttributes attributes); + void EnsureFileAttributeSet(string path, FileAttributes attributes); /// <summary> /// Ensure file attributes are removed from a specified path. /// </summary> /// <param name="path">The path.</param> /// <param name="attributes">The attributes.</param> + void EnsureFileAttributeRemoved(string path, FileAttributes attributes); + + +#pragma warning disable IDE1006 + [Obsolete("This overload is deprecated and will be removed in v3.")] + string combine_paths(string leftItem, params string[] rightItems); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + string get_full_path(string path); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + string get_temp_path(); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + char get_path_directory_separator_char(); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + string get_executable_path(string executableName); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + string get_current_assembly_path(); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + IEnumerable<string> get_files(string directoryPath, string pattern = "*.*", SearchOption option = SearchOption.TopDirectoryOnly); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + IEnumerable<string> get_files(string directoryPath, string[] extensions, SearchOption option = SearchOption.TopDirectoryOnly); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + bool file_exists(string filePath); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + string get_file_name(string filePath); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + string get_file_name_without_extension(string filePath); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + string get_file_extension(string filePath); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + dynamic get_file_info_for(string filePath); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + DateTime get_file_modified_date(string filePath); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + long get_file_size(string filePath); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + string get_file_version_for(string filePath); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + bool is_system_file(dynamic file); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + bool is_readonly_file(dynamic file); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + bool is_hidden_file(dynamic file); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + bool is_encrypted_file(dynamic file); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + string get_file_date(dynamic file); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + void move_file(string filePath, string newFilePath); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + void copy_file(string sourceFilePath, string destinationFilePath, bool overwriteExisting); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + bool copy_file_unsafe(string sourceFilePath, string destinationFilePath, bool overwriteExisting); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + void replace_file(string sourceFilePath, string destinationFilePath, string backupFilePath); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + void delete_file(string filePath); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + FileStream create_file(string filePath); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + string read_file(string filePath); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + byte[] read_file_bytes(string filePath); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + FileStream open_file_readonly(string filePath); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + FileStream open_file_exclusive(string filePath); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + void write_file(string filePath, string fileText); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + void write_file(string filePath, string fileText, Encoding encoding); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + void write_file(string filePath, Func<Stream> getStream); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + string get_current_directory(); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + IEnumerable<string> get_directories(string directoryPath); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + IEnumerable<string> get_directories(string directoryPath, string pattern, SearchOption option = SearchOption.TopDirectoryOnly); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + bool directory_exists(string directoryPath); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + string get_directory_name(string filePath); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + dynamic get_directory_info_for(string directoryPath); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + dynamic get_directory_info_from_file_path(string filePath); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + void create_directory(string directoryPath); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + void move_directory(string directoryPath, string newDirectoryPath); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + void copy_directory(string sourceDirectoryPath, string destinationDirectoryPath, bool overwriteExisting); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + void create_directory_if_not_exists(string directoryPath); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + void delete_directory(string directoryPath, bool recursive); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + void delete_directory(string directoryPath, bool recursive, bool overrideAttributes); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + void delete_directory(string directoryPath, bool recursive, bool overrideAttributes, bool isSilent); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + void delete_directory_if_exists(string directoryPath, bool recursive); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + void delete_directory_if_exists(string directoryPath, bool recursive, bool overrideAttributes); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + void delete_directory_if_exists(string directoryPath, bool recursive, bool overrideAttributes, bool isSilent); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + void ensure_file_attribute_set(string path, FileAttributes attributes); + + [Obsolete("This overload is deprecated and will be removed in v3.")] void ensure_file_attribute_removed(string path, FileAttributes attributes); +#pragma warning restore IDE1006 } } diff --git a/src/chocolatey/infrastructure/guards/Ensure.cs b/src/chocolatey/infrastructure/guards/Ensure.cs index a2966f416a..de4409afb9 100644 --- a/src/chocolatey/infrastructure/guards/Ensure.cs +++ b/src/chocolatey/infrastructure/guards/Ensure.cs @@ -22,41 +22,51 @@ namespace chocolatey.infrastructure.guards public static class Ensure { - public static EnsureString that(Expression<Func<string>> expression) + public static EnsureString That(Expression<Func<string>> expression) { - var memberName = expression.get_name_on_right().Member.Name; + var memberName = expression.GetNameOnRight().Member.Name; return new EnsureString(memberName, expression.Compile().Invoke()); } - public static Ensure<TypeToEnsure> that<TypeToEnsure>(Expression<Func<TypeToEnsure>> expression) where TypeToEnsure : class + public static Ensure<TypeToEnsure> That<TypeToEnsure>(Expression<Func<TypeToEnsure>> expression) where TypeToEnsure : class { - var memberName = expression.get_name_on_right().Member.Name; + var memberName = expression.GetNameOnRight().Member.Name; return new Ensure<TypeToEnsure>(memberName, expression.Compile().Invoke()); } - private static MemberExpression get_name_on_right(this Expression e) + // This method needs a beter name. + private static MemberExpression GetNameOnRight(this Expression e) { - if (e is LambdaExpression) - return get_name_on_right(((LambdaExpression) e).Body); + if (e is LambdaExpression lambdaExpr) + return GetNameOnRight(lambdaExpr.Body); - if (e is MemberExpression) - return (MemberExpression) e; + if (e is MemberExpression memberExpr) + return memberExpr; - if (e is MethodCallExpression) + if (e is MethodCallExpression methodExpr) { - var callExpression = (MethodCallExpression) e; - var member = callExpression.Arguments.Count > 0 ? callExpression.Arguments[0] : callExpression.Object; - return get_name_on_right(member); + var member = methodExpr.Arguments.Count > 0 ? methodExpr.Arguments[0] : methodExpr.Object; + return GetNameOnRight(member); } - if (e is UnaryExpression) + if (e is UnaryExpression unaryExpr) { - var unaryExpression = (UnaryExpression) e; - return get_name_on_right(unaryExpression.Operand); + return GetNameOnRight(unaryExpr.Operand); } - throw new Exception("Unable to find member for {0}".format_with(e.to_string())); + throw new Exception("Unable to find member for {0}".FormatWith(e.ToStringSafe())); } + + +#pragma warning disable IDE1006 + [Obsolete("This overload is deprecated and will be removed in v3.")] + public static EnsureString that(Expression<Func<string>> expression) + => That(expression); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public static Ensure<TypeToEnsure> that<TypeToEnsure>(Expression<Func<TypeToEnsure>> expression) where TypeToEnsure : class + => That(expression); +#pragma warning restore IDE1006 } public class EnsureString : Ensure<string> @@ -66,32 +76,41 @@ public EnsureString(string name, string value) { } - public EnsureString is_not_null_or_whitespace() + public EnsureString NotNullOrWhitespace() { - is_not_null(); + NotNull(); if (string.IsNullOrWhiteSpace(Value)) { - throw new ArgumentException(Name, "Value for {0} cannot be empty or only contain whitespace.".format_with(Name)); + throw new ArgumentException(Name, "Value for {0} cannot be empty or only contain whitespace.".FormatWith(Name)); } return this; } - public EnsureString has_any_extension(params string[] extensions) + public EnsureString HasExtension(params string[] extensions) { var actualExtension = Path.GetExtension(Value); foreach (var extension in extensions) { - if (extension.is_equal_to(actualExtension)) + if (extension.IsEqualTo(actualExtension)) { return this; } } - throw new ArgumentException(Name, "Value for {0} must contain one of the following extensions: {1}".format_with(Name, string.Join(", ", extensions))); + throw new ArgumentException(Name, "Value for {0} must contain one of the following extensions: {1}".FormatWith(Name, string.Join(", ", extensions))); } +#pragma warning disable IDE1006 + [Obsolete("This overload is deprecated and will be removed in v3.")] + public EnsureString is_not_null_or_whitespace() + => NotNullOrWhitespace(); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public EnsureString has_any_extension(params string[] extensions) + => HasExtension(extensions); +#pragma warning restore IDE1006 } public class Ensure<EnsurableType> where EnsurableType : class @@ -105,23 +124,32 @@ public Ensure(string name, EnsurableType value) Value = value; } - public void is_not_null() + public void NotNull() { if (Value == null) { - throw new ArgumentNullException(Name, "Value for {0} cannot be null.".format_with(Name)); + throw new ArgumentNullException(Name, "Value for {0} cannot be null.".FormatWith(Name)); } } - public void meets(Func<EnsurableType, bool> ensureFunction, Action<string, EnsurableType> exceptionAction) + public void Meets(Func<EnsurableType, bool> ensureFunction, Action<string, EnsurableType> exceptionAction) { - Ensure.that(() => ensureFunction).is_not_null(); - Ensure.that(() => exceptionAction).is_not_null(); + Ensure.That(() => ensureFunction).NotNull(); + Ensure.That(() => exceptionAction).NotNull(); if (!ensureFunction(Value)) { exceptionAction.Invoke(Name, Value); } } +#pragma warning disable IDE1006 + [Obsolete("This overload is deprecated and will be removed in v3.")] + public void is_not_null() + => NotNull(); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public void meets(Func<EnsurableType, bool> ensureFunction, Action<string, EnsurableType> exceptionAction) + => Meets(ensureFunction, exceptionAction); +#pragma warning restore IDE1006 } } diff --git a/src/chocolatey/infrastructure/information/ExtensionInformation.cs b/src/chocolatey/infrastructure/information/ExtensionInformation.cs index 219f86cb08..a55c0fabd2 100644 --- a/src/chocolatey/infrastructure/information/ExtensionInformation.cs +++ b/src/chocolatey/infrastructure/information/ExtensionInformation.cs @@ -24,7 +24,7 @@ public class ExtensionInformation public ExtensionInformation(IAssembly assembly) { Name = assembly.GetName().Name; - Version = VersionInformation.get_current_informational_version(assembly); + Version = VersionInformation.GetCurrentInformationalVersion(assembly); Status = ExtensionStatus.Unknown; } @@ -57,7 +57,7 @@ public override int GetHashCode() public override string ToString() { - return "{0} v{1}".format_with(Name, Version); + return "{0} v{1}".FormatWith(Name, Version); } } diff --git a/src/chocolatey/infrastructure/information/ProcessInformation.cs b/src/chocolatey/infrastructure/information/ProcessInformation.cs index 9412fc33b1..e70e1b253e 100644 --- a/src/chocolatey/infrastructure/information/ProcessInformation.cs +++ b/src/chocolatey/infrastructure/information/ProcessInformation.cs @@ -23,9 +23,9 @@ namespace chocolatey.infrastructure.information public sealed class ProcessInformation { - public static bool user_is_administrator() + public static bool UserIsAdministrator() { - if (Platform.get_platform() != PlatformType.Windows) return false; + if (Platform.GetPlatform() != PlatformType.Windows) return false; var isAdmin = false; @@ -38,7 +38,7 @@ public static bool user_is_administrator() // Any version of Windows less than 6 does not have UAC // so bail with the answer from the above check - if (Platform.get_version().Major < 6) return isAdmin; + if (Platform.GetVersion().Major < 6) return isAdmin; if (!isAdmin) { @@ -73,7 +73,7 @@ public static bool user_is_administrator() if (!successfulCall) { - "chocolatey".Log().Warn("Error during native GetTokenInformation call - {0}".format_with(Marshal.GetLastWin32Error())); + "chocolatey".Log().Warn("Error during native GetTokenInformation call - {0}".FormatWith(Marshal.GetLastWin32Error())); if (tokenInformation != IntPtr.Zero) Marshal.FreeHGlobal(tokenInformation); } @@ -100,9 +100,9 @@ public static bool user_is_administrator() return isAdmin; } - public static bool process_is_elevated() + public static bool IsElevated() { - if (Platform.get_platform() != PlatformType.Windows) return false; + if (Platform.GetPlatform() != PlatformType.Windows) return false; using (var identity = WindowsIdentity.GetCurrent(TokenAccessLevels.Query | TokenAccessLevels.Duplicate)) { @@ -116,19 +116,19 @@ public static bool process_is_elevated() return false; } - public static bool user_is_terminal_services() + public static bool UserIsTerminalServices() { - return Environment.GetEnvironmentVariable("SESSIONNAME").to_string().contains("rdp-"); + return Environment.GetEnvironmentVariable("SESSIONNAME").ToStringSafe().ContainsSafe("rdp-"); } - public static bool user_is_remote() + public static bool UserIsRemote() { - return user_is_terminal_services() || Environment.GetEnvironmentVariable("SESSIONNAME").to_string() == string.Empty; + return UserIsTerminalServices() || Environment.GetEnvironmentVariable("SESSIONNAME").ToStringSafe() == string.Empty; } - public static bool user_is_system() + public static bool UserIsSystem() { - if (Platform.get_platform() != PlatformType.Windows) return false; + if (Platform.GetPlatform() != PlatformType.Windows) return false; var isSystem = false; @@ -140,8 +140,6 @@ public static bool user_is_system() return isSystem; } - // ReSharper disable InconsistentNaming - /* https://msdn.microsoft.com/en-us/library/windows/desktop/aa376402.aspx BOOL WINAPI ConvertStringSidToSid( @@ -228,7 +226,26 @@ enum TokenElevationType TokenElevationTypeLimited } - // ReSharper restore InconsistentNaming +#pragma warning disable IDE1006 + [Obsolete("This overload is deprecated and will be removed in v3.")] + public static bool user_is_administrator() + => UserIsAdministrator(); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public static bool process_is_elevated() + => IsElevated(); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public static bool user_is_terminal_services() + => UserIsTerminalServices(); + [Obsolete("This overload is deprecated and will be removed in v3.")] + public static bool user_is_remote() + => UserIsRemote(); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public static bool user_is_system() + => UserIsSystem(); +#pragma warning restore IDE1006 } } diff --git a/src/chocolatey/infrastructure/information/VersionInformation.cs b/src/chocolatey/infrastructure/information/VersionInformation.cs index f3aed7a37d..3c5b52960e 100644 --- a/src/chocolatey/infrastructure/information/VersionInformation.cs +++ b/src/chocolatey/infrastructure/information/VersionInformation.cs @@ -16,12 +16,13 @@ namespace chocolatey.infrastructure.information { + using System; using System.Diagnostics; using adapters; public sealed class VersionInformation { - public static string get_current_assembly_version(IAssembly assembly = null) + public static string GetCurrentAssemblyVersion(IAssembly assembly = null) { string version = null; if (assembly == null) assembly = Assembly.GetExecutingAssembly(); @@ -37,9 +38,9 @@ public static string get_current_assembly_version(IAssembly assembly = null) var attributes= assembly.UnderlyingType.GetCustomAttributesData(); foreach (var attribute in attributes) { - if (attribute.to_string().Contains("AssemblyFileVersion")) + if (attribute.ToStringSafe().Contains("AssemblyFileVersion")) { - version = attribute.ConstructorArguments[0].Value.to_string(); + version = attribute.ConstructorArguments[0].Value.ToStringSafe(); break; } } @@ -48,7 +49,7 @@ public static string get_current_assembly_version(IAssembly assembly = null) return version; } - public static string get_current_informational_version(IAssembly assembly = null) + public static string GetCurrentInformationalVersion(IAssembly assembly = null) { string version = null; if (assembly == null) assembly = Assembly.GetExecutingAssembly(); @@ -64,9 +65,9 @@ public static string get_current_informational_version(IAssembly assembly = null var attributes = assembly.UnderlyingType.GetCustomAttributesData(); foreach (var attribute in attributes) { - if (attribute.to_string().Contains("AssemblyInformationalVersion")) + if (attribute.ToStringSafe().Contains("AssemblyInformationalVersion")) { - version = attribute.ConstructorArguments[0].Value.to_string(); + version = attribute.ConstructorArguments[0].Value.ToStringSafe(); break; } } @@ -75,16 +76,16 @@ public static string get_current_informational_version(IAssembly assembly = null return version; } - public static string get_minimum_chocolatey_version(IAssembly assembly = null) + public static string GetMinimumChocolateyVersion(IAssembly assembly = null) { if (assembly == null) assembly = Assembly.GetExecutingAssembly(); var attributeData = assembly.UnderlyingType.GetCustomAttributesData(); foreach (var attribute in attributeData) { - if (attribute.to_string().Contains("MinimumChocolateyVersion")) + if (attribute.ToStringSafe().Contains("MinimumChocolateyVersion")) { - return attribute.ConstructorArguments[0].Value.to_string(); + return attribute.ConstructorArguments[0].Value.ToStringSafe(); } } @@ -93,5 +94,19 @@ public static string get_minimum_chocolatey_version(IAssembly assembly = null) // attribute on the assembly to say what the minimum required Chocolatey version is. return "1.0.0"; } + +#pragma warning disable IDE1006 + [Obsolete("This overload is deprecated and will be removed in v3.")] + public static string get_current_assembly_version(IAssembly assembly = null) + => GetCurrentAssemblyVersion(assembly = null); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public static string get_current_informational_version(IAssembly assembly = null) + => GetCurrentInformationalVersion(assembly); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public static string get_minimum_chocolatey_version(IAssembly assembly = null) + => GetMinimumChocolateyVersion(assembly); +#pragma warning restore IDE1006 } } diff --git a/src/chocolatey/infrastructure/licensing/ChocolateyLicense.cs b/src/chocolatey/infrastructure/licensing/ChocolateyLicense.cs index 109a4ebf32..65c4851616 100644 --- a/src/chocolatey/infrastructure/licensing/ChocolateyLicense.cs +++ b/src/chocolatey/infrastructure/licensing/ChocolateyLicense.cs @@ -17,6 +17,7 @@ namespace chocolatey.infrastructure.licensing { using adapters; + using System; using DateTime = System.DateTime; public sealed class ChocolateyLicense @@ -33,12 +34,18 @@ public sealed class ChocolateyLicense public DateTime? ExpirationDate { get; set; } public bool IsCompatible { get; set; } - public bool is_licensed_version() + public bool IsLicensedVersion() { return IsValid && LicenseType != ChocolateyLicenseType.Unknown && LicenseType != ChocolateyLicenseType.Foss ; } + +#pragma warning disable IDE1006 + [Obsolete("This overload is deprecated and will be removed in v3.")] + public bool is_licensed_version() + => IsLicensedVersion(); +#pragma warning restore IDE1006 } } diff --git a/src/chocolatey/infrastructure/licensing/License.cs b/src/chocolatey/infrastructure/licensing/License.cs index d6c87a8f6d..f6fe5090a1 100644 --- a/src/chocolatey/infrastructure/licensing/License.cs +++ b/src/chocolatey/infrastructure/licensing/License.cs @@ -24,10 +24,10 @@ namespace chocolatey.infrastructure.licensing public static class License { - public static ChocolateyLicense validate_license() + public static ChocolateyLicense ValidateLicense() { - var license = LicenseValidation.validate(); - if (license.is_licensed_version()) + var license = LicenseValidation.Validate(); + if (license.IsLicensedVersion()) { try { @@ -36,7 +36,7 @@ public static ChocolateyLicense validate_license() #else var chocolateyPublicKey = ApplicationParameters.UnofficialChocolateyPublicKey; #endif - var licensedAssembly = AssemblyResolution.load_extension(ApplicationParameters.LicensedChocolateyAssemblySimpleName); + var licensedAssembly = AssemblyResolution.LoadExtension(ApplicationParameters.LicensedChocolateyAssemblySimpleName); if (licensedAssembly == null) { @@ -45,16 +45,16 @@ public static ChocolateyLicense validate_license() license.AssemblyLoaded = true; license.Assembly = licensedAssembly; - license.Version = VersionInformation.get_current_informational_version(licensedAssembly); + license.Version = VersionInformation.GetCurrentInformationalVersion(licensedAssembly); // The licensed assembly is installed, check its supported Chocolatey versions and/or the assembly // version so we can attempt to determine whether it's compatible with this version of Chocolatey. - var minimumChocolateyVersionString = VersionInformation.get_minimum_chocolatey_version(licensedAssembly); - "chocolatey".Log().Debug("Minimum Chocolatey Version: '{0}'".format_with(minimumChocolateyVersionString)); - var currentChocolateyVersionString = VersionInformation.get_current_assembly_version(); - "chocolatey".Log().Debug("Current Chocolatey Version: '{0}'".format_with(currentChocolateyVersionString)); - var currentChocolateyLicensedVersionString = VersionInformation.get_current_assembly_version(licensedAssembly); - "chocolatey".Log().Debug("Current Chocolatey Licensed Version: '{0}'".format_with(currentChocolateyLicensedVersionString)); + var minimumChocolateyVersionString = VersionInformation.GetMinimumChocolateyVersion(licensedAssembly); + "chocolatey".Log().Debug("Minimum Chocolatey Version: '{0}'".FormatWith(minimumChocolateyVersionString)); + var currentChocolateyVersionString = VersionInformation.GetCurrentAssemblyVersion(); + "chocolatey".Log().Debug("Current Chocolatey Version: '{0}'".FormatWith(currentChocolateyVersionString)); + var currentChocolateyLicensedVersionString = VersionInformation.GetCurrentAssemblyVersion(licensedAssembly); + "chocolatey".Log().Debug("Current Chocolatey Licensed Version: '{0}'".FormatWith(currentChocolateyLicensedVersionString)); var minimumChocolateyVersion = new Version(minimumChocolateyVersionString); var currentChocolateyVersion = new Version(currentChocolateyVersionString); @@ -68,7 +68,7 @@ public static ChocolateyLicense validate_license() } Type licensedComponent = licensedAssembly.GetType(ApplicationParameters.LicensedComponentRegistry, throwOnError: false, ignoreCase: true); - SimpleInjectorContainer.add_component_registry_class(licensedComponent); + SimpleInjectorContainer.AddComponentRegistryClass(licensedComponent); } catch (Exception ex) { @@ -76,7 +76,7 @@ public static ChocolateyLicense validate_license() @"A valid Chocolatey license was found, but the chocolatey.licensed.dll assembly could not be loaded: {0} Ensure that the chocolatey.licensed.dll exists at the following path: - '{1}'".format_with(ex.Message, ApplicationParameters.LicensedAssemblyLocation)); + '{1}'".FormatWith(ex.Message, ApplicationParameters.LicensedAssemblyLocation)); "chocolatey".Log().Warn( ChocolateyLoggers.Important, @@ -87,5 +87,11 @@ public static ChocolateyLicense validate_license() return license; } + +#pragma warning disable IDE1006 + [Obsolete("This overload is deprecated and will be removed in v3.")] + public static ChocolateyLicense validate_license() + => ValidateLicense(); +#pragma warning restore IDE1006 } } diff --git a/src/chocolatey/infrastructure/licensing/LicenseValidation.cs b/src/chocolatey/infrastructure/licensing/LicenseValidation.cs index c322b2cafa..fe30004b5f 100644 --- a/src/chocolatey/infrastructure/licensing/LicenseValidation.cs +++ b/src/chocolatey/infrastructure/licensing/LicenseValidation.cs @@ -24,10 +24,10 @@ namespace chocolatey.infrastructure.licensing public sealed class LicenseValidation { - private const string PUBLIC_KEY = + private const string PublicKey = @"<RSAKeyValue><Modulus>rznyhs3OslLqL7A7qav9bSHYGQmgWVsP/L47dWU7yF3EHsiYZuJNLlq8tQkPql/LB1FfLihiGsOKKUF1tmxihcRUrDaYkK1IYY3A+uJWkBglDUOUjnoDboI1FgF3wmXSb07JC8JCVYWjchq+h6MV9aDZaigA5MqMKNj9FE14f68=</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>"; - public static ChocolateyLicense validate() + public static ChocolateyLicense Validate() { var chocolateyLicense = new ChocolateyLicense { @@ -35,7 +35,7 @@ public static ChocolateyLicense validate() IsCompatible = true }; - var regularLogOutput = determine_if_regular_output_for_logging(); + var regularLogOutput = ShouldLogErrorsToConsole(); string licenseFile = ApplicationParameters.LicenseFileLocation; var userLicenseFile = ApplicationParameters.UserLicenseFileLocation; @@ -54,8 +54,8 @@ public static ChocolateyLicense validate() if (Directory.GetFiles(licenseDirectory).Length != 0) { "chocolatey".Log().Error(regularLogOutput ? ChocolateyLoggers.Normal : ChocolateyLoggers.LogFileOnly, @"Files found in directory '{0}' but not a - valid license file. License should be named '{1}'.".format_with(licenseDirectory, licenseFileName)); - "chocolatey".Log().Warn(ChocolateyLoggers.Important,@" Rename license file to '{0}' to allow commercial features.".format_with(licenseFileName)); + valid license file. License should be named '{1}'.".FormatWith(licenseDirectory, licenseFileName)); + "chocolatey".Log().Warn(ChocolateyLoggers.Important,@" Rename license file to '{0}' to allow commercial features.".FormatWith(licenseFileName)); } } @@ -64,16 +64,16 @@ public static ChocolateyLicense validate() if (File.Exists(Path.Combine(ApplicationParameters.InstallLocation, licenseFileName)) || File.Exists(Path.Combine(ApplicationParameters.InstallLocation, licenseFileName + ".txt"))) { "chocolatey".Log().Error(regularLogOutput ? ChocolateyLoggers.Normal : ChocolateyLoggers.LogFileOnly, @"Chocolatey license found in the wrong location. File must be located at - '{0}'.".format_with(ApplicationParameters.LicenseFileLocation)); - "chocolatey".Log().Warn(regularLogOutput ? ChocolateyLoggers.Important : ChocolateyLoggers.LogFileOnly, @" Move license file to '{0}' to allow commercial features.".format_with(ApplicationParameters.LicenseFileLocation)); + '{0}'.".FormatWith(ApplicationParameters.LicenseFileLocation)); + "chocolatey".Log().Warn(regularLogOutput ? ChocolateyLoggers.Important : ChocolateyLoggers.LogFileOnly, @" Move license file to '{0}' to allow commercial features.".FormatWith(ApplicationParameters.LicenseFileLocation)); } } // no IFileSystem at this point if (File.Exists(licenseFile)) { - "chocolatey".Log().Debug("Evaluating license file found at '{0}'".format_with(licenseFile)); - var license = new LicenseValidator(PUBLIC_KEY, licenseFile); + "chocolatey".Log().Debug("Evaluating license file found at '{0}'".FormatWith(licenseFile)); + var license = new LicenseValidator(PublicKey, licenseFile); try { @@ -91,21 +91,21 @@ public static ChocolateyLicense validate() { chocolateyLicense.IsValid = false; chocolateyLicense.InvalidReason = e.Message; - "chocolatey".Log().Error(regularLogOutput ? ChocolateyLoggers.Normal : ChocolateyLoggers.LogFileOnly, "A license was not found for a licensed version of Chocolatey:{0} {1}{0} {2}".format_with(Environment.NewLine, e.Message, - "A license was also not found in the user profile: '{0}'.".format_with(ApplicationParameters.UserLicenseFileLocation))); + "chocolatey".Log().Error(regularLogOutput ? ChocolateyLoggers.Normal : ChocolateyLoggers.LogFileOnly, "A license was not found for a licensed version of Chocolatey:{0} {1}{0} {2}".FormatWith(Environment.NewLine, e.Message, + "A license was also not found in the user profile: '{0}'.".FormatWith(ApplicationParameters.UserLicenseFileLocation))); } catch (Exception e) { //license may be invalid chocolateyLicense.IsValid = false; chocolateyLicense.InvalidReason = e.Message; - "chocolatey".Log().Error(regularLogOutput ? ChocolateyLoggers.Normal : ChocolateyLoggers.LogFileOnly, "A license was found for a licensed version of Chocolatey, but is invalid:{0} {1}".format_with(Environment.NewLine, e.Message)); + "chocolatey".Log().Error(regularLogOutput ? ChocolateyLoggers.Normal : ChocolateyLoggers.LogFileOnly, "A license was found for a licensed version of Chocolatey, but is invalid:{0} {1}".FormatWith(Environment.NewLine, e.Message)); } var chocolateyLicenseType = ChocolateyLicenseType.Unknown; try { - Enum.TryParse(license.LicenseType.to_string(), true, out chocolateyLicenseType); + Enum.TryParse(license.LicenseType.ToStringSafe(), true, out chocolateyLicenseType); } catch (Exception) { @@ -124,7 +124,7 @@ public static ChocolateyLicense validate() chocolateyLicense.LicenseType = chocolateyLicenseType; chocolateyLicense.ExpirationDate = license.ExpirationDate; chocolateyLicense.Name = license.Name; - chocolateyLicense.Id = license.UserId.to_string(); + chocolateyLicense.Id = license.UserId.ToStringSafe(); } else { @@ -135,15 +135,22 @@ public static ChocolateyLicense validate() return chocolateyLicense; } - private static bool determine_if_regular_output_for_logging() + private static bool ShouldLogErrorsToConsole() { var args = Environment.GetCommandLineArgs(); + // I think this check is incorrect??? if --version is supposed to return false, it can return true at this point? if (args == null || args.Length < 2) return true; - var firstArg = args[1].to_string(); - if (firstArg.is_equal_to("-v") || firstArg.is_equal_to("--version")) return false; + var firstArg = args[1].ToStringSafe(); + if (firstArg.IsEqualTo("-v") || firstArg.IsEqualTo("--version")) return false; return true; } + +#pragma warning disable IDE1006 + [Obsolete("This overload is deprecated and will be removed in v3.")] + public static ChocolateyLicense validate() + => Validate(); +#pragma warning restore IDE1006 } } diff --git a/src/chocolatey/infrastructure/logging/AggregateLog.cs b/src/chocolatey/infrastructure/logging/AggregateLog.cs index 0397399d25..87b7d0c4dd 100644 --- a/src/chocolatey/infrastructure/logging/AggregateLog.cs +++ b/src/chocolatey/infrastructure/logging/AggregateLog.cs @@ -19,8 +19,6 @@ namespace chocolatey.infrastructure.logging using System; using System.Collections.Generic; - // ReSharper disable InconsistentNaming - public sealed class AggregateLog : ILog, ILog<AggregateLog> { public IEnumerable<ILog> Loggers { get; private set; } @@ -37,7 +35,7 @@ public AggregateLog(IEnumerable<ILog> loggers) public void InitializeFor(string loggerName) { - foreach (var logger in Loggers.or_empty_list_if_null()) + foreach (var logger in Loggers.OrEmpty()) { logger.InitializeFor(loggerName); } @@ -45,7 +43,7 @@ public void InitializeFor(string loggerName) public void Debug(string message, params object[] formatting) { - foreach (var logger in Loggers.or_empty_list_if_null()) + foreach (var logger in Loggers.OrEmpty()) { logger.Debug(message, formatting); } @@ -53,7 +51,7 @@ public void Debug(string message, params object[] formatting) public void Debug(Func<string> message) { - foreach (var logger in Loggers.or_empty_list_if_null()) + foreach (var logger in Loggers.OrEmpty()) { logger.Debug(message); } @@ -61,7 +59,7 @@ public void Debug(Func<string> message) public void Info(string message, params object[] formatting) { - foreach (var logger in Loggers.or_empty_list_if_null()) + foreach (var logger in Loggers.OrEmpty()) { logger.Info(message, formatting); } @@ -69,7 +67,7 @@ public void Info(string message, params object[] formatting) public void Info(Func<string> message) { - foreach (var logger in Loggers.or_empty_list_if_null()) + foreach (var logger in Loggers.OrEmpty()) { logger.Info(message); } @@ -77,7 +75,7 @@ public void Info(Func<string> message) public void Warn(string message, params object[] formatting) { - foreach (var logger in Loggers.or_empty_list_if_null()) + foreach (var logger in Loggers.OrEmpty()) { logger.Warn(message, formatting); } @@ -85,7 +83,7 @@ public void Warn(string message, params object[] formatting) public void Warn(Func<string> message) { - foreach (var logger in Loggers.or_empty_list_if_null()) + foreach (var logger in Loggers.OrEmpty()) { logger.Warn(message); } @@ -93,7 +91,7 @@ public void Warn(Func<string> message) public void Error(string message, params object[] formatting) { - foreach (var logger in Loggers.or_empty_list_if_null()) + foreach (var logger in Loggers.OrEmpty()) { logger.Error(message, formatting); } @@ -101,7 +99,7 @@ public void Error(string message, params object[] formatting) public void Error(Func<string> message) { - foreach (var logger in Loggers.or_empty_list_if_null()) + foreach (var logger in Loggers.OrEmpty()) { logger.Error(message); } @@ -109,7 +107,7 @@ public void Error(Func<string> message) public void Fatal(string message, params object[] formatting) { - foreach (var logger in Loggers.or_empty_list_if_null()) + foreach (var logger in Loggers.OrEmpty()) { logger.Fatal(message, formatting); } @@ -117,12 +115,10 @@ public void Fatal(string message, params object[] formatting) public void Fatal(Func<string> message) { - foreach (var logger in Loggers.or_empty_list_if_null()) + foreach (var logger in Loggers.OrEmpty()) { logger.Fatal(message); } } } - - // ReSharper restore InconsistentNaming } diff --git a/src/chocolatey/infrastructure/logging/ILog.cs b/src/chocolatey/infrastructure/logging/ILog.cs index fdb825ff78..babfcf270d 100644 --- a/src/chocolatey/infrastructure/logging/ILog.cs +++ b/src/chocolatey/infrastructure/logging/ILog.cs @@ -18,8 +18,6 @@ namespace chocolatey.infrastructure.logging { using System; - // ReSharper disable InconsistentNaming - /// <summary> /// Custom interface for logging messages /// </summary> @@ -97,8 +95,6 @@ public interface ILog void Fatal(Func<string> message); } - // ReSharper restore InconsistentNaming - /// <summary> /// Ensures a default constructor for the logger type /// </summary> diff --git a/src/chocolatey/infrastructure/logging/Log.cs b/src/chocolatey/infrastructure/logging/Log.cs index b3ab3801bb..2a4b9f1e12 100644 --- a/src/chocolatey/infrastructure/logging/Log.cs +++ b/src/chocolatey/infrastructure/logging/Log.cs @@ -18,8 +18,6 @@ namespace chocolatey.infrastructure.logging { using System; - // ReSharper disable InconsistentNaming - /// <summary> /// Logger type initialization /// </summary> @@ -75,6 +73,4 @@ public static ILog GetLoggerFor(string objectName) return logger; } } - - // ReSharper restore InconsistentNaming } diff --git a/src/chocolatey/infrastructure/logging/Log4NetAppenderConfiguration.cs b/src/chocolatey/infrastructure/logging/Log4NetAppenderConfiguration.cs index 0953d107cd..2110f19989 100644 --- a/src/chocolatey/infrastructure/logging/Log4NetAppenderConfiguration.cs +++ b/src/chocolatey/infrastructure/logging/Log4NetAppenderConfiguration.cs @@ -39,7 +39,7 @@ public sealed class Log4NetAppenderConfiguration private static readonly log4net.ILog _logger = LogManager.GetLogger(typeof(Log4NetAppenderConfiguration)); private static Lazy<IConsole> _console = new Lazy<IConsole>(() => new Console()); [EditorBrowsable(EditorBrowsableState.Never)] - public static void initialize_with(Lazy<IConsole> console) + public static void InitializeWith(Lazy<IConsole> console) { _console = console; } @@ -50,9 +50,9 @@ private static IConsole Console } private static bool _alreadyConfiguredFileAppender; - private static readonly string _summaryLogAppenderName = "{0}.summary.log.appender".format_with(ApplicationParameters.Name); - private const string NORMAL_LOGGING_COLORED_APPENDER = "NormalLoggingColoredConsoleAppender"; - private const string IMPORTANT_LOGGING_COLORED_APPENDER = "ImportantLoggingColoredConsoleAppender"; + private static readonly string _summaryLogAppenderName = "{0}.summary.log.appender".FormatWith(ApplicationParameters.Name); + private const string NormalLoggingColoredAppender = "NormalLoggingColoredConsoleAppender"; + private const string ImportantLoggingColoredAppender = "ImportantLoggingColoredConsoleAppender"; /// <summary> /// Pulls xml configuration from embedded location and applies it. @@ -60,7 +60,7 @@ private static IConsole Console /// </summary> /// <param name="outputDirectory">The output directory.</param> /// <param name="excludeLoggerNames">Loggers, such as a verbose logger, to exclude from this.</param> - public static void configure(string outputDirectory = null, params string[] excludeLoggerNames) + public static void Configure(string outputDirectory = null, params string[] excludeLoggerNames) { GlobalContext.Properties["pid"] = System.Diagnostics.Process.GetCurrentProcess().Id; @@ -74,27 +74,27 @@ public static void configure(string outputDirectory = null, params string[] excl { var assembly = Assembly.GetExecutingAssembly(); var resource = ApplicationParameters.Log4NetConfigurationResource; - if (Platform.get_platform() != PlatformType.Windows) + if (Platform.GetPlatform() != PlatformType.Windows) { // it became much easier to do this once we realized that updating the current mappings is about impossible. resource = resource.Replace("log4net.", "log4net.mono."); } - Stream xmlConfigStream = assembly.get_manifest_stream(resource); + Stream xmlConfigStream = assembly.GetManifestStream(resource); XmlConfigurator.Configure(xmlConfigStream); _logger.DebugFormat("Configured Log4Net configuration ('{0}') from assembly {1}", resource, assembly.FullName); } - configure_info_logging_colors(); + ConfigureLoggingInfoColors(); if (!string.IsNullOrWhiteSpace(outputDirectory)) { - set_file_appender(outputDirectory, excludeLoggerNames); + SetFileAppender(outputDirectory, excludeLoggerNames); } } - private static void configure_info_logging_colors() + private static void ConfigureLoggingInfoColors() { try { @@ -102,7 +102,7 @@ private static void configure_info_logging_colors() var bgColor = Console.BackgroundColor; var fgColor = Console.ForegroundColor; ILoggerRepository logRepository = LogManager.GetRepository(Assembly.GetCallingAssembly().UnderlyingType); - foreach (var append in logRepository.GetAppenders().Where(a => a.Name.is_equal_to(NORMAL_LOGGING_COLORED_APPENDER)).or_empty_list_if_null()) + foreach (var append in logRepository.GetAppenders().Where(a => a.Name.IsEqualTo(NormalLoggingColoredAppender)).OrEmpty()) { var appender = append as ManagedColoredConsoleAppender; if (appender != null) @@ -156,7 +156,7 @@ private static void configure_info_logging_colors() } } - foreach (var append in logRepository.GetAppenders().Where(a => a.Name.is_equal_to(IMPORTANT_LOGGING_COLORED_APPENDER)).or_empty_list_if_null()) + foreach (var append in logRepository.GetAppenders().Where(a => a.Name.IsEqualTo(ImportantLoggingColoredAppender)).OrEmpty()) { var appender = append as ManagedColoredConsoleAppender; if (appender != null) @@ -206,7 +206,7 @@ private static void configure_info_logging_colors() /// </summary> /// <param name="outputDirectory">The output directory.</param> /// <param name="excludeLoggerNames">Loggers, such as a trace logger, to exclude from file appender.</param> - private static void set_file_appender(string outputDirectory, params string[] excludeLoggerNames) + private static void SetFileAppender(string outputDirectory, params string[] excludeLoggerNames) { if (excludeLoggerNames == null) excludeLoggerNames = new string[] {}; @@ -222,7 +222,7 @@ private static void set_file_appender(string outputDirectory, params string[] ex var app = new RollingFileAppender { - Name = "{0}.changes.log.appender".format_with(ApplicationParameters.Name), + Name = "{0}.changes.log.appender".FormatWith(ApplicationParameters.Name), File = Path.Combine(Path.GetFullPath(outputDirectory), ApplicationParameters.LoggingFile), Layout = layout, AppendToFile = true, @@ -250,7 +250,7 @@ private static void set_file_appender(string outputDirectory, params string[] ex infoOnlyAppender.ActivateOptions(); ILoggerRepository logRepository = LogManager.GetRepository(Assembly.GetCallingAssembly().UnderlyingType); - foreach (ILogger log in logRepository.GetCurrentLoggers().Where(l => excludeLoggerNames.All(name => !l.Name.is_equal_to(name))).or_empty_list_if_null()) + foreach (ILogger log in logRepository.GetCurrentLoggers().Where(l => excludeLoggerNames.All(name => !l.Name.IsEqualTo(name))).OrEmpty()) { var logger = log as Logger; if (logger != null) @@ -269,7 +269,7 @@ private static void set_file_appender(string outputDirectory, params string[] ex /// if set to <c>true</c> [enable debug]. /// </param> /// <param name="excludeAppenderNames">Appenders, such as a verbose console appender, to exclude from debug.</param> - public static void set_logging_level_debug_when_debug(bool enableDebug, params string[] excludeAppenderNames) + public static void EnableDebugLoggingIf(bool enableDebug, params string[] excludeAppenderNames) { if (excludeAppenderNames == null) excludeAppenderNames = new string[] { }; @@ -286,10 +286,10 @@ public static void set_logging_level_debug_when_debug(bool enableDebug, params s } } - foreach (var append in logRepository.GetAppenders().Where(a => excludeAppenderNames.All(name => !a.Name.is_equal_to(name))).or_empty_list_if_null()) + foreach (var append in logRepository.GetAppenders().Where(a => excludeAppenderNames.All(name => !a.Name.IsEqualTo(name))).OrEmpty()) { var appender = append as AppenderSkeleton; - if (appender != null && !appender.Name.is_equal_to(_summaryLogAppenderName)) + if (appender != null && !appender.Name.IsEqualTo(_summaryLogAppenderName)) { // slightly naive implementation appender.ClearFilters(); @@ -306,7 +306,7 @@ public static void set_logging_level_debug_when_debug(bool enableDebug, params s /// </param> /// <param name="enableDebug">If debug is also enabled</param> /// <param name="verboseLoggerName">Name of the verbose logger.</param> - public static void set_verbose_logger_when_verbose(bool enableVerbose, bool enableDebug, string verboseLoggerName) + public static void EnableVerboseLoggingIf(bool enableVerbose, bool enableDebug, string verboseLoggerName) { if (enableVerbose) { @@ -314,7 +314,7 @@ public static void set_verbose_logger_when_verbose(bool enableVerbose, bool enab foreach (var append in logRepository.GetAppenders()) { var appender = append as AppenderSkeleton; - if (appender != null && appender.Name.is_equal_to(verboseLoggerName)) + if (appender != null && appender.Name.IsEqualTo(verboseLoggerName)) { appender.ClearFilters(); var minLevel = enableDebug ? Level.Debug : Level.Info; @@ -329,7 +329,7 @@ public static void set_verbose_logger_when_verbose(bool enableVerbose, bool enab /// </summary> /// <param name="enableTrace">if set to <c>true</c> [enable trace].</param> /// <param name="traceLoggerName">Name of the trace logger.</param> - public static void set_trace_logger_when_trace(bool enableTrace, string traceLoggerName) + public static void EnableTraceLoggingIf(bool enableTrace, string traceLoggerName) { if (enableTrace) { @@ -343,7 +343,7 @@ public static void set_trace_logger_when_trace(bool enableTrace, string traceLog foreach (var append in logRepository.GetAppenders()) { var appender = append as AppenderSkeleton; - if (appender != null && appender.Name.is_equal_to(traceLoggerName)) + if (appender != null && appender.Name.IsEqualTo(traceLoggerName)) { appender.ClearFilters(); var minLevel = Level.Debug; @@ -353,12 +353,12 @@ public static void set_trace_logger_when_trace(bool enableTrace, string traceLog if (appender != null && appender.GetType() == typeof(RollingFileAppender)) fileAppenders.Add(appender); } - foreach (ILogger log in logRepository.GetCurrentLoggers().Where(l => l.Name.is_equal_to("Trace")).or_empty_list_if_null()) + foreach (ILogger log in logRepository.GetCurrentLoggers().Where(l => l.Name.IsEqualTo("Trace")).OrEmpty()) { var logger = log as Logger; if (logger != null) { - foreach (var appender in fileAppenders.or_empty_list_if_null()) + foreach (var appender in fileAppenders.OrEmpty()) { logger.AddAppender(appender); } @@ -368,7 +368,7 @@ public static void set_trace_logger_when_trace(bool enableTrace, string traceLog foreach (var append in logRepository.GetAppenders()) { var appender = append as AppenderSkeleton; - if (appender != null && appender.Name.is_equal_to("{0}.changes.log.appender".format_with(ApplicationParameters.Name))) + if (appender != null && appender.Name.IsEqualTo("{0}.changes.log.appender".FormatWith(ApplicationParameters.Name))) { var traceLayout = new PatternLayout { @@ -382,7 +382,7 @@ public static void set_trace_logger_when_trace(bool enableTrace, string traceLog } } - public static void configure_additional_log_file(string logFileLocation) + public static void SetupAdditionalLogFile(string logFileLocation) { if (string.IsNullOrWhiteSpace(logFileLocation)) return; @@ -397,7 +397,7 @@ public static void configure_additional_log_file(string logFileLocation) var app = new FileAppender() { - Name = "{0}.{1}.log.appender".format_with(ApplicationParameters.Name, logFileName), + Name = "{0}.{1}.log.appender".FormatWith(ApplicationParameters.Name, logFileName), File = logFileLocation, Layout = layout, AppendToFile = true, @@ -406,7 +406,7 @@ public static void configure_additional_log_file(string logFileLocation) app.ActivateOptions(); ILoggerRepository logRepository = LogManager.GetRepository(Assembly.GetCallingAssembly().UnderlyingType); - foreach (ILogger log in logRepository.GetCurrentLoggers().Where(l => !l.Name.is_equal_to("Trace")).or_empty_list_if_null()) + foreach (ILogger log in logRepository.GetCurrentLoggers().Where(l => !l.Name.IsEqualTo("Trace")).OrEmpty()) { var logger = log as Logger; if (logger != null) @@ -414,7 +414,32 @@ public static void configure_additional_log_file(string logFileLocation) logger.AddAppender(app); } } - } + +#pragma warning disable IDE1006 + [Obsolete("This overload is deprecated and will be removed in v3.")] + public static void initialize_with(Lazy<IConsole> console) + => InitializeWith(console); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public static void configure(string outputDirectory = null, params string[] excludeLoggerNames) + => Configure(outputDirectory, excludeLoggerNames); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public static void set_logging_level_debug_when_debug(bool enableDebug, params string[] excludeAppenderNames) + => EnableDebugLoggingIf(enableDebug, excludeAppenderNames); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public static void set_verbose_logger_when_verbose(bool enableVerbose, bool enableDebug, string verboseLoggerName) + => EnableVerboseLoggingIf(enableVerbose, enableDebug, verboseLoggerName); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public static void set_trace_logger_when_trace(bool enableTrace, string traceLoggerName) + => EnableTraceLoggingIf(enableTrace, traceLoggerName); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public static void configure_additional_log_file(string logFileLocation) + => SetupAdditionalLogFile(logFileLocation); +#pragma warning restore IDE1006 } } diff --git a/src/chocolatey/infrastructure/logging/Log4NetLog.cs b/src/chocolatey/infrastructure/logging/Log4NetLog.cs index 264c0a31e2..c1ad0153c2 100644 --- a/src/chocolatey/infrastructure/logging/Log4NetLog.cs +++ b/src/chocolatey/infrastructure/logging/Log4NetLog.cs @@ -25,8 +25,6 @@ namespace chocolatey.infrastructure.logging using log4net; using log4net.Core; - // ReSharper disable InconsistentNaming - /// <summary> /// Log4net logger implementing special ILog class /// </summary> @@ -45,68 +43,68 @@ public void InitializeFor(string loggerName) [TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")] public void Debug(string message, params object[] formatting) { - if (_logger.IsDebugEnabled) Log(Level.Debug, decorate_message_with_audit_information(message), formatting); + if (_logger.IsDebugEnabled) Log(Level.Debug, DecorateMessageWithAuditInformation(message), formatting); } [TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")] public void Debug(Func<string> message) { - if (_logger.IsDebugEnabled) Log(Level.Debug, decorate_message_with_audit_information(message.Invoke()).escape_curly_braces()); + if (_logger.IsDebugEnabled) Log(Level.Debug, DecorateMessageWithAuditInformation(message.Invoke()).EscapeCurlyBraces()); } [TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")] public void Info(string message, params object[] formatting) { - if (_logger.IsInfoEnabled) Log(Level.Info, decorate_message_with_audit_information(message), formatting); + if (_logger.IsInfoEnabled) Log(Level.Info, DecorateMessageWithAuditInformation(message), formatting); } [TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")] public void Info(Func<string> message) { - if (_logger.IsInfoEnabled) Log(Level.Info, decorate_message_with_audit_information(message.Invoke()).escape_curly_braces()); + if (_logger.IsInfoEnabled) Log(Level.Info, DecorateMessageWithAuditInformation(message.Invoke()).EscapeCurlyBraces()); } [TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")] public void Warn(string message, params object[] formatting) { - if (_logger.IsWarnEnabled) Log(Level.Warn, decorate_message_with_audit_information(message), formatting); + if (_logger.IsWarnEnabled) Log(Level.Warn, DecorateMessageWithAuditInformation(message), formatting); } [TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")] public void Warn(Func<string> message) { - if (_logger.IsWarnEnabled) Log(Level.Warn, decorate_message_with_audit_information(message.Invoke()).escape_curly_braces()); + if (_logger.IsWarnEnabled) Log(Level.Warn, DecorateMessageWithAuditInformation(message.Invoke()).EscapeCurlyBraces()); } [TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")] public void Error(string message, params object[] formatting) { // don't need to check for enabled at this level - Log(Level.Error, decorate_message_with_audit_information(message), formatting); + Log(Level.Error, DecorateMessageWithAuditInformation(message), formatting); } [TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")] public void Error(Func<string> message) { // don't need to check for enabled at this level - Log(Level.Error, decorate_message_with_audit_information(message.Invoke()).escape_curly_braces()); + Log(Level.Error, DecorateMessageWithAuditInformation(message.Invoke()).EscapeCurlyBraces()); } [TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")] public void Fatal(string message, params object[] formatting) { // don't need to check for enabled at this level - Log(Level.Fatal, decorate_message_with_audit_information(message), formatting); + Log(Level.Fatal, DecorateMessageWithAuditInformation(message), formatting); } [TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")] public void Fatal(Func<string> message) { // don't need to check for enabled at this level - Log(Level.Fatal, decorate_message_with_audit_information(message.Invoke()).escape_curly_braces()); + Log(Level.Fatal, DecorateMessageWithAuditInformation(message.Invoke()).EscapeCurlyBraces()); } - public string decorate_message_with_audit_information(string message) + public string DecorateMessageWithAuditInformation(string message) { return message; } @@ -115,10 +113,13 @@ public string decorate_message_with_audit_information(string message) private void Log(Level level, string message, params object[] formatting) { // SystemStringFormat is used to evaluate the message as late as possible. A filter may discard this message. - _logger.Logger.Log(_declaringType, level, message.format_with(formatting), null); + _logger.Logger.Log(_declaringType, level, message.FormatWith(formatting), null); } +#pragma warning disable IDE1006 + [Obsolete("This overload is deprecated and will be removed in v3.")] + public string decorate_message_with_audit_information(string message) + => DecorateMessageWithAuditInformation(message); +#pragma warning restore IDE1006 } - - // ReSharper restore InconsistentNaming } diff --git a/src/chocolatey/infrastructure/logging/LogSinkLog.cs b/src/chocolatey/infrastructure/logging/LogSinkLog.cs index d5701e7198..58093cc447 100644 --- a/src/chocolatey/infrastructure/logging/LogSinkLog.cs +++ b/src/chocolatey/infrastructure/logging/LogSinkLog.cs @@ -19,8 +19,6 @@ namespace chocolatey.infrastructure.logging using System; using System.Collections.Generic; - // ReSharper disable InconsistentNaming - public sealed class LogSinkLog : ILog, ILog<LogSinkLog> { private readonly IList<LogMessage> _messages = new List<LogMessage>(); @@ -34,7 +32,7 @@ public void InitializeFor(string loggerName) public void Debug(string message, params object[] formatting) { - _messages.Add(new LogMessage(LogLevelType.Debug, message.format_with(formatting))); + _messages.Add(new LogMessage(LogLevelType.Debug, message.FormatWith(formatting))); } public void Debug(Func<string> message) @@ -44,7 +42,7 @@ public void Debug(Func<string> message) public void Info(string message, params object[] formatting) { - _messages.Add(new LogMessage(LogLevelType.Information, message.format_with(formatting))); + _messages.Add(new LogMessage(LogLevelType.Information, message.FormatWith(formatting))); } public void Info(Func<string> message) @@ -54,7 +52,7 @@ public void Info(Func<string> message) public void Warn(string message, params object[] formatting) { - _messages.Add(new LogMessage(LogLevelType.Warning, message.format_with(formatting))); + _messages.Add(new LogMessage(LogLevelType.Warning, message.FormatWith(formatting))); } public void Warn(Func<string> message) @@ -64,7 +62,7 @@ public void Warn(Func<string> message) public void Error(string message, params object[] formatting) { - _messages.Add(new LogMessage(LogLevelType.Error, message.format_with(formatting))); + _messages.Add(new LogMessage(LogLevelType.Error, message.FormatWith(formatting))); } public void Error(Func<string> message) @@ -74,7 +72,7 @@ public void Error(Func<string> message) public void Fatal(string message, params object[] formatting) { - _messages.Add(new LogMessage(LogLevelType.Fatal, message.format_with(formatting))); + _messages.Add(new LogMessage(LogLevelType.Fatal, message.FormatWith(formatting))); } public void Fatal(Func<string> message) @@ -82,6 +80,4 @@ public void Fatal(Func<string> message) _messages.Add(new LogMessage(LogLevelType.Fatal, message())); } } - - // ReSharper restore InconsistentNaming } diff --git a/src/chocolatey/infrastructure/logging/NullLog.cs b/src/chocolatey/infrastructure/logging/NullLog.cs index 10eac489ea..c4ecc4b438 100644 --- a/src/chocolatey/infrastructure/logging/NullLog.cs +++ b/src/chocolatey/infrastructure/logging/NullLog.cs @@ -18,8 +18,6 @@ namespace chocolatey.infrastructure.logging { using System; - // ReSharper disable InconsistentNaming - /// <summary> /// The default logger until one is set. /// </summary> @@ -69,6 +67,4 @@ public void Fatal(Func<string> message) { } } - - // ReSharper restore InconsistentNaming } diff --git a/src/chocolatey/infrastructure/logging/TraceLog.cs b/src/chocolatey/infrastructure/logging/TraceLog.cs index a9d52b4496..4e988086f1 100644 --- a/src/chocolatey/infrastructure/logging/TraceLog.cs +++ b/src/chocolatey/infrastructure/logging/TraceLog.cs @@ -29,11 +29,11 @@ public TraceLog() { try { - enable_system_net_logging(); + EnableNetworkLogging(); } catch (Exception e) { - this.Log().Warn(ChocolateyLoggers.Verbose, "Unable to set trace logging:{0} {1}".format_with(Environment.NewLine, e.Message)); + this.Log().Warn(ChocolateyLoggers.Verbose, "Unable to set trace logging:{0} {1}".FormatWith(Environment.NewLine, e.Message)); } } @@ -42,11 +42,11 @@ public TraceLog(string name) { try { - enable_system_net_logging(); + EnableNetworkLogging(); } catch (Exception e) { - this.Log().Warn(ChocolateyLoggers.Verbose, "Unable to set trace logging:{0} {1}".format_with(Environment.NewLine, e.Message)); + this.Log().Warn(ChocolateyLoggers.Verbose, "Unable to set trace logging:{0} {1}".FormatWith(Environment.NewLine, e.Message)); } } @@ -54,7 +54,7 @@ public TraceLog(string name) /// Enable logging for network requests and responses /// </summary> /// <remarks>Based on http://stackoverflow.com/a/27467753/18475 </remarks> - private void enable_system_net_logging() + private void EnableNetworkLogging() { var logging = typeof(WebRequest).Assembly.GetType("System.Net.Logging"); var isInitialized = logging.GetField("s_LoggingInitialized", BindingFlags.NonPublic | BindingFlags.Static); @@ -77,16 +77,16 @@ private void enable_system_net_logging() } } - enable_trace_source("s_WebTraceSource", logging, this); //System.Net - enable_trace_source("s_HttpListenerTraceSource", logging, this); //System.Net.HttpListener - enable_trace_source("s_SocketsTraceSource", logging, this); //System.Net.Sockets - enable_trace_source("s_CacheTraceSource", logging, this); //System.Net.Cache + EnableTraceSource("s_WebTraceSource", logging, this); //System.Net + EnableTraceSource("s_HttpListenerTraceSource", logging, this); //System.Net.HttpListener + EnableTraceSource("s_SocketsTraceSource", logging, this); //System.Net.Sockets + EnableTraceSource("s_CacheTraceSource", logging, this); //System.Net.Cache var isEnabled = logging.GetField("s_LoggingEnabled", BindingFlags.NonPublic | BindingFlags.Static); if (isEnabled !=null) isEnabled.SetValue(null, true); } - private static void enable_trace_source(string fieldName, Type logging, TraceListener listener) + private static void EnableTraceSource(string fieldName, Type logging, TraceListener listener) { var traceSource = (TraceSource)logging.GetField(fieldName, BindingFlags.NonPublic | BindingFlags.Static).GetValue(null); if (traceSource != null) diff --git a/src/chocolatey/infrastructure/platforms/Platform.cs b/src/chocolatey/infrastructure/platforms/Platform.cs index 5c9d003160..af181cce66 100644 --- a/src/chocolatey/infrastructure/platforms/Platform.cs +++ b/src/chocolatey/infrastructure/platforms/Platform.cs @@ -31,27 +31,27 @@ namespace chocolatey.infrastructure.platforms /// </remarks> public static class Platform { - private static Lazy<IEnvironment> environment_initializer = new Lazy<IEnvironment>(() => new Environment()); - private static Lazy<IFileSystem> file_system_initializer = new Lazy<IFileSystem>(() => new DotNetFileSystem()); + private static Lazy<IEnvironment> _environmentInitializer = new Lazy<IEnvironment>(() => new Environment()); + private static Lazy<IFileSystem> _fileSystemInitializer = new Lazy<IFileSystem>(() => new DotNetFileSystem()); [EditorBrowsable(EditorBrowsableState.Never)] - public static void initialize_with(Lazy<IEnvironment> environment, Lazy<IFileSystem> file_system) + public static void InitializeWith(Lazy<IEnvironment> environment, Lazy<IFileSystem> file_system) { - environment_initializer = environment; - file_system_initializer = file_system; + _environmentInitializer = environment; + _fileSystemInitializer = file_system; } - private static IFileSystem file_system + private static IFileSystem FileSystem { - get { return file_system_initializer.Value; } + get { return _fileSystemInitializer.Value; } } private static IEnvironment Environment { - get { return environment_initializer.Value; } + get { return _environmentInitializer.Value; } } - public static PlatformType get_platform() + public static PlatformType GetPlatform() { switch (Environment.OSVersion.Platform) { @@ -61,10 +61,10 @@ public static PlatformType get_platform() case PlatformID.Unix: // Well, there are chances macOS is reported as Unix instead of macOS (MacOSX). // Instead of platform check, we'll do a feature checks (Mac specific root folders) - if (file_system.directory_exists("/Applications") - & file_system.directory_exists("/System") - & file_system.directory_exists("/Users") - & file_system.directory_exists("/Volumes")) + if (FileSystem.DirectoryExists("/Applications") + & FileSystem.DirectoryExists("/System") + & FileSystem.DirectoryExists("/Users") + & FileSystem.DirectoryExists("/Volumes")) return PlatformType.Mac; else return PlatformType.Linux; @@ -73,21 +73,21 @@ public static PlatformType get_platform() } } - public static Version get_version() + public static Version GetVersion() { return Environment.OSVersion.Version; } - public static string get_name() + public static string GetName() { - switch (get_platform()) + switch (GetPlatform()) { case PlatformType.Linux: return "Linux"; case PlatformType.Mac: return "macOS"; case PlatformType.Windows: - return get_windows_name(get_version()); + return GetWindowsVersionName(GetVersion()); default: return ""; } @@ -99,7 +99,7 @@ public static string get_name() /// </summary> /// <param name="version">The version.</param> /// <remarks>Looked at http://www.csharp411.com/determine-windows-version-and-edition-with-c/</remarks> - private static string get_windows_name(Version version) + private static string GetWindowsVersionName(Version version) { var name = "Windows"; var isServer = false; @@ -134,18 +134,6 @@ private static string get_windows_name(Version version) case "6.1": name = isServer ? "Windows Server 2008 R2" : "Windows 7"; break; - case "6.0": - name = isServer ? "Windows Server 2008" : "Windows Vista"; - break; - case "5.2": - name = isServer ? "Windows Server 2003" : "Windows XP"; - break; - case "5.1": - name = "Windows XP"; - break; - case "5.0": - name = "Windows 2000"; - break; } return name; @@ -206,5 +194,24 @@ _Inout_ LPOSVERSIONINFO lpVersionInfo private static extern bool GetVersionEx(ref OSVERSIONINFOEX osVersionInfo); // ReSharper restore InconsistentNaming + +#pragma warning disable IDE1006 + [Obsolete("This overload is deprecated and will be removed in v3.")] + [EditorBrowsable(EditorBrowsableState.Never)] + public static void initialize_with(Lazy<IEnvironment> environment, Lazy<IFileSystem> file_system) + => InitializeWith(environment, file_system); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public static PlatformType get_platform() + => GetPlatform(); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public static Version get_version() + => GetVersion(); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public static string get_name() + => GetName(); +#pragma warning restore IDE1006 } } diff --git a/src/chocolatey/infrastructure/powershell/PoshHost.cs b/src/chocolatey/infrastructure/powershell/PoshHost.cs index 40dda2c793..5294b81a3a 100644 --- a/src/chocolatey/infrastructure/powershell/PoshHost.cs +++ b/src/chocolatey/infrastructure/powershell/PoshHost.cs @@ -52,7 +52,7 @@ public PoshHost(ChocolateyConfiguration configuration) ExitCode = -1; _configuration = configuration; _psUI = new PoshHostUserInterface(configuration); - _version = get_current_version(); + _version = GetCurrentVersion(); } /// <summary> @@ -60,12 +60,12 @@ public PoshHost(ChocolateyConfiguration configuration) /// </summary> /// <returns></returns> /// <remarks>We can cheat because we require at least v2, which takes us down to just the check for v3</remarks> - private Version get_current_version() + private Version GetCurrentVersion() { // users need at least v2 to even use Chocolatey // this allows us to shortcut the check for the v1/2 key var version = new Version(2, 0); - var majorMinor = RegistryService.get_value(RegistryHiveType.LocalMachine, "SOFTWARE\\Microsoft\\PowerShell\\3\\PowerShellEngine", "PowerShellVersion"); + var majorMinor = RegistryService.GetRegistryValue(RegistryHiveType.LocalMachine, "SOFTWARE\\Microsoft\\PowerShell\\3\\PowerShellEngine", "PowerShellVersion"); if (majorMinor != null) { version = new Version(majorMinor.Value); diff --git a/src/chocolatey/infrastructure/powershell/PoshHostUserInterface.cs b/src/chocolatey/infrastructure/powershell/PoshHostUserInterface.cs index 0b80d3f472..a2628c3d6b 100644 --- a/src/chocolatey/infrastructure/powershell/PoshHostUserInterface.cs +++ b/src/chocolatey/infrastructure/powershell/PoshHostUserInterface.cs @@ -34,7 +34,7 @@ public class PoshHostUserInterface : PSHostUserInterface private readonly ChocolateyConfiguration _configuration; protected readonly Console Console = new Console(); private readonly PoshHostRawUserInterface _rawUi = new PoshHostRawUserInterface(); - private const int TIMEOUT_IN_SECONDS = 30; + private const int TimeoutInSeconds = 30; public bool StandardErrorWritten { get; set; } @@ -55,9 +55,9 @@ public override string ReadLine() if (!_configuration.PromptForConfirmation) { this.Log().Warn(ChocolateyLoggers.Important, @" Confirmation (`-y`) is set. - Respond within {0} seconds or the default selection will be chosen.".format_with(TIMEOUT_IN_SECONDS)); + Respond within {0} seconds or the default selection will be chosen.".FormatWith(TimeoutInSeconds)); - return Console.ReadLine(TIMEOUT_IN_SECONDS * 1000); + return Console.ReadLine(TimeoutInSeconds * 1000); } return Console.ReadLine(); @@ -68,17 +68,17 @@ public override SecureString ReadLineAsSecureString() if (!_configuration.PromptForConfirmation) { this.Log().Warn(ChocolateyLoggers.Important, @" Confirmation (`-y`) is set. - Respond within {0} seconds or the default selection will be chosen.".format_with(TIMEOUT_IN_SECONDS)); + Respond within {0} seconds or the default selection will be chosen.".FormatWith(TimeoutInSeconds)); } - var secureStringPlainText = InteractivePrompt.get_password(_configuration.PromptForConfirmation); + var secureStringPlainText = InteractivePrompt.GetPassword(_configuration.PromptForConfirmation); - return secureStringPlainText.to_secure_string(); + return secureStringPlainText.ToSecureStringSafe(); } public override void Write(string value) { - this.Log().Info(value.escape_curly_braces()); + this.Log().Info(value.EscapeCurlyBraces()); //Console.Write(value); } @@ -90,7 +90,7 @@ public override void Write(ConsoleColor foregroundColor, ConsoleColor background System.Console.BackgroundColor = backgroundColor; Console.Write(value); - this.Log().Info(ChocolateyLoggers.LogFileOnly, value.escape_curly_braces()); + this.Log().Info(ChocolateyLoggers.LogFileOnly, value.EscapeCurlyBraces()); System.Console.ForegroundColor = originalForegroundColor; System.Console.BackgroundColor = originalBackgroundColor; @@ -109,7 +109,7 @@ public override void WriteLine(ConsoleColor foregroundColor, ConsoleColor backgr System.Console.BackgroundColor = backgroundColor; Console.WriteLine(value); - this.Log().Info(ChocolateyLoggers.LogFileOnly, value.escape_curly_braces()); + this.Log().Info(ChocolateyLoggers.LogFileOnly, value.EscapeCurlyBraces()); System.Console.ForegroundColor = originalForegroundColor; System.Console.BackgroundColor = originalBackgroundColor; @@ -117,18 +117,18 @@ public override void WriteLine(ConsoleColor foregroundColor, ConsoleColor backgr public override void WriteLine(string value) { - this.Log().Info(value.escape_curly_braces()); + this.Log().Info(value.EscapeCurlyBraces()); } public override void WriteErrorLine(string value) { StandardErrorWritten = true; - this.Log().Error(value.escape_curly_braces()); + this.Log().Error(value.EscapeCurlyBraces()); } public override void WriteDebugLine(string message) { - this.Log().Debug(message.escape_curly_braces()); + this.Log().Debug(message.EscapeCurlyBraces()); } private bool hasLoggedStartProgress = false; @@ -139,42 +139,42 @@ public override void WriteProgress(long sourceId, ProgressRecord record) if (!hasLoggedStartProgress) { hasLoggedStartProgress = true; - this.Log().Debug(record.Activity.escape_curly_braces()); + this.Log().Debug(record.Activity.EscapeCurlyBraces()); } if (_configuration.Features.ShowDownloadProgress) { // http://stackoverflow.com/a/888569/18475 - Console.Write("\rProgress: {0}% - {1}".format_with(record.PercentComplete.to_string(), record.StatusDescription).PadRight(Console.WindowWidth)); + Console.Write("\rProgress: {0}% - {1}".FormatWith(record.PercentComplete.ToStringSafe(), record.StatusDescription).PadRight(Console.WindowWidth)); } } public override void WriteVerboseLine(string message) { - this.Log().Info(ChocolateyLoggers.Verbose, "VERBOSE: " + message.escape_curly_braces()); + this.Log().Info(ChocolateyLoggers.Verbose, "VERBOSE: " + message.EscapeCurlyBraces()); } public override void WriteWarningLine(string message) { - this.Log().Warn("WARNING: " + message.escape_curly_braces()); + this.Log().Warn("WARNING: " + message.EscapeCurlyBraces()); } public override Dictionary<string, PSObject> Prompt(string caption, string message, Collection<FieldDescription> descriptions) { - this.Log().Info(ChocolateyLoggers.Important, caption.escape_curly_braces()); + this.Log().Info(ChocolateyLoggers.Important, caption.EscapeCurlyBraces()); var results = new Dictionary<string, PSObject>(); foreach (FieldDescription field in descriptions) { - if (string.IsNullOrWhiteSpace(field.Label)) this.Log().Warn(field.Name.escape_curly_braces()); + if (string.IsNullOrWhiteSpace(field.Label)) this.Log().Warn(field.Name.EscapeCurlyBraces()); else { - string[] label = get_hotkey_and_label(field.Label); - this.Log().Warn(label[1].escape_curly_braces()); + string[] label = GetHotkeyAndLabel(field.Label); + this.Log().Warn(label[1].EscapeCurlyBraces()); } dynamic selection = string.Empty; - if (field.ParameterTypeFullName.is_equal_to(typeof(SecureString).FullName)) + if (field.ParameterTypeFullName.IsEqualTo(typeof(SecureString).FullName)) { selection = ReadLineAsSecureString(); } @@ -202,14 +202,14 @@ public override Dictionary<string, PSObject> Prompt(string caption, string messa /// <returns> /// A two dimensional array containing the parsed components. /// </returns> - private static string[] get_hotkey_and_label(string input) + private static string[] GetHotkeyAndLabel(string input) { var result = new[] { String.Empty, String.Empty }; //Do not use StringSplitOptions.RemoveEmptyEntries, it causes issues here string[] fragments = input.Split('&'); if (fragments.Length == 2) { - if (fragments[1].Length > 0) result[0] = fragments[1][0].to_string().ToUpper(CultureInfo.CurrentCulture); + if (fragments[1].Length > 0) result[0] = fragments[1][0].ToStringSafe().ToUpper(CultureInfo.CurrentCulture); result[1] = (fragments[0] + fragments[1]).Trim(); } @@ -220,10 +220,10 @@ private static string[] get_hotkey_and_label(string input) public override int PromptForChoice(string caption, string message, Collection<ChoiceDescription> choices, int defaultChoice) { - if (!string.IsNullOrWhiteSpace(caption)) this.Log().Warn(caption.escape_curly_braces()); - if (!string.IsNullOrWhiteSpace(message)) this.Log().Warn(ChocolateyLoggers.Important, message.escape_curly_braces()); + if (!string.IsNullOrWhiteSpace(caption)) this.Log().Warn(caption.EscapeCurlyBraces()); + if (!string.IsNullOrWhiteSpace(message)) this.Log().Warn(ChocolateyLoggers.Important, message.EscapeCurlyBraces()); - string[,] promptData = build_hotkeys_and_plain_labels(choices); + string[,] promptData = BuildHotkeysAndLabels(choices); // Format the overall choice prompt string to display. var choicePrompt = new StringBuilder(); @@ -243,8 +243,8 @@ public override int PromptForChoice(string caption, string message, Collection<C while (true) { - this.Log().Warn(choicePrompt.ToString().escape_curly_braces()); - string selection = ReadLine().trim_safe().ToUpper(CultureInfo.CurrentCulture); + this.Log().Warn(choicePrompt.ToString().EscapeCurlyBraces()); + string selection = ReadLine().TrimSafe().ToUpper(CultureInfo.CurrentCulture); if (selection.Length == 0) return defaultChoice; @@ -253,17 +253,17 @@ public override int PromptForChoice(string caption, string message, Collection<C if (promptData[0, i] == selection) return i; } - this.Log().Warn(ChocolateyLoggers.Important, "Invalid choice: " + selection.escape_curly_braces()); + this.Log().Warn(ChocolateyLoggers.Important, "Invalid choice: " + selection.EscapeCurlyBraces()); } } - private static string[,] build_hotkeys_and_plain_labels(Collection<ChoiceDescription> choices) + private static string[,] BuildHotkeysAndLabels(Collection<ChoiceDescription> choices) { var choiceSelections = new string[2, choices.Count]; for (int i = 0; i < choices.Count; ++i) { - string[] hotkeyAndLabel = get_hotkey_and_label(choices[i].Label); + string[] hotkeyAndLabel = GetHotkeyAndLabel(choices[i].Label); choiceSelections[0, i] = hotkeyAndLabel[0]; choiceSelections[1, i] = hotkeyAndLabel[1]; } @@ -278,13 +278,13 @@ public override PSCredential PromptForCredential(string caption, string message, public override PSCredential PromptForCredential(string caption, string message, string userName, string targetName, PSCredentialTypes allowedCredentialTypes, PSCredentialUIOptions options) { - if (!string.IsNullOrWhiteSpace(caption)) this.Log().Warn(caption.escape_curly_braces()); - if (!string.IsNullOrWhiteSpace(message)) this.Log().Warn(ChocolateyLoggers.Important, message.escape_curly_braces()); + if (!string.IsNullOrWhiteSpace(caption)) this.Log().Warn(caption.EscapeCurlyBraces()); + if (!string.IsNullOrWhiteSpace(message)) this.Log().Warn(ChocolateyLoggers.Important, message.EscapeCurlyBraces()); if (string.IsNullOrWhiteSpace(userName)) { this.Log().Warn("Please provide username:"); - string selection = ReadLine().trim_safe().ToUpper(CultureInfo.CurrentCulture); + string selection = ReadLine().TrimSafe().ToUpper(CultureInfo.CurrentCulture); if (selection.Length == 0) selection = targetName; @@ -293,14 +293,14 @@ public override PSCredential PromptForCredential(string caption, string message, var password = string.Empty; this.Log().Warn("Please provide password:"); - password = InteractivePrompt.get_password(_configuration.PromptForConfirmation); + password = InteractivePrompt.GetPassword(_configuration.PromptForConfirmation); if (string.IsNullOrWhiteSpace(userName) || string.IsNullOrWhiteSpace(password)) { this.Log().Warn(ChocolateyLoggers.Important, "A userName or password was not entered. This may result in future failures."); } - return new PSCredential(userName, password.to_secure_string()); + return new PSCredential(userName, password.ToSecureStringSafe()); } public override PSHostRawUserInterface RawUI { get { return _rawUi; } } diff --git a/src/chocolatey/infrastructure/registration/AssemblyResolution.cs b/src/chocolatey/infrastructure/registration/AssemblyResolution.cs index 04934f689c..3845358672 100644 --- a/src/chocolatey/infrastructure/registration/AssemblyResolution.cs +++ b/src/chocolatey/infrastructure/registration/AssemblyResolution.cs @@ -30,7 +30,7 @@ namespace chocolatey.infrastructure.registration public class AssemblyResolution { - private const int LOCK_RESOLUTION_TIMEOUT_SECONDS = 5; + private const int LockResolutionTimeoutSeconds = 5; private static readonly object _lockObject = new object(); private static readonly ConcurrentDictionary<string, IAssembly> _loadedAssemblies = new ConcurrentDictionary<string, IAssembly>(); @@ -43,8 +43,8 @@ public class AssemblyResolution /// <param name="assemblyFileLocation">The assembly file location. Typically the path to the DLL on disk.</param> /// <returns>An assembly</returns> /// <exception cref="Exception">Unable to enter synchronized code to determine assembly loading</exception> - public static IAssembly resolve_or_load_assembly(string assemblySimpleName, string publicKeyToken, string assemblyFileLocation) { - return resolve_or_load_assembly(assemblySimpleName, publicKeyToken, assemblyFileLocation, false); + public static IAssembly ResolveOrLoadAssembly(string assemblySimpleName, string publicKeyToken, string assemblyFileLocation) { + return ResolveOrLoadAssembly(assemblySimpleName, publicKeyToken, assemblyFileLocation, false); } /// <summary> @@ -56,12 +56,12 @@ public static IAssembly resolve_or_load_assembly(string assemblySimpleName, stri /// <param name="ignoreExisting">Whether any existing library that has previously been loaded should be ignored or not.</param> /// <returns>An assembly</returns> /// <exception cref="Exception">Unable to enter synchronized code to determine assembly loading</exception> - public static IAssembly resolve_or_load_assembly(string assemblySimpleName, string publicKeyToken, string assemblyFileLocation, bool ignoreExisting = false) + public static IAssembly ResolveOrLoadAssembly(string assemblySimpleName, string publicKeyToken, string assemblyFileLocation, bool ignoreExisting = false) { var lockTaken = false; try { - Monitor.TryEnter(_lockObject, TimeSpan.FromSeconds(LOCK_RESOLUTION_TIMEOUT_SECONDS), ref lockTaken); + Monitor.TryEnter(_lockObject, TimeSpan.FromSeconds(LockResolutionTimeoutSeconds), ref lockTaken); } catch (Exception) { @@ -76,29 +76,29 @@ public static IAssembly resolve_or_load_assembly(string assemblySimpleName, stri { if (!ignoreExisting) { - resolvedAssembly = resolve_assembly(assemblySimpleName, publicKeyToken); + resolvedAssembly = ResolveAssembly(assemblySimpleName, publicKeyToken); } if (resolvedAssembly == null) { - var tempAssembly = Assembly.Load(FileSystem.read_binary_file_into_byte_array(assemblyFileLocation)); + var tempAssembly = Assembly.Load(FileSystem.ReadFileBytes(assemblyFileLocation)); if (tempAssembly == null) { return null; } - if (string.IsNullOrWhiteSpace(publicKeyToken) || tempAssembly.GetName().get_public_key_token().is_equal_to(publicKeyToken)) + if (string.IsNullOrWhiteSpace(publicKeyToken) || AssemblyExtensions.GetPublicKeyTokenString(tempAssembly.GetName()).IsEqualTo(publicKeyToken)) { - "chocolatey".Log().Debug("Loading up '{0}' assembly type from '{1}'".format_with(assemblySimpleName, assemblyFileLocation)); + "chocolatey".Log().Debug("Loading up '{0}' assembly type from '{1}'".FormatWith(assemblySimpleName, assemblyFileLocation)); resolvedAssembly = tempAssembly; - _loadedAssemblies.TryAdd(assemblySimpleName.to_lower(), resolvedAssembly); + _loadedAssemblies.TryAdd(assemblySimpleName.ToLowerSafe(), resolvedAssembly); - if (assemblySimpleName.is_equal_to("choco")) + if (assemblySimpleName.IsEqualTo("choco")) { _loadedAssemblies.TryAdd("chocolatey", resolvedAssembly); } - else if (assemblySimpleName.is_equal_to("chocolatey")) + else if (assemblySimpleName.IsEqualTo("chocolatey")) { _loadedAssemblies.TryAdd("choco", resolvedAssembly); } @@ -115,7 +115,7 @@ public static IAssembly resolve_or_load_assembly(string assemblySimpleName, stri return resolvedAssembly; } - public static IAssembly load_assembly(string assemblySimpleName, string assemblyFileLocation, params string[] publicKeyTokens) + public static IAssembly LoadAssembly(string assemblySimpleName, string assemblyFileLocation, params string[] publicKeyTokens) { if (publicKeyTokens == null || publicKeyTokens.Length == 0) { @@ -125,7 +125,7 @@ public static IAssembly load_assembly(string assemblySimpleName, string assembly var lockTaken = false; try { - Monitor.TryEnter(_lockObject, TimeSpan.FromSeconds(LOCK_RESOLUTION_TIMEOUT_SECONDS), ref lockTaken); + Monitor.TryEnter(_lockObject, TimeSpan.FromSeconds(LockResolutionTimeoutSeconds), ref lockTaken); } catch (Exception) { @@ -140,19 +140,19 @@ public static IAssembly load_assembly(string assemblySimpleName, string assembly { IAssembly tempAssembly; #if FORCE_CHOCOLATEY_OFFICIAL_KEY - tempAssembly = Assembly.Load(FileSystem.read_binary_file_into_byte_array(assemblyFileLocation)); + tempAssembly = Assembly.Load(FileSystem.ReadFileBytes(assemblyFileLocation)); #else var symbolFile = System.IO.Path.ChangeExtension(assemblyFileLocation, ".pdb"); if (System.IO.File.Exists(symbolFile)) { tempAssembly = Assembly.Load( - FileSystem.read_binary_file_into_byte_array(assemblyFileLocation), - FileSystem.read_binary_file_into_byte_array(symbolFile)); + FileSystem.ReadFileBytes(assemblyFileLocation), + FileSystem.ReadFileBytes(symbolFile)); } else { - tempAssembly = Assembly.Load(FileSystem.read_binary_file_into_byte_array(assemblyFileLocation)); + tempAssembly = Assembly.Load(FileSystem.ReadFileBytes(assemblyFileLocation)); } #endif @@ -163,18 +163,18 @@ public static IAssembly load_assembly(string assemblySimpleName, string assembly foreach (var publicKeyToken in publicKeyTokens) { - if (string.IsNullOrWhiteSpace(publicKeyToken) || tempAssembly.GetName().get_public_key_token().is_equal_to(publicKeyToken)) + if (string.IsNullOrWhiteSpace(publicKeyToken) || AssemblyExtensions.GetPublicKeyTokenString(tempAssembly.GetName()).IsEqualTo(publicKeyToken)) { - "chocolatey".Log().Debug("Loading up '{0}' assembly type from '{1}'".format_with(assemblySimpleName, assemblyFileLocation)); + "chocolatey".Log().Debug("Loading up '{0}' assembly type from '{1}'".FormatWith(assemblySimpleName, assemblyFileLocation)); resolvedAssembly = tempAssembly; - _loadedAssemblies.TryAdd(assemblySimpleName.to_lower(), resolvedAssembly); + _loadedAssemblies.TryAdd(assemblySimpleName.ToLowerSafe(), resolvedAssembly); - if (assemblySimpleName.is_equal_to("choco")) + if (assemblySimpleName.IsEqualTo("choco")) { _loadedAssemblies.TryAdd("chocolatey", resolvedAssembly); } - else if (assemblySimpleName.is_equal_to("chocolatey")) + else if (assemblySimpleName.IsEqualTo("chocolatey")) { _loadedAssemblies.TryAdd("choco", resolvedAssembly); } @@ -201,7 +201,7 @@ public static IAssembly load_assembly(string assemblySimpleName, string assembly /// /// <returns>An assembly</returns> /// <exception cref="Exception">Unable to enter synchronized code to determine assembly loading</exception> - public static IAssembly resolve_existing_assembly(string assemblySimpleName, params string[] publicKeyTokens) + public static IAssembly ResolveExistingAssembly(string assemblySimpleName, params string[] publicKeyTokens) { if (publicKeyTokens == null || publicKeyTokens.Length == 0) { @@ -211,7 +211,7 @@ public static IAssembly resolve_existing_assembly(string assemblySimpleName, par var lockTaken = false; try { - Monitor.TryEnter(_lockObject, TimeSpan.FromSeconds(LOCK_RESOLUTION_TIMEOUT_SECONDS), ref lockTaken); + Monitor.TryEnter(_lockObject, TimeSpan.FromSeconds(LockResolutionTimeoutSeconds), ref lockTaken); } catch (Exception) { @@ -226,7 +226,7 @@ public static IAssembly resolve_existing_assembly(string assemblySimpleName, par { foreach (var publicKeyToken in publicKeyTokens) { - resolvedAssembly = resolve_assembly(assemblySimpleName, publicKeyToken); + resolvedAssembly = ResolveAssembly(assemblySimpleName, publicKeyToken); if (resolvedAssembly != null) { @@ -244,27 +244,27 @@ public static IAssembly resolve_existing_assembly(string assemblySimpleName, par return resolvedAssembly; } - private static IAssembly resolve_assembly(string assemblySimpleName, string publicKeyToken) + private static IAssembly ResolveAssembly(string assemblySimpleName, string publicKeyToken) { IAssembly resolvedAssembly = null; - foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies().Where(a => a.GetName().Name.is_equal_to(assemblySimpleName)).or_empty_list_if_null()) + foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies().Where(a => a.GetName().Name.IsEqualTo(assemblySimpleName)).OrEmpty()) { - if (string.IsNullOrWhiteSpace(publicKeyToken) || assembly.GetName().get_public_key_token().is_equal_to(publicKeyToken)) + if (string.IsNullOrWhiteSpace(publicKeyToken) || AssemblyExtensions.GetPublicKeyTokenString(assembly.GetName()).IsEqualTo(publicKeyToken)) { - "chocolatey".Log().Debug("Returning loaded assembly type for '{0}'".format_with(assemblySimpleName)); - resolvedAssembly = Assembly.set_assembly(assembly); + "chocolatey".Log().Debug("Returning loaded assembly type for '{0}'".FormatWith(assemblySimpleName)); + resolvedAssembly = Assembly.SetAssembly(assembly); break; } } IAssembly tempAssembly; - if (_loadedAssemblies.TryGetValue(assemblySimpleName.to_lower(), out tempAssembly)) + if (_loadedAssemblies.TryGetValue(assemblySimpleName.ToLowerSafe(), out tempAssembly)) { - if (string.IsNullOrWhiteSpace(publicKeyToken) || tempAssembly.GetName().get_public_key_token().is_equal_to(publicKeyToken)) + if (string.IsNullOrWhiteSpace(publicKeyToken) || AssemblyExtensions.GetPublicKeyTokenString(tempAssembly.GetName()).IsEqualTo(publicKeyToken)) { - "chocolatey".Log().Debug("Returning loaded assembly type for '{0}'".format_with(assemblySimpleName)); + "chocolatey".Log().Debug("Returning loaded assembly type for '{0}'".FormatWith(assemblySimpleName)); resolvedAssembly = tempAssembly; } } @@ -272,7 +272,7 @@ private static IAssembly resolve_assembly(string assemblySimpleName, string publ return resolvedAssembly; } - public static IAssembly load_extension(string assemblySimpleName) + public static IAssembly LoadExtension(string assemblySimpleName) { #if FORCE_CHOCOLATEY_OFFICIAL_KEY var chocolateyPublicKey = ApplicationParameters.OfficialChocolateyPublicKey; @@ -280,7 +280,7 @@ public static IAssembly load_extension(string assemblySimpleName) var chocolateyPublicKey = ApplicationParameters.UnofficialChocolateyPublicKey; #endif - var fullName = "{0}, Version=0.0.0.0, Culture=neutral, PublicKeyToken={1}".format_with( + var fullName = "{0}, Version=0.0.0.0, Culture=neutral, PublicKeyToken={1}".FormatWith( assemblySimpleName, chocolateyPublicKey); @@ -292,7 +292,7 @@ public static IAssembly load_extension(string assemblySimpleName) if (assembly != null) { - return Assembly.set_assembly(assembly); + return Assembly.SetAssembly(assembly); } } // Ignore load failures, so we return null and let the caller handle the failure to load the extension. @@ -311,7 +311,7 @@ public static IAssembly load_extension(string assemblySimpleName) return null; } - public static System.Reflection.Assembly resolve_extension_or_merged_assembly(object sender, ResolveEventArgs args) + public static System.Reflection.Assembly ResolveExtensionOrMergedAssembly(object sender, ResolveEventArgs args) { var requestedAssembly = new AssemblyName(args.Name); @@ -321,7 +321,7 @@ public static System.Reflection.Assembly resolve_extension_or_merged_assembly(ob var chocolateyPublicKey = ApplicationParameters.UnofficialChocolateyPublicKey; #endif - if (!requestedAssembly.get_public_key_token().is_equal_to(chocolateyPublicKey)) + if (!AssemblyExtensions.GetPublicKeyTokenString(requestedAssembly).IsEqualTo(chocolateyPublicKey)) { // This resolver is only loading official extensions for Chocolatey and ILMerged assemblies. // Everything else is not handled by this resolver. @@ -329,7 +329,7 @@ public static System.Reflection.Assembly resolve_extension_or_merged_assembly(ob } // Check if the requested assembly is already loaded - var resolvedAssembly = resolve_existing_assembly(requestedAssembly.Name, chocolateyPublicKey); + var resolvedAssembly = ResolveExistingAssembly(requestedAssembly.Name, chocolateyPublicKey); if (resolvedAssembly != null) { @@ -344,7 +344,7 @@ public static System.Reflection.Assembly resolve_extension_or_merged_assembly(ob extensionsFound = true; try { - resolvedAssembly = load_assembly(requestedAssembly.Name, extensionDll, chocolateyPublicKey); + resolvedAssembly = LoadAssembly(requestedAssembly.Name, extensionDll, chocolateyPublicKey); if (resolvedAssembly != null) { @@ -370,12 +370,38 @@ public static System.Reflection.Assembly resolve_extension_or_merged_assembly(ob // There are things that are ILMerged into Chocolatey. Anything with // the right public key except extensions should use the choco/chocolatey assembly if (!requestedAssembly.Name.EndsWith(".resources", StringComparison.OrdinalIgnoreCase) - && !requestedAssembly.Name.is_equal_to(ApplicationParameters.LicensedChocolateyAssemblySimpleName)) + && !requestedAssembly.Name.IsEqualTo(ApplicationParameters.LicensedChocolateyAssemblySimpleName)) { return typeof(ConsoleApplication).Assembly; } return null; } + +#pragma warning disable IDE1006 + [Obsolete("This overload is deprecated and will be removed in v3.")] + public static IAssembly resolve_or_load_assembly(string assemblySimpleName, string publicKeyToken, string assemblyFileLocation) + => ResolveOrLoadAssembly(assemblySimpleName, publicKeyToken, assemblyFileLocation); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public static IAssembly resolve_or_load_assembly(string assemblySimpleName, string publicKeyToken, string assemblyFileLocation, bool ignoreExisting = false) + => ResolveOrLoadAssembly(assemblySimpleName, publicKeyToken, assemblyFileLocation, ignoreExisting); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public static IAssembly load_assembly(string assemblySimpleName, string assemblyFileLocation, params string[] publicKeyTokens) + => LoadAssembly(assemblySimpleName, assemblyFileLocation, publicKeyTokens); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public static IAssembly resolve_existing_assembly(string assemblySimpleName, params string[] publicKeyTokens) + => ResolveExistingAssembly(assemblySimpleName, publicKeyTokens); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public static IAssembly load_extension(string assemblySimpleName) + => LoadExtension(assemblySimpleName); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public static System.Reflection.Assembly resolve_extension_or_merged_assembly(object sender, ResolveEventArgs args) + => ResolveExtensionOrMergedAssembly(sender, args); +#pragma warning restore IDE1006 } } diff --git a/src/chocolatey/infrastructure/registration/Bootstrap.cs b/src/chocolatey/infrastructure/registration/Bootstrap.cs index 899af62b65..65ce247688 100644 --- a/src/chocolatey/infrastructure/registration/Bootstrap.cs +++ b/src/chocolatey/infrastructure/registration/Bootstrap.cs @@ -32,7 +32,7 @@ public sealed class Bootstrap /// <summary> /// Initializes this instance. /// </summary> - public static void initialize() + public static void Initialize() { Log.InitializeWith<Log4NetLog>(); _logger.Debug("XmlConfiguration is now operational"); @@ -41,7 +41,7 @@ public static void initialize() /// <summary> /// Startups this instance. /// </summary> - public static void startup() + public static void Startup() { AppDomain.CurrentDomain.UnhandledException += DomainUnhandledException; } @@ -75,8 +75,22 @@ private static void DomainUnhandledException(object sender, UnhandledExceptionEv /// <summary> /// Shutdowns this instance. /// </summary> - public static void shutdown() + public static void Shutdown() { } + +#pragma warning disable IDE1006 + [Obsolete("This overload is deprecated and will be removed in v3.")] + public static void initialize() + => Initialize(); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public static void startup() + => Startup(); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public static void shutdown() + => Shutdown(); +#pragma warning restore IDE1006 } } diff --git a/src/chocolatey/infrastructure/registration/HttpsSecurity.cs b/src/chocolatey/infrastructure/registration/HttpsSecurity.cs new file mode 100644 index 0000000000..f04347da68 --- /dev/null +++ b/src/chocolatey/infrastructure/registration/HttpsSecurity.cs @@ -0,0 +1,63 @@ +namespace chocolatey.infrastructure.registration +{ + using System; + using System.Collections.Generic; + using System.Linq; + using System.Net; + using System.Text; + using System.Threading.Tasks; + + public static class HttpsSecurity + { + /// <summary> + /// Resets the <see cref="ServicePointManager.SecurityProtocol"/> and <see cref="ServicePointManager.ServerCertificateValidationCallback"/> for HTTPS connections + /// in order to ensure that PowerShell scripts we run can't have a persistent effect on these settings across the whole process after they're done running. + /// </summary> + public static void Reset() + { + // SystemDefault is used because: + // 1. Most supported operating systems default to / require TLS 1.2 anyway. + // 2. Explicitly *enabling* any less secure protocols leaves us open to TLS downgrade attacks. + // https://en.wikipedia.org/wiki/Downgrade_attack + // 3. Always *requiring* TLS 1.2 or higher on any OS version may cause issues with some folks' internal + // networks which may have older infrastructure that doesn't support it, and they won't have a way + // to make Chocolately CLI work with that infrastructure if we're forcing a TLS version they can't + // support. + // 4. Thus, the only sensible solution (since we don't want to add a configuration value for this) is + // to take the OS-level setting and use that, because if folks set their system up to use certain + // TLS versions, we should probably follow suit, regardless of what their OS version may be. + // + // See https://learn.microsoft.com/en-us/dotnet/framework/network-programming/tls for more information + // and best practices recommendation from the .NET team. + if (ServicePointManager.SecurityProtocol != SecurityProtocolType.SystemDefault) + { + "chocolatey".Log().Warn( + "{0} was set to {1}, resetting to SystemDefault.", + nameof(ServicePointManager.SecurityProtocol), + ServicePointManager.SecurityProtocol); + + ServicePointManager.SecurityProtocol = SecurityProtocolType.SystemDefault; + } + + try + { + // We reset this to ensure that if a package overrides this callback during its script runs, it doesn't affect the rest of + // the actions we need to take for the duration of this process (other packages we're installing, etc.) Setting this to + // null restores the default behaviour of certificate validation instead of whatever custom behaviour has been injected. + if (ServicePointManager.ServerCertificateValidationCallback != null) + { + "chocolatey".Log().Warn( + "{0} was set to '{1}' Removing.", + nameof(ServicePointManager.ServerCertificateValidationCallback), + ServicePointManager.ServerCertificateValidationCallback); + + ServicePointManager.ServerCertificateValidationCallback = null; + } + } + catch (Exception ex) + { + "chocolatey".Log().Warn("Error resetting ServerCertificateValidationCallback: {0}".FormatWith(ex.Message)); + } + } + } +} diff --git a/src/chocolatey/infrastructure/registration/SecurityProtocol.cs b/src/chocolatey/infrastructure/registration/SecurityProtocol.cs index d89f6c875c..a15a73d9a7 100644 --- a/src/chocolatey/infrastructure/registration/SecurityProtocol.cs +++ b/src/chocolatey/infrastructure/registration/SecurityProtocol.cs @@ -21,54 +21,12 @@ namespace chocolatey.infrastructure.registration using app.configuration; using logging; + [Obsolete("This type is deprecated and will be removed in v3.")] public sealed class SecurityProtocol { - private const int TLS_1_1 = 768; - private const int TLS_1_2 = 3072; - +#pragma warning disable IDE1006 public static void set_protocol(ChocolateyConfiguration config, bool provideWarning) - { - try - { - // We can't address the protocols directly when built with .NET - // Framework 4.0. However if someone is running .NET 4.5 or - // greater, they have in-place upgrades for System.dll, which - // will allow us to set these protocols directly. - const SecurityProtocolType tls11 = (SecurityProtocolType)TLS_1_1; - const SecurityProtocolType tls12 = (SecurityProtocolType)TLS_1_2; - ServicePointManager.SecurityProtocol = tls12 | tls11 | SecurityProtocolType.Tls | SecurityProtocolType.Ssl3; - } - catch (Exception) - { - ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Ssl3; - //todo: #2585 provide this warning with the ability to opt out of seeing it again so we can move it up to more prominent visibility and not just the verbose log - if (provideWarning) - { - "chocolatey".Log().Warn(ChocolateyLoggers.Verbose, -@" !!WARNING!! -Choco prefers to use TLS v1.2 if it is available, but this client is - running on .NET 4.0, which uses an older SSL. It's using TLS 1.0 or - earlier, which makes it susceptible to BEAST and also doesn't - implement the 1/n-1 record splitting mitigation for Cipher-Block - Chaining. Upgrade to at least .NET 4.5 at your earliest convenience. - - For more information you should visit https://www.howsmyssl.com/"); - } - } - - try - { - if (ServicePointManager.ServerCertificateValidationCallback != null) - { - "chocolatey".Log().Warn("ServerCertificateValidationCallback was set to '{0}' Removing.".format_with(System.Net.ServicePointManager.ServerCertificateValidationCallback)); - ServicePointManager.ServerCertificateValidationCallback = null; - } - } - catch (Exception ex) - { - "chocolatey".Log().Warn("Error resetting ServerCertificateValidationCallback: {0}".format_with(ex.Message)); - } - - } + => HttpsSecurity.Reset(); +#pragma warning restore IDE1006 } } diff --git a/src/chocolatey/infrastructure/registration/SimpleInjectorContainer.cs b/src/chocolatey/infrastructure/registration/SimpleInjectorContainer.cs index 55bc7d9c71..bc4a61e6a0 100644 --- a/src/chocolatey/infrastructure/registration/SimpleInjectorContainer.cs +++ b/src/chocolatey/infrastructure/registration/SimpleInjectorContainer.cs @@ -33,9 +33,9 @@ namespace chocolatey.infrastructure.registration /// </summary> public static class SimpleInjectorContainer { - private static readonly Lazy<Container> _container = new Lazy<Container>(initialize); + private static readonly Lazy<Container> _container = new Lazy<Container>(Initialize); private static readonly IList<Type> _componentRegistries = new List<Type>(); - private const string REGISTER_COMPONENTS_METHOD = "RegisterComponents"; + private const string RegisterComponentsMethod = "RegisterComponents"; #if DEBUG private static bool _verifyContainer = true; @@ -55,7 +55,7 @@ public static bool VerifyContainer /// and a parameterless constructor. /// </summary> /// <param name="componentType">Type of the component.</param> - public static void add_component_registry_class(Type componentType) + public static void AddComponentRegistryClass(Type componentType) { _componentRegistries.Add(componentType); } @@ -68,7 +68,7 @@ public static void add_component_registry_class(Type componentType) /// <summary> /// Initializes the container /// </summary> - private static Container initialize() + private static Container Initialize() { var container = new Container(); container.Options.AllowOverridingRegistrations = true; @@ -82,7 +82,7 @@ private static Container initialize() foreach (var componentRegistry in _componentRegistries) { - load_component_registry(componentRegistry, container, extensions); + LoadComponentRegistry(componentRegistry, container, extensions); } if (_verifyContainer) container.Verify(); @@ -96,11 +96,11 @@ private static Container initialize() /// <param name="componentRegistry">The component registry.</param> /// <param name="container">The container.</param> /// <param name="extensions">Any extension libraries</param> - private static void load_component_registry(Type componentRegistry, Container container, IEnumerable<ExtensionInformation> extensions) + private static void LoadComponentRegistry(Type componentRegistry, Container container, IEnumerable<ExtensionInformation> extensions) { if (componentRegistry == null) { - if (!extensions.Any(e => e.Name.is_equal_to("chocolatey.licensed"))) + if (!extensions.Any(e => e.Name.IsEqualTo("chocolatey.licensed"))) { "chocolatey".Log().Warn(ChocolateyLoggers.Important, @"Unable to register licensed components. This is likely related to a @@ -110,14 +110,14 @@ private static void load_component_registry(Type componentRegistry, Container co } try { - if (!extensions.Any(e => e.Name.is_equal_to(componentRegistry.Assembly.GetName().Name))) + if (!extensions.Any(e => e.Name.IsEqualTo(componentRegistry.Assembly.GetName().Name))) { var registrations = container.GetCurrentRegistrations(); object componentClass = Activator.CreateInstance(componentRegistry); componentRegistry.InvokeMember( - REGISTER_COMPONENTS_METHOD, + RegisterComponentsMethod, BindingFlags.InvokeMethod, null, componentClass, @@ -127,22 +127,29 @@ private static void load_component_registry(Type componentRegistry, Container co } catch (Exception ex) { - var isDebug = ApplicationParameters.is_debug_mode_cli_primitive(); + var isDebug = ApplicationParameters.IsDebugModeCliPrimitive(); var message = isDebug ? ex.ToString() : ex.Message; if (isDebug && ex.InnerException != null) { - message += "{0}{1}".format_with(Environment.NewLine, ex.InnerException.ToString()); + message += "{0}{1}".FormatWith(Environment.NewLine, ex.InnerException.ToString()); } "chocolatey".Log().Error( ChocolateyLoggers.Important, - @"Error when registering components for '{0}':{1} {2}".format_with( + @"Error when registering components for '{0}':{1} {2}".FormatWith( componentRegistry.FullName, Environment.NewLine, message )); } } + + +#pragma warning disable IDE1006 + [Obsolete("This overload is deprecated and will be removed in v3.")] + public static void add_component_registry_class(Type componentType) + => AddComponentRegistryClass(componentType); +#pragma warning restore IDE1006 } } diff --git a/src/chocolatey/infrastructure/results/PackageResult.cs b/src/chocolatey/infrastructure/results/PackageResult.cs index 572b90c926..f7b1f0d35b 100644 --- a/src/chocolatey/infrastructure/results/PackageResult.cs +++ b/src/chocolatey/infrastructure/results/PackageResult.cs @@ -55,16 +55,16 @@ public void ResetMetadata(IPackageMetadata metadata, IPackageSearchMetadata sear PackageMetadata = metadata; SearchMetadata = search; Name = metadata.Id; - Version = metadata.Version.to_string(); + Version = metadata.Version.ToStringSafe(); } - public PackageResult(IPackageMetadata packageMetadata, string installLocation, string source = null) : this(packageMetadata.Id, packageMetadata.Version.to_string(), installLocation) + public PackageResult(IPackageMetadata packageMetadata, string installLocation, string source = null) : this(packageMetadata.Id, packageMetadata.Version.ToStringSafe(), installLocation) { PackageMetadata = packageMetadata; Source = source; } - public PackageResult(IPackageSearchMetadata packageSearch, string installLocation, string source = null) : this(packageSearch.Identity.Id, packageSearch.Identity.Version.to_string(), installLocation) + public PackageResult(IPackageSearchMetadata packageSearch, string installLocation, string source = null) : this(packageSearch.Identity.Id, packageSearch.Identity.Version.ToStringSafe(), installLocation) { SearchMetadata = packageSearch; Source = source; @@ -78,13 +78,13 @@ public PackageResult(IPackageSearchMetadata packageSearch, string installLocatio } catch (Exception ex) { - this.Log().Debug("Unable to determine sources from '{0}'. Using value as is.{1} {2}".format_with(source, Environment.NewLine, ex.to_string())); + this.Log().Debug("Unable to determine sources from '{0}'. Using value as is.{1} {2}".FormatWith(source, Environment.NewLine, ex.ToStringSafe())); // source is already set above return; } } - Source = sources.FirstOrDefault(uri => uri.IsFile || uri.IsUnc).to_string(); + Source = sources.FirstOrDefault(uri => uri.IsFile || uri.IsUnc).ToStringSafe(); /* var rp = Package as DataServicePackage; if (rp != null && rp.DownloadUrl != null) @@ -103,7 +103,7 @@ public PackageResult(IPackageSearchMetadata packageSearch, string installLocatio */ } - public PackageResult(IPackageMetadata packageMetadata, IPackageSearchMetadata packageSearch, string installLocation, string source = null) : this(packageMetadata.Id, packageMetadata.Version.to_string(), installLocation) + public PackageResult(IPackageMetadata packageMetadata, IPackageSearchMetadata packageSearch, string installLocation, string source = null) : this(packageMetadata.Id, packageMetadata.Version.ToStringSafe(), installLocation) { SearchMetadata = packageSearch; PackageMetadata = packageMetadata; @@ -116,13 +116,13 @@ public PackageResult(IPackageMetadata packageMetadata, IPackageSearchMetadata pa } catch (Exception ex) { - this.Log().Debug("Unable to determine sources from '{0}'. Using value as is.{1} {2}".format_with(source, Environment.NewLine, ex.to_string())); + this.Log().Debug("Unable to determine sources from '{0}'. Using value as is.{1} {2}".FormatWith(source, Environment.NewLine, ex.ToStringSafe())); // source is already set above return; } } - Source = sources.FirstOrDefault(uri => uri.IsFile || uri.IsUnc).to_string(); + Source = sources.FirstOrDefault(uri => uri.IsFile || uri.IsUnc).ToStringSafe(); } public PackageResult(string name, string version, string installLocation, string source = null) diff --git a/src/chocolatey/infrastructure/rules/IMetadataRule.cs b/src/chocolatey/infrastructure/rules/IMetadataRule.cs index 23276a0429..d444e57b93 100644 --- a/src/chocolatey/infrastructure/rules/IMetadataRule.cs +++ b/src/chocolatey/infrastructure/rules/IMetadataRule.cs @@ -15,6 +15,7 @@ namespace chocolatey.infrastructure.rules { + using System; using System.Collections.Generic; using chocolatey.infrastructure.app.attributes; using NuGet.Packaging; @@ -22,6 +23,13 @@ namespace chocolatey.infrastructure.rules [MultiService] public interface IMetadataRule { + IEnumerable<RuleResult> Validate(NuspecReader reader); + + IReadOnlyList<ImmutableRule> GetAvailableRules(); + +#pragma warning disable IDE1006 + [Obsolete("This overload is deprecated and will be removed in v3.")] IEnumerable<RuleResult> validate(NuspecReader reader); +#pragma warning restore IDE1006 } } diff --git a/src/chocolatey/infrastructure/rules/ImmutableRule.cs b/src/chocolatey/infrastructure/rules/ImmutableRule.cs new file mode 100644 index 0000000000..c288268a4b --- /dev/null +++ b/src/chocolatey/infrastructure/rules/ImmutableRule.cs @@ -0,0 +1,33 @@ +// Copyright © 2023-Present Chocolatey Software, Inc +// +// 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. + +namespace chocolatey.infrastructure.rules +{ + public readonly struct ImmutableRule + { + public ImmutableRule(RuleType severity, string id, string summary, string helpUrl = null) + { + Severity = severity; + Id = id; + Summary = summary; + HelpUrl = helpUrl; + } + + public readonly RuleType Severity; + public readonly string Id; + public readonly string Summary; + public readonly string HelpUrl; + } +} diff --git a/src/chocolatey/infrastructure/rules/RuleResult.cs b/src/chocolatey/infrastructure/rules/RuleResult.cs index 3ad07810fd..a3a1c90fe2 100644 --- a/src/chocolatey/infrastructure/rules/RuleResult.cs +++ b/src/chocolatey/infrastructure/rules/RuleResult.cs @@ -28,5 +28,17 @@ public RuleResult(RuleType severity, string id, string message) public string Id { get; private set; } public string Message { get; private set; } public RuleType Severity { get; set; } + + internal static RuleResult FromImmutableRule(ImmutableRule result, string summary = null) + { + if (string.IsNullOrEmpty(summary)) + { + return new RuleResult(result.Severity, result.Id, result.Summary) { HelpUrl = result.HelpUrl }; + } + else + { + return new RuleResult(result.Severity, result.Id, summary) { HelpUrl = result.HelpUrl }; + } + } } } diff --git a/src/chocolatey/infrastructure/services/EventSubscriptionManagerService.cs b/src/chocolatey/infrastructure/services/EventSubscriptionManagerService.cs index 6a166b4eb0..9f931afb37 100644 --- a/src/chocolatey/infrastructure/services/EventSubscriptionManagerService.cs +++ b/src/chocolatey/infrastructure/services/EventSubscriptionManagerService.cs @@ -33,16 +33,16 @@ public class EventSubscriptionManagerService : IEventSubscriptionManagerService private readonly ISubject<object> _subject = new Subject<object>(); - public void publish<Event>(Event eventMessage) where Event : class, IMessage + public void Publish<Event>(Event eventMessage) where Event : class, IMessage { - Ensure.that(() => eventMessage).is_not_null(); + Ensure.That(() => eventMessage).NotNull(); - this.Log().Debug(ChocolateyLoggers.Verbose, () => "Sending message '{0}' out if there are subscribers...".format_with(typeof (Event).Name)); + this.Log().Debug(ChocolateyLoggers.Verbose, () => "Sending message '{0}' out if there are subscribers...".FormatWith(typeof (Event).Name)); _subject.OnNext(eventMessage); } - public IDisposable subscribe<Event>(Action<Event> handleEvent, Action<Exception> handleError, Func<Event, bool> filter) where Event : class, IMessage + public IDisposable Subscribe<Event>(Action<Event> handleEvent, Action<Exception> handleError, Func<Event, bool> filter) where Event : class, IMessage { if (filter == null) filter = (message) => true; if (handleError == null) handleError = (ex) => { }; @@ -53,5 +53,15 @@ public IDisposable subscribe<Event>(Action<Event> handleEvent, Action<Exception> return subscription; } + +#pragma warning disable IDE1006 + [Obsolete("This overload is deprecated and will be removed in v3.")] + public void publish<Event>(Event eventMessage) where Event : class, IMessage + => Publish(eventMessage); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public IDisposable subscribe<Event>(Action<Event> handleEvent, Action<Exception> handleError, Func<Event, bool> filter) where Event : class, IMessage + => Subscribe(handleEvent, handleError, filter); +#pragma warning restore IDE1006 } } diff --git a/src/chocolatey/infrastructure/services/IDateTimeService.cs b/src/chocolatey/infrastructure/services/IDateTimeService.cs index 3dd754dd27..e5ba1584fe 100644 --- a/src/chocolatey/infrastructure/services/IDateTimeService.cs +++ b/src/chocolatey/infrastructure/services/IDateTimeService.cs @@ -26,6 +26,11 @@ public interface IDateTimeService /// <summary> /// Gets the current date time. /// </summary> + DateTime? GetCurrentDateTime(); + +#pragma warning disable IDE1006 + [Obsolete("This overload is deprecated and will be removed in v3.")] DateTime? get_current_date_time(); +#pragma warning restore IDE1006 } } diff --git a/src/chocolatey/infrastructure/services/IEventSubscriptionManagerService.cs b/src/chocolatey/infrastructure/services/IEventSubscriptionManagerService.cs index 8c8f8f6e63..b90b3ce8ab 100644 --- a/src/chocolatey/infrastructure/services/IEventSubscriptionManagerService.cs +++ b/src/chocolatey/infrastructure/services/IEventSubscriptionManagerService.cs @@ -29,7 +29,7 @@ public interface IEventSubscriptionManagerService /// </summary> /// <typeparam name="Event">The type of the event.</typeparam> /// <param name="eventMessage">The message to publish.</param> - void publish<Event>(Event eventMessage) where Event : class, IMessage; + void Publish<Event>(Event eventMessage) where Event : class, IMessage; /// <summary> /// Subscribes to the specified event. @@ -39,6 +39,14 @@ public interface IEventSubscriptionManagerService /// <param name="handleError">The error handler.</param> /// <param name="filter">The message filter.</param> /// <returns>The subscription as Disposable</returns> + IDisposable Subscribe<Event>(Action<Event> handleEvent, Action<Exception> handleError, Func<Event, bool> filter) where Event : class, IMessage; + +#pragma warning disable IDE1006 + [Obsolete("This overload is deprecated and will be removed in v3.")] + void publish<Event>(Event eventMessage) where Event : class, IMessage; + + [Obsolete("This overload is deprecated and will be removed in v3.")] IDisposable subscribe<Event>(Action<Event> handleEvent, Action<Exception> handleError, Func<Event, bool> filter) where Event : class, IMessage; +#pragma warning restore IDE1006 } } diff --git a/src/chocolatey/infrastructure/services/IRegularExpressionService.cs b/src/chocolatey/infrastructure/services/IRegularExpressionService.cs index 62efa275b1..5d626a564c 100644 --- a/src/chocolatey/infrastructure/services/IRegularExpressionService.cs +++ b/src/chocolatey/infrastructure/services/IRegularExpressionService.cs @@ -16,6 +16,7 @@ namespace chocolatey.infrastructure.services { + using System; using System.Text.RegularExpressions; /// <summary> @@ -30,6 +31,11 @@ public interface IRegularExpressionService /// <param name="pattern">The pattern.</param> /// <param name="matchEvaluator">The match evaluator.</param> /// <returns></returns> + string Replace(string input, string pattern, MatchEvaluator matchEvaluator); + +#pragma warning disable IDE1006 + [Obsolete("This overload is deprecated and will be removed in v3.")] string replace(string input, string pattern, MatchEvaluator matchEvaluator); +#pragma warning restore IDE1006 } } diff --git a/src/chocolatey/infrastructure/services/IRuleService.cs b/src/chocolatey/infrastructure/services/IRuleService.cs index 3843fb9cb9..e4c211cdf0 100644 --- a/src/chocolatey/infrastructure/services/IRuleService.cs +++ b/src/chocolatey/infrastructure/services/IRuleService.cs @@ -15,11 +15,17 @@ namespace chocolatey.infrastructure.services { + using System; using System.Collections.Generic; using chocolatey.infrastructure.rules; public interface IRuleService { + IEnumerable<RuleResult> ValidateRules(string filePath); + +#pragma warning disable IDE1006 + [Obsolete("This overload is deprecated and will be removed in v3.")] IEnumerable<RuleResult> validate_rules(string filePath); +#pragma warning restore IDE1006 } } diff --git a/src/chocolatey/infrastructure/services/IXmlService.cs b/src/chocolatey/infrastructure/services/IXmlService.cs index 10f33e9df9..eb2aa8389f 100644 --- a/src/chocolatey/infrastructure/services/IXmlService.cs +++ b/src/chocolatey/infrastructure/services/IXmlService.cs @@ -16,6 +16,8 @@ namespace chocolatey.infrastructure.services { + using System; + public interface IXmlService { /// <summary> @@ -24,7 +26,7 @@ public interface IXmlService /// <typeparam name="XmlType">The type of the ml type.</typeparam> /// <param name="xmlFilePath">The XML file path.</param> /// <returns></returns> - XmlType deserialize<XmlType>(string xmlFilePath); + XmlType Deserialize<XmlType>(string xmlFilePath); /// <summary> /// Deserializes the specified XML file path. @@ -33,7 +35,7 @@ public interface IXmlService /// <param name="xmlFilePath">The XML file path.</param> /// <param name="retryCount">The number of times to attempt deserialization on event of a failure.</param> /// <returns></returns> - XmlType deserialize<XmlType>(string xmlFilePath, int retryCount); + XmlType Deserialize<XmlType>(string xmlFilePath, int retryCount); /// <summary> /// Serializes the specified XML type. @@ -41,7 +43,7 @@ public interface IXmlService /// <typeparam name="XmlType">The type of the ml type.</typeparam> /// <param name="xmlType">Type of the XML.</param> /// <param name="xmlFilePath">The XML file path.</param> - void serialize<XmlType>(XmlType xmlType, string xmlFilePath); + void Serialize<XmlType>(XmlType xmlType, string xmlFilePath); /// <summary> /// Serializes the specified XML type. @@ -50,6 +52,20 @@ public interface IXmlService /// <param name="xmlType">Type of the XML.</param> /// <param name="xmlFilePath">The XML file path.</param> /// <param name="isSilent">Log messages?</param> + void Serialize<XmlType>(XmlType xmlType, string xmlFilePath, bool isSilent); + +#pragma warning disable IDE1006 + [Obsolete("This overload is deprecated and will be removed in v3.")] + XmlType deserialize<XmlType>(string xmlFilePath); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + XmlType deserialize<XmlType>(string xmlFilePath, int retryCount); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + void serialize<XmlType>(XmlType xmlType, string xmlFilePath); + + [Obsolete("This overload is deprecated and will be removed in v3.")] void serialize<XmlType>(XmlType xmlType, string xmlFilePath, bool isSilent); +#pragma warning restore IDE1006 } } diff --git a/src/chocolatey/infrastructure/services/RegularExpressionService.cs b/src/chocolatey/infrastructure/services/RegularExpressionService.cs index e4a9397b56..123c6d1132 100644 --- a/src/chocolatey/infrastructure/services/RegularExpressionService.cs +++ b/src/chocolatey/infrastructure/services/RegularExpressionService.cs @@ -16,6 +16,7 @@ namespace chocolatey.infrastructure.services { + using System; using System.Text.RegularExpressions; /// <summary> @@ -23,10 +24,16 @@ namespace chocolatey.infrastructure.services /// </summary> public class RegularExpressionService : IRegularExpressionService { - public string replace(string input, string pattern, MatchEvaluator matchEvaluator) + public string Replace(string input, string pattern, MatchEvaluator matchEvaluator) { var regex = new Regex(pattern, RegexOptions.IgnoreCase | RegexOptions.Multiline); return regex.Replace(input, matchEvaluator); } + +#pragma warning disable IDE1006 + [Obsolete("This overload is deprecated and will be removed in v3.")] + public string replace(string input, string pattern, MatchEvaluator matchEvaluator) + => Replace(input, pattern, matchEvaluator); +#pragma warning restore IDE1006 } } diff --git a/src/chocolatey/infrastructure/services/SystemDateTimeService.cs b/src/chocolatey/infrastructure/services/SystemDateTimeService.cs index e3447330b3..6bd0eafd59 100644 --- a/src/chocolatey/infrastructure/services/SystemDateTimeService.cs +++ b/src/chocolatey/infrastructure/services/SystemDateTimeService.cs @@ -23,9 +23,15 @@ namespace chocolatey.infrastructure.services /// </summary> public class SystemDateTimeService : IDateTimeService { - public DateTime? get_current_date_time() + public DateTime? GetCurrentDateTime() { return DateTime.Now; } + +#pragma warning disable IDE1006 + [Obsolete("This overload is deprecated and will be removed in v3.")] + public DateTime? get_current_date_time() + => GetCurrentDateTime(); +#pragma warning restore IDE1006 } } diff --git a/src/chocolatey/infrastructure/services/SystemDateTimeUtcService.cs b/src/chocolatey/infrastructure/services/SystemDateTimeUtcService.cs index d08b77219f..cb11d04087 100644 --- a/src/chocolatey/infrastructure/services/SystemDateTimeUtcService.cs +++ b/src/chocolatey/infrastructure/services/SystemDateTimeUtcService.cs @@ -23,9 +23,15 @@ namespace chocolatey.infrastructure.services /// </summary> public class SystemDateTimeUtcService : IDateTimeService { - public DateTime? get_current_date_time() + public DateTime? GetCurrentDateTime() { return DateTime.UtcNow; } + +#pragma warning disable IDE1006 + [Obsolete("This overload is deprecated and will be removed in v3.")] + public DateTime? get_current_date_time() + => GetCurrentDateTime(); +#pragma warning restore IDE1006 } } diff --git a/src/chocolatey/infrastructure/services/XmlService.cs b/src/chocolatey/infrastructure/services/XmlService.cs index f5086c58a9..3a5e10116f 100644 --- a/src/chocolatey/infrastructure/services/XmlService.cs +++ b/src/chocolatey/infrastructure/services/XmlService.cs @@ -34,7 +34,7 @@ public sealed class XmlService : IXmlService { private readonly IFileSystem _fileSystem; private readonly IHashProvider _hashProvider; - private const int MUTEX_TIMEOUT = 2000; + private const int MutexTimeout = 2000; public XmlService(IFileSystem fileSystem, IHashProvider hashProvider) { @@ -42,23 +42,23 @@ public XmlService(IFileSystem fileSystem, IHashProvider hashProvider) _hashProvider = hashProvider; } - public XmlType deserialize<XmlType>(string xmlFilePath) + public XmlType Deserialize<XmlType>(string xmlFilePath) { - return deserialize<XmlType>(xmlFilePath, 3); + return Deserialize<XmlType>(xmlFilePath, 3); } - public XmlType deserialize<XmlType>(string xmlFilePath, int retryCount) + public XmlType Deserialize<XmlType>(string xmlFilePath, int retryCount) { - return FaultTolerance.retry(retryCount, () => GlobalMutex.enter( + return FaultTolerance.Retry(retryCount, () => GlobalMutex.Enter( () => { - this.Log().Trace("Entered mutex to deserialize '{0}'".format_with(xmlFilePath)); + this.Log().Trace("Entered mutex to deserialize '{0}'".FormatWith(xmlFilePath)); - return FaultTolerance.try_catch_with_logging_exception( + return FaultTolerance.TryCatchWithLoggingException( () => { var xmlSerializer = new XmlSerializer(typeof(XmlType)); - using (var fileStream = _fileSystem.open_file_readonly(xmlFilePath)) + using (var fileStream = _fileSystem.OpenFileReadonly(xmlFilePath)) using (var fileReader = new StreamReader(fileStream)) using (var xmlReader = XmlReader.Create(fileReader)) { @@ -78,9 +78,9 @@ public XmlType deserialize<XmlType>(string xmlFilePath, int retryCount) if (ex.Message.Contains("There is an error in XML document")) { // If so, check for a backup file and try an parse that. - if (_fileSystem.file_exists(xmlFilePath + ".backup")) + if (_fileSystem.FileExists(xmlFilePath + ".backup")) { - using (var backupStream = _fileSystem.open_file_readonly(xmlFilePath + ".backup")) + using (var backupStream = _fileSystem.OpenFileReadonly(xmlFilePath + ".backup")) using (var backupReader = new StreamReader(backupStream)) using (var backupXmlReader = XmlReader.Create(backupReader)) { @@ -91,7 +91,7 @@ public XmlType deserialize<XmlType>(string xmlFilePath, int retryCount) { // Close fileReader so that we can copy the file without it being locked. fileReader.Close(); - _fileSystem.copy_file(xmlFilePath + ".backup", xmlFilePath, overwriteExisting: true); + _fileSystem.CopyFile(xmlFilePath + ".backup", xmlFilePath, overwriteExisting: true); } return validConfig; @@ -104,11 +104,11 @@ public XmlType deserialize<XmlType>(string xmlFilePath, int retryCount) } finally { - foreach (var updateFile in _fileSystem.get_files(_fileSystem.get_directory_name(xmlFilePath), "*.update").or_empty_list_if_null()) + foreach (var updateFile in _fileSystem.GetFiles(_fileSystem.GetDirectoryName(xmlFilePath), "*.update").OrEmpty()) { - this.Log().Debug("Removing '{0}'".format_with(updateFile)); - FaultTolerance.try_catch_with_logging_exception( - () => _fileSystem.delete_file(updateFile), + this.Log().Debug("Removing '{0}'".FormatWith(updateFile)); + FaultTolerance.TryCatchWithLoggingException( + () => _fileSystem.DeleteFile(updateFile), errorMessage: "Unable to remove update file", logDebugInsteadOfError: true, isSilent: true @@ -117,28 +117,28 @@ public XmlType deserialize<XmlType>(string xmlFilePath, int retryCount) } } }, - "Error deserializing response of type {0}".format_with(typeof(XmlType)), + "Error deserializing response of type {0}".FormatWith(typeof(XmlType)), throwError: true); - }, MUTEX_TIMEOUT), + }, MutexTimeout), waitDurationMilliseconds: 200, increaseRetryByMilliseconds: 200); } - public void serialize<XmlType>(XmlType xmlType, string xmlFilePath) + public void Serialize<XmlType>(XmlType xmlType, string xmlFilePath) { - serialize(xmlType, xmlFilePath, isSilent: false); + Serialize(xmlType, xmlFilePath, isSilent: false); } - public void serialize<XmlType>(XmlType xmlType, string xmlFilePath, bool isSilent) + public void Serialize<XmlType>(XmlType xmlType, string xmlFilePath, bool isSilent) { - _fileSystem.create_directory_if_not_exists(_fileSystem.get_directory_name(xmlFilePath)); + _fileSystem.EnsureDirectoryExists(_fileSystem.GetDirectoryName(xmlFilePath)); - FaultTolerance.retry(3, () => GlobalMutex.enter( + FaultTolerance.Retry(3, () => GlobalMutex.Enter( () => { - this.Log().Trace("Entered mutex to serialize '{0}'".format_with(xmlFilePath)); - FaultTolerance.try_catch_with_logging_exception( + this.Log().Trace("Entered mutex to serialize '{0}'".FormatWith(xmlFilePath)); + FaultTolerance.TryCatchWithLoggingException( () => { var xmlSerializer = new XmlSerializer(typeof(XmlType)); @@ -154,18 +154,18 @@ public void serialize<XmlType>(XmlType xmlType, string xmlFilePath, bool isSilen streamWriter.Flush(); // Grab the hash of both files and compare them. - this.Log().Trace("Hashing original file at '{0}'".format_with(xmlFilePath)); - var originalFileHash = _hashProvider.hash_file(xmlFilePath); + this.Log().Trace("Hashing original file at '{0}'".FormatWith(xmlFilePath)); + var originalFileHash = _hashProvider.ComputeFileHash(xmlFilePath); memoryStream.Position = 0; - if (!originalFileHash.is_equal_to(_hashProvider.hash_stream(memoryStream))) + if (!originalFileHash.IsEqualTo(_hashProvider.ComputeStreamHash(memoryStream))) { this.Log().Trace("The hashes were different."); // If there wasn't a file there in the first place, just write the new one out directly. if (string.IsNullOrEmpty(originalFileHash)) { - this.Log().Debug("There was no original file at '{0}'".format_with(xmlFilePath)); + this.Log().Debug("There was no original file at '{0}'".FormatWith(xmlFilePath)); memoryStream.Position = 0; - _fileSystem.write_file(xmlFilePath, () => memoryStream); + _fileSystem.WriteFile(xmlFilePath, () => memoryStream); this.Log().Trace("Closing xml memory stream."); memoryStream.Close(); @@ -176,25 +176,43 @@ public void serialize<XmlType>(XmlType xmlType, string xmlFilePath, bool isSilen // Otherwise, create an update file, and resiliently move it into place. var tempUpdateFile = xmlFilePath + "." + Process.GetCurrentProcess().Id + ".update"; - this.Log().Trace("Creating a temp file at '{0}'".format_with(tempUpdateFile)); + this.Log().Trace("Creating a temp file at '{0}'".FormatWith(tempUpdateFile)); memoryStream.Position = 0; - this.Log().Trace("Writing file '{0}'".format_with(tempUpdateFile)); - _fileSystem.write_file(tempUpdateFile, () => memoryStream); + this.Log().Trace("Writing file '{0}'".FormatWith(tempUpdateFile)); + _fileSystem.WriteFile(tempUpdateFile, () => memoryStream); memoryStream.Close(); streamWriter.Close(); - this.Log().Trace("Replacing file '{0}' with '{1}'.".format_with(xmlFilePath, tempUpdateFile)); - _fileSystem.replace_file(tempUpdateFile, xmlFilePath, xmlFilePath + ".backup"); + this.Log().Trace("Replacing file '{0}' with '{1}'.".FormatWith(xmlFilePath, tempUpdateFile)); + _fileSystem.ReplaceFile(tempUpdateFile, xmlFilePath, xmlFilePath + ".backup"); } } }, - errorMessage: "Error serializing type {0}".format_with(typeof(XmlType)), + errorMessage: "Error serializing type {0}".FormatWith(typeof(XmlType)), throwError: true, isSilent: isSilent); - }, MUTEX_TIMEOUT), + }, MutexTimeout), waitDurationMilliseconds: 200, increaseRetryByMilliseconds: 200); } + +#pragma warning disable IDE1006 + [Obsolete("This overload is deprecated and will be removed in v3.")] + public XmlType deserialize<XmlType>(string xmlFilePath) + => Deserialize<XmlType>(xmlFilePath); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public XmlType deserialize<XmlType>(string xmlFilePath, int retryCount) + => Deserialize<XmlType>(xmlFilePath, retryCount); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public void serialize<XmlType>(XmlType xmlType, string xmlFilePath) + => Serialize<XmlType>(xmlType, xmlFilePath); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public void serialize<XmlType>(XmlType xmlType, string xmlFilePath, bool isSilent) + => Serialize<XmlType>(xmlType, xmlFilePath, isSilent); +#pragma warning restore IDE1006 } } diff --git a/src/chocolatey/infrastructure/synchronization/GlobalMutex.cs b/src/chocolatey/infrastructure/synchronization/GlobalMutex.cs index a78ca21f15..892953fc64 100644 --- a/src/chocolatey/infrastructure/synchronization/GlobalMutex.cs +++ b/src/chocolatey/infrastructure/synchronization/GlobalMutex.cs @@ -32,13 +32,13 @@ namespace chocolatey.infrastructure.synchronization public class GlobalMutex : IDisposable { private readonly bool _hasHandle = false; - private const string APP_GUID = "bd59231e-97d1-4fc0-a975-80c3fed498b7"; // matches the one in Assembly + private const string AppGuid = "bd59231e-97d1-4fc0-a975-80c3fed498b7"; // matches the one in Assembly private Mutex _mutex; - private void init_mutex() + private void InitMutex() { this.Log().Trace("Initializing global mutex"); - var mutexId = "Global\\{{{0}}}".format_with(APP_GUID); + var mutexId = "Global\\{{{0}}}".FormatWith(AppGuid); _mutex = new Mutex(initiallyOwned: false, name: mutexId); var allowEveryoneRule = new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), MutexRights.FullControl, AccessControlType.Allow); @@ -54,10 +54,10 @@ private void init_mutex() /// <exception cref="System.TimeoutException">Timeout waiting for exclusive access to value.</exception> private GlobalMutex(int timeOut) { - init_mutex(); + InitMutex(); try { - this.Log().Trace("Waiting on the mutex handle for {0} milliseconds".format_with(timeOut)); + this.Log().Trace("Waiting on the mutex handle for {0} milliseconds".FormatWith(timeOut)); _hasHandle = _mutex.WaitOne(timeOut < 0 ? Timeout.Infinite : timeOut, exitContext: false); if (_hasHandle == false) @@ -75,11 +75,11 @@ private GlobalMutex(int timeOut) /// Enters the Global Mutex /// </summary> /// <param name="action">The action to perform.</param> - /// <param name="timeout">The timeout in seconds.</param> - public static void enter(Action action, int timeout) + /// <param name="timeout">The timeout in milliseconds.</param> + public static void Enter(Action action, int timeout) { - if (Platform.get_platform() == PlatformType.Windows) + if (Platform.GetPlatform() == PlatformType.Windows) { using (new GlobalMutex(timeout)) { @@ -99,11 +99,11 @@ public static void enter(Action action, int timeout) /// <param name="func">The function to perform.</param> /// <param name="timeout">The timeout in seconds.</param> /// <returns></returns> - public static T enter<T>(Func<T> func, int timeout) + public static T Enter<T>(Func<T> func, int timeout) { var returnValue = default(T); - if (Platform.get_platform() == PlatformType.Windows) + if (Platform.GetPlatform() == PlatformType.Windows) { using (new GlobalMutex(timeout)) { @@ -129,5 +129,15 @@ public void Dispose() _mutex.Dispose(); } } + +#pragma warning disable IDE1006 + [Obsolete("This overload is deprecated and will be removed in v3.")] + public static void enter(Action action, int timeout) + => Enter(action, timeout); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public static T enter<T>(Func<T> func, int timeout) + => Enter(func, timeout); +#pragma warning restore IDE1006 } } diff --git a/src/chocolatey/infrastructure/tasks/ITask.cs b/src/chocolatey/infrastructure/tasks/ITask.cs index c331cb9ed9..35d3c5abfd 100644 --- a/src/chocolatey/infrastructure/tasks/ITask.cs +++ b/src/chocolatey/infrastructure/tasks/ITask.cs @@ -17,6 +17,7 @@ namespace chocolatey.infrastructure.tasks { using chocolatey.infrastructure.app.attributes; + using System; /// <summary> /// Interface for all runners. @@ -28,11 +29,19 @@ public interface ITask /// Initializes a task. This should be initialized to run on a schedule, a trigger, a subscription to event messages, /// etc, or some combination of the above. /// </summary> - void initialize(); + void Initialize(); /// <summary> /// Shuts down a task that is in a waiting state. Turns off all schedules, triggers or subscriptions. /// </summary> + void Shutdown(); + +#pragma warning disable IDE1006 + [Obsolete("This overload is deprecated and will be removed in v3.")] + void initialize(); + + [Obsolete("This overload is deprecated and will be removed in v3.")] void shutdown(); +#pragma warning restore IDE1006 } } diff --git a/src/chocolatey/infrastructure/tokens/TokenReplacer.cs b/src/chocolatey/infrastructure/tokens/TokenReplacer.cs index 8c1e4028d0..db107f4ba1 100644 --- a/src/chocolatey/infrastructure/tokens/TokenReplacer.cs +++ b/src/chocolatey/infrastructure/tokens/TokenReplacer.cs @@ -16,27 +16,28 @@ namespace chocolatey.infrastructure.tokens { + using System; using System.Collections.Generic; using System.Reflection; using System.Text.RegularExpressions; public sealed class TokenReplacer { - public static string replace_tokens<TConfig>(TConfig configuration, string textToReplace, string tokenPrefix = "[[", string tokenSuffix = "]]") + public static string ReplaceTokens<TConfig>(TConfig configuration, string textToReplace, string tokenPrefix = "[[", string tokenSuffix = "]]") { if (string.IsNullOrEmpty(textToReplace)) return string.Empty; - IDictionary<string, string> dictionary = create_dictionary_from_configuration(configuration); + IDictionary<string, string> dictionary = CreateDictionaryFromConfiguration(configuration); if (dictionary.Count == 0) return textToReplace; - var regex = new Regex("{0}(?<key>\\w+){1}".format_with(Regex.Escape(tokenPrefix), Regex.Escape(tokenSuffix))); + var regex = new Regex("{0}(?<key>\\w+){1}".FormatWith(Regex.Escape(tokenPrefix), Regex.Escape(tokenSuffix))); string output = regex.Replace(textToReplace, m => { string key = ""; var originalKey = m.Groups["key"].Value; - key = originalKey.to_lower(); + key = originalKey.ToLowerSafe(); if (!dictionary.ContainsKey(key)) { return tokenPrefix + originalKey + tokenSuffix; @@ -49,28 +50,38 @@ public static string replace_tokens<TConfig>(TConfig configuration, string textT return output; } - private static IDictionary<string, string> create_dictionary_from_configuration<TConfig>(TConfig configuration) + private static IDictionary<string, string> CreateDictionaryFromConfiguration<TConfig>(TConfig configuration) { if (configuration is IDictionary<string, string>) return configuration as IDictionary<string, string>; var propertyDictionary = new Dictionary<string, string>(); foreach (PropertyInfo property in configuration.GetType().GetProperties()) { - propertyDictionary.Add(property.Name.to_lower(), property.GetValue(configuration, null).to_string()); + propertyDictionary.Add(property.Name.ToLowerSafe(), property.GetValue(configuration, null).ToStringSafe()); } return propertyDictionary; } - public static IEnumerable<string> get_tokens(string textWithTokens, string tokenPrefix = "[[", string tokenSuffix = "]]") + public static IEnumerable<string> GetTokens(string textWithTokens, string tokenPrefix = "[[", string tokenSuffix = "]]") { var regexMatches = Regex.Matches(textWithTokens, "{0}(?<key>\\w+){1}" - .format_with(Regex.Escape(tokenPrefix), Regex.Escape(tokenSuffix)) + .FormatWith(Regex.Escape(tokenPrefix), Regex.Escape(tokenSuffix)) ); foreach (Match regexMatch in regexMatches) { - yield return regexMatch.Groups["key"].to_string(); + yield return regexMatch.Groups["key"].ToStringSafe(); } } + +#pragma warning disable IDE1006 + [Obsolete("This overload is deprecated and will be removed in v3.")] + public static string replace_tokens<TConfig>(TConfig configuration, string textToReplace, string tokenPrefix = "[[", string tokenSuffix = "]]") + => ReplaceTokens(configuration, textToReplace, tokenPrefix, tokenSuffix); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public static IEnumerable<string> get_tokens(string textWithTokens, string tokenPrefix = "[[", string tokenSuffix = "]]") + => GetTokens(textWithTokens, tokenPrefix, tokenSuffix); +#pragma warning restore IDE1006 } } diff --git a/src/chocolatey/infrastructure/tolerance/FaultTolerance.cs b/src/chocolatey/infrastructure/tolerance/FaultTolerance.cs index 3a96745d2f..b5aa14d20d 100644 --- a/src/chocolatey/infrastructure/tolerance/FaultTolerance.cs +++ b/src/chocolatey/infrastructure/tolerance/FaultTolerance.cs @@ -26,12 +26,12 @@ namespace chocolatey.infrastructure.tolerance /// </summary> public class FaultTolerance { - private static bool log_is_in_debug_mode() + private static bool InDebugMode() { var debugging = false; try { - debugging = Config.get_configuration_settings().Debug; + debugging = Config.GetConfigurationSettings().Debug; } catch { @@ -49,11 +49,11 @@ private static bool log_is_in_debug_mode() /// <param name="waitDurationMilliseconds">The wait duration in milliseconds.</param> /// <param name="increaseRetryByMilliseconds">The time for each try to increase the wait duration by in milliseconds.</param> /// <param name="isSilent">Log messages?</param> - public static void retry(int numberOfTries, Action action, int waitDurationMilliseconds = 100, int increaseRetryByMilliseconds = 0, bool isSilent = false) + public static void Retry(int numberOfTries, Action action, int waitDurationMilliseconds = 100, int increaseRetryByMilliseconds = 0, bool isSilent = false) { if (action == null) return; - var success = retry( + var success = Retry( numberOfTries, () => { @@ -76,13 +76,13 @@ public static void retry(int numberOfTries, Action action, int waitDurationMilli /// <returns>The return value from the function</returns> /// <exception cref="System.ApplicationException">You must specify a number of retries greater than zero.</exception> /// <param name="isSilent">Log messages?</param> - public static T retry<T>(int numberOfTries, Func<T> function, int waitDurationMilliseconds = 100, int increaseRetryByMilliseconds = 0, bool isSilent = false) + public static T Retry<T>(int numberOfTries, Func<T> function, int waitDurationMilliseconds = 100, int increaseRetryByMilliseconds = 0, bool isSilent = false) { if (function == null) return default(T); if (numberOfTries == 0) throw new ApplicationException("You must specify a number of tries greater than zero."); var returnValue = default(T); - var debugging = log_is_in_debug_mode(); + var debugging = InDebugMode(); var logLocation = ChocolateyLoggers.Normal; if (isSilent) logLocation = ChocolateyLoggers.LogFileOnly; @@ -97,7 +97,7 @@ public static T retry<T>(int numberOfTries, Func<T> function, int waitDurationMi { if (i == numberOfTries) { - "chocolatey".Log().Error(logLocation, "Maximum tries of {0} reached. Throwing error.".format_with(numberOfTries)); + "chocolatey".Log().Error(logLocation, "Maximum tries of {0} reached. Throwing error.".FormatWith(numberOfTries)); throw; } @@ -105,7 +105,7 @@ public static T retry<T>(int numberOfTries, Func<T> function, int waitDurationMi var exceptionMessage = debugging ? ex.ToString() : ex.Message; - "chocolatey".Log().Warn(logLocation, "This is try {3}/{4}. Retrying after {2} milliseconds.{0} Error converted to warning:{0} {1}".format_with( + "chocolatey".Log().Warn(logLocation, "This is try {3}/{4}. Retrying after {2} milliseconds.{0} Error converted to warning:{0} {1}".FormatWith( Environment.NewLine, exceptionMessage, retryWait, @@ -127,11 +127,11 @@ public static T retry<T>(int numberOfTries, Func<T> function, int waitDurationMi /// <param name="logWarningInsteadOfError">if set to <c>true</c> log as warning instead of error.</param> /// <param name="logDebugInsteadOfError">Log to debug</param> /// <param name="isSilent">Log messages?</param> - public static void try_catch_with_logging_exception(Action action, string errorMessage, bool throwError = false, bool logWarningInsteadOfError = false, bool logDebugInsteadOfError = false, bool isSilent = false) + public static void TryCatchWithLoggingException(Action action, string errorMessage, bool throwError = false, bool logWarningInsteadOfError = false, bool logDebugInsteadOfError = false, bool isSilent = false) { if (action == null) return; - var success = try_catch_with_logging_exception( + var success = TryCatchWithLoggingException( () => { action.Invoke(); @@ -156,7 +156,7 @@ public static void try_catch_with_logging_exception(Action action, string errorM /// <param name="logDebugInsteadOfError">Log to debug</param> /// <param name="isSilent">Log messages?</param> /// <returns>The return value from the function</returns> - public static T try_catch_with_logging_exception<T>(Func<T> function, string errorMessage, bool throwError = false, bool logWarningInsteadOfError = false, bool logDebugInsteadOfError = false, bool isSilent = false) + public static T TryCatchWithLoggingException<T>(Func<T> function, string errorMessage, bool throwError = false, bool logWarningInsteadOfError = false, bool logDebugInsteadOfError = false, bool isSilent = false) { if (function == null) return default(T); var returnValue = default(T); @@ -170,19 +170,19 @@ public static T try_catch_with_logging_exception<T>(Func<T> function, string err } catch (Exception ex) { - var exceptionMessage = log_is_in_debug_mode() ? ex.ToString() : ex.Message; + var exceptionMessage = InDebugMode() ? ex.ToString() : ex.Message; if (logDebugInsteadOfError) { - "chocolatey".Log().Debug(logLocation, "{0}:{1} {2}".format_with(errorMessage, Environment.NewLine, exceptionMessage)); + "chocolatey".Log().Debug(logLocation, "{0}:{1} {2}".FormatWith(errorMessage, Environment.NewLine, exceptionMessage)); } else if (logWarningInsteadOfError) { - "chocolatey".Log().Warn(logLocation, "{0}:{1} {2}".format_with(errorMessage, Environment.NewLine, exceptionMessage)); + "chocolatey".Log().Warn(logLocation, "{0}:{1} {2}".FormatWith(errorMessage, Environment.NewLine, exceptionMessage)); } else { - "chocolatey".Log().Error(logLocation, "{0}:{1} {2}".format_with(errorMessage, Environment.NewLine, exceptionMessage)); + "chocolatey".Log().Error(logLocation, "{0}:{1} {2}".FormatWith(errorMessage, Environment.NewLine, exceptionMessage)); } if (throwError) @@ -193,5 +193,23 @@ public static T try_catch_with_logging_exception<T>(Func<T> function, string err return returnValue; } + +#pragma warning disable IDE1006 + [Obsolete("This overload is deprecated and will be removed in v3.")] + public static void retry(int numberOfTries, Action action, int waitDurationMilliseconds = 100, int increaseRetryByMilliseconds = 0, bool isSilent = false) + => Retry(numberOfTries, action, waitDurationMilliseconds, increaseRetryByMilliseconds, isSilent); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public static T retry<T>(int numberOfTries, Func<T> function, int waitDurationMilliseconds = 100, int increaseRetryByMilliseconds = 0, bool isSilent = false) + => Retry(numberOfTries, function, waitDurationMilliseconds, increaseRetryByMilliseconds, isSilent); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public static void try_catch_with_logging_exception(Action action, string errorMessage, bool throwError = false, bool logWarningInsteadOfError = false, bool logDebugInsteadOfError = false, bool isSilent = false) + => TryCatchWithLoggingException(action, errorMessage, throwError, logWarningInsteadOfError, logDebugInsteadOfError, isSilent); + + [Obsolete("This overload is deprecated and will be removed in v3.")] + public static T try_catch_with_logging_exception<T>(Func<T> function, string errorMessage, bool throwError = false, bool logWarningInsteadOfError = false, bool logDebugInsteadOfError = false, bool isSilent = false) + => TryCatchWithLoggingException(function, errorMessage, throwError, logWarningInsteadOfError, logDebugInsteadOfError, isSilent); +#pragma warning restore IDE1006 } } diff --git a/src/chocolatey/infrastructure/validations/IValidation.cs b/src/chocolatey/infrastructure/validations/IValidation.cs index c0aab571e8..3694d7fcaf 100644 --- a/src/chocolatey/infrastructure/validations/IValidation.cs +++ b/src/chocolatey/infrastructure/validations/IValidation.cs @@ -16,6 +16,7 @@ namespace chocolatey.infrastructure.validations { + using System; using System.Collections.Generic; using app.configuration; using chocolatey.infrastructure.app.attributes; @@ -31,6 +32,11 @@ public interface IValidation /// </summary> /// <param name="config">The current Chocolatey Configuration</param> /// <returns>The validation results</returns> + ICollection<ValidationResult> Validate(ChocolateyConfiguration config); + +#pragma warning disable IDE1006 + [Obsolete("This overload is deprecated and will be removed in v3.")] ICollection<ValidationResult> validate(ChocolateyConfiguration config); +#pragma warning restore IDE1006 } } diff --git a/src/chocolatey/infrastructure/xml/XmlCData.cs b/src/chocolatey/infrastructure/xml/XmlCData.cs index 08fcab75be..209ec843d0 100644 --- a/src/chocolatey/infrastructure/xml/XmlCData.cs +++ b/src/chocolatey/infrastructure/xml/XmlCData.cs @@ -49,7 +49,7 @@ public static implicit operator XmlCData(string value) /// <returns></returns> public static implicit operator string(XmlCData cdata) { - if (cdata != null) return cdata._value.to_string(); + if (cdata != null) return cdata._value.ToStringSafe(); return string.Empty; } @@ -65,7 +65,7 @@ public XmlCData(string value) public override string ToString() { - return _value.to_string(); + return _value.ToStringSafe(); } public XmlSchema GetSchema() diff --git a/src/chocolatey/packages.config b/src/chocolatey/packages.config index 8a1040e80d..116418dd7f 100644 --- a/src/chocolatey/packages.config +++ b/src/chocolatey/packages.config @@ -1,19 +1,19 @@ <?xml version="1.0" encoding="utf-8"?> <packages> <package id="AlphaFS" version="2.1.3" targetFramework="net40-Client" /> - <package id="Chocolatey.NuGet.Commands" version="3.0.0-alpha-20230315-204" targetFramework="net48" /> - <package id="Chocolatey.NuGet.Common" version="3.0.0-alpha-20230315-204" targetFramework="net48" /> - <package id="Chocolatey.NuGet.Configuration" version="3.0.0-alpha-20230315-204" targetFramework="net48" /> - <package id="Chocolatey.NuGet.Credentials" version="3.0.0-alpha-20230315-204" targetFramework="net48" /> - <package id="Chocolatey.NuGet.DependencyResolver.Core" version="3.0.0-alpha-20230315-204" targetFramework="net48" /> - <package id="Chocolatey.NuGet.Frameworks" version="3.0.0-alpha-20230315-204" targetFramework="net48" /> - <package id="Chocolatey.NuGet.LibraryModel" version="3.0.0-alpha-20230315-204" targetFramework="net48" /> - <package id="Chocolatey.NuGet.PackageManagement" version="3.0.0-alpha-20230315-204" targetFramework="net48" /> - <package id="Chocolatey.NuGet.Packaging" version="3.0.0-alpha-20230315-204" targetFramework="net48" /> - <package id="Chocolatey.NuGet.ProjectModel" version="3.0.0-alpha-20230315-204" targetFramework="net48" /> - <package id="Chocolatey.NuGet.Protocol" version="3.0.0-alpha-20230315-204" targetFramework="net48" /> - <package id="Chocolatey.NuGet.Resolver" version="3.0.0-alpha-20230315-204" targetFramework="net48" /> - <package id="Chocolatey.NuGet.Versioning" version="3.0.0-alpha-20230315-204" targetFramework="net48" /> + <package id="Chocolatey.NuGet.Commands" version="3.1.0" targetFramework="net48" /> + <package id="Chocolatey.NuGet.Common" version="3.1.0" targetFramework="net48" /> + <package id="Chocolatey.NuGet.Configuration" version="3.1.0" targetFramework="net48" /> + <package id="Chocolatey.NuGet.Credentials" version="3.1.0" targetFramework="net48" /> + <package id="Chocolatey.NuGet.DependencyResolver.Core" version="3.1.0" targetFramework="net48" /> + <package id="Chocolatey.NuGet.Frameworks" version="3.1.0" targetFramework="net48" /> + <package id="Chocolatey.NuGet.LibraryModel" version="3.1.0" targetFramework="net48" /> + <package id="Chocolatey.NuGet.PackageManagement" version="3.1.0" targetFramework="net48" /> + <package id="Chocolatey.NuGet.Packaging" version="3.1.0" targetFramework="net48" /> + <package id="Chocolatey.NuGet.ProjectModel" version="3.1.0" targetFramework="net48" /> + <package id="Chocolatey.NuGet.Protocol" version="3.1.0" targetFramework="net48" /> + <package id="Chocolatey.NuGet.Resolver" version="3.1.0" targetFramework="net48" /> + <package id="Chocolatey.NuGet.Versioning" version="3.1.0" targetFramework="net48" /> <package id="log4net" version="2.0.12" targetFramework="net48" /> <package id="Microsoft.Bcl.HashCode" version="1.1.1" targetFramework="net48" /> <package id="Microsoft.CodeAnalysis.BannedApiAnalyzers" version="3.3.3" targetFramework="net48" developmentDependency="true" /> diff --git a/tests/Vagrantfile b/tests/Vagrantfile index 0fbca632d2..83adfb6231 100644 --- a/tests/Vagrantfile +++ b/tests/Vagrantfile @@ -22,9 +22,9 @@ Vagrant.configure("2") do |config| config.vm.network :forwarded_port, guest: 3389, host: 14389, id: 'rdp', auto_correct: true config.vm.provider "virtualbox" do |vb| - vb.gui = true - vb.memory = 4096 - vb.cpus = 2 + vb.gui = ENV['VM_GUI'] ? ENV['VM_GUI'].to_s.downcase == 'true' : true + vb.memory = ENV['VM_MEMORY'] ? ENV['VM_MEMORY'].to_i : 4096 + vb.cpus = ENV['VM_CPU'] ? ENV['VM_CPU'].to_i : 2 vb.linked_clone = true vb.customize ['modifyvm', :id, '--vram', '128'] end @@ -37,30 +37,39 @@ Vagrant.configure("2") do |config| config.vm.synced_folder '../', '/chocoRoot' - config.vm.provision "shell", inline: <<-SHELL + config.vm.provision "shell", name: "prep", inline: <<-SHELL cscript c:/windows/system32/slmgr.vbs /rearm | Out-Null Set-ExecutionPolicy Bypass -Scope Process -Force - [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor 3072 - iex ((New-Object System.Net.WebClient).DownloadString('https://community.chocolatey.org/install.ps1')) + iex (irm https://community.chocolatey.org/install.ps1) - Write-Host "We are going to install some prerequisites now. This could take some time" + Write-Host "($(Get-Date -Format "dddd MM/dd/yyyy HH:mm:ss K")) We are going to install some prerequisites now. This could take some time" $null = choco install git pester visualstudio2022community visualstudio2022-workload-manageddesktop netfx-4.8-devpack -y Import-Module $env:ChocolateyInstall/helpers/chocolateyProfile.psm1 Update-SessionEnvironment - Write-Host "Done installing software, now copying files" - $null = robocopy c:/chocoRoot c:/code/choco /mir + Write-Host "($(Get-Date -Format "dddd MM/dd/yyyy HH:mm:ss K")) Done installing software, now copying files" + # If you try to build on macOS, then run this, there are attributes on some files that cause the build to fail inside of the vagrant environment. + $null = robocopy c:/chocoRoot c:/code/choco /e /copy:dt + SHELL + config.vm.provision "shell", name: "build", inline: <<-SHELL + $null = robocopy c:/chocoRoot c:/code/choco /e /copy:dt /purge Push-Location c:/code/choco - Write-Host "Files have been copied, beginning build process." + Write-Host "($(Get-Date -Format "dddd MM/dd/yyyy HH:mm:ss K")) Files have been copied, beginning build process." $CakeOutput = ./build.bat 2>&1 + if ($LastExitCode -ne 0) { - Set-Content c:/chocoRoot/buildOutput.txt -Value $CakeOutput - Write-Host "The build has failed. Please see the buildOutput.txt file at the root of the repository for details" - exit $LastExitCode + Set-Content c:/vagrant/buildOutput.log -Value $CakeOutput + Write-Host "The build has failed. Please see the buildOutput.log file for details" + exit $LastExitCode } - Write-Host "Build complete. Executing tests." + Write-Host "($(Get-Date -Format "dddd MM/dd/yyyy HH:mm:ss K")) Build complete." + SHELL + config.vm.provision "shell", name: "test", inline: <<-SHELL + Write-Host "($(Get-Date -Format "dddd MM/dd/yyyy HH:mm:ss K")) Starting Test Execution" + Push-Location c:/code/choco # $env:TEST_KITCHEN = 1 $env:VM_RUNNING = 1 ./Invoke-Tests.ps1 + Copy-Item $env:ALLUSERSPROFILE/chocolatey/logs/testInvocations.log C:/vagrant SHELL end diff --git a/tests/chocolatey-tests/chocolatey.Tests.ps1 b/tests/chocolatey-tests/chocolatey.Tests.ps1 index 61bd1a6ddb..3e73940b1d 100644 --- a/tests/chocolatey-tests/chocolatey.Tests.ps1 +++ b/tests/chocolatey-tests/chocolatey.Tests.ps1 @@ -1,4 +1,4 @@ -Import-Module helpers/common-helpers +Import-Module helpers/common-helpers Describe "Ensuring Chocolatey is correctly installed" -Tag Environment, Chocolatey { BeforeDiscovery { @@ -146,9 +146,9 @@ Describe "Ensuring Chocolatey is correctly installed" -Tag Environment, Chocolat # This is FossOnly for now as there are some undetermined errors here that do not seem to present inside of Chocolatey. https://gitlab.com/chocolatey/build-automation/chocolatey-test-kitchen/-/issues/39 It "Should be able to run the script in AllSigned mode" -Skip:($_ -notin $PowerShellFiles) -Tag FossOnly { $expectedErrors = 0 - $command = "Import-Module $FileUnderTest -ErrorAction SilentlyContinue; exit `$error.count" - & powershell.exe -noprofile -ExecutionPolicy AllSigned -command $command 2>$null - $LastExitCode | Should -BeExactly $expectedErrors + $command = "try { `$ErrorActionPreference = 'Stop'; Import-Module $FileUnderTest } catch { $_ ; exit 1 }" + $result = & powershell.exe -noprofile -ExecutionPolicy AllSigned -command $command *>&1 + $LastExitCode | Should -BeExactly $expectedErrors -Because $result } } @@ -182,15 +182,55 @@ Describe "Ensuring Chocolatey is correctly installed" -Tag Environment, Chocolat # This is Foss only as PowerShell running under version 2 doesn't have .net available and can't import the Licensed DLL. # Tests on Windows 7 show no issues with running Chocolatey under Windows 7 with PowerShell v2 aside from issues surrounding TLS versions that we cannot resolve without an upgrade to Windows 7. It "Imports ChocolateyInstaller module successfully in PowerShell v2" -Tag FossOnly { - $command = 'Import-Module $env:ChocolateyInstall\helpers\chocolateyInstaller.psm1;exit $error.count' - & powershell.exe -Version 2 -noprofile -command $command - $LastExitCode | Should -BeExactly 0 + $command = 'try { $ErrorActionPreference = ''Stop''; Import-Module $env:ChocolateyInstall\helpers\chocolateyInstaller.psm1 } catch { $_ ; exit 1 }' + $result = & powershell.exe -Version 2 -noprofile -command $command + $LastExitCode | Should -BeExactly 0 -Because $result } It "Imports ChocolateyProfile module successfully in PowerShell v2" { - $command = 'Import-Module $env:ChocolateyInstall\helpers\chocolateyProfile.psm1;exit $error.count' - & powershell.exe -Version 2 -noprofile -command $command - $LastExitCode | Should -BeExactly 0 + $command = 'try { $ErrorActionPreference = ''Stop''; Import-Module $env:ChocolateyInstall\helpers\chocolateyProfile.psm1 } catch { $_ ; exit 1 }' + $result = & powershell.exe -Version 2 -noprofile -command $command + $LastExitCode | Should -BeExactly 0 -Because $result + } + + Context "chocolateyScriptRunner.ps1" { + BeforeAll { + $Command = @' +& "$env:ChocolateyInstall\helpers\chocolateyScriptRunner.ps1" -packageScript '{0}' -installArguments '' -packageParameters '' -preRunHookScripts '{1}' -postRunHookScripts '{2}' +exit $error.count +'@ + 'Write-Host "packageScript"' > packageScript.ps1 + 'Write-Host "preRunHookScript"' > preRunHookScript.ps1 + 'Write-Host "postRunHookScript"' > postRunHookScript.ps1 + } + + It "Handles just a packageScript" { + $commandToExecute = $Command -f "$PWD/packageScript.ps1", $null, $null + $output = & powershell.exe -Version 2 -noprofile -command $commandToExecute + $LastExitCode | Should -BeExactly 0 -Because ($output -join ([Environment]::NewLine)) + $output | Should -Be @('packageScript') -Because ($output -join ([Environment]::NewLine)) + } + + It "Handles a packageScript with a preRunHookScript" { + $commandToExecute = $Command -f "$PWD/packageScript.ps1", "$PWD/preRunHookScript.ps1", $null + $output = & powershell.exe -Version 2 -noprofile -command $commandToExecute + $LastExitCode | Should -BeExactly 0 -Because ($output -join ([Environment]::NewLine)) + $output | Should -Be @('preRunHookScript','packageScript') -Because ($output -join ([Environment]::NewLine)) + } + + It "Handles a packageScript with a preRunHookScript and postRunHookScript" { + $commandToExecute = $Command -f "$PWD/packageScript.ps1", "$PWD/preRunHookScript.ps1", "$PWD/postRunHookScript.ps1" + $output = & powershell.exe -Version 2 -noprofile -command $commandToExecute + $LastExitCode | Should -BeExactly 0 -Because ($output -join ([Environment]::NewLine)) + $output | Should -Be @('preRunHookScript','packageScript', 'postRunHookScript') -Because ($output -join ([Environment]::NewLine)) + } + + It "Handles a packageScript with and postRunHookScript" { + $commandToExecute = $Command -f "$PWD/packageScript.ps1", $null, "$PWD/postRunHookScript.ps1" + $output = & powershell.exe -Version 2 -noprofile -command $commandToExecute + $LastExitCode | Should -BeExactly 0 -Because ($output -join ([Environment]::NewLine)) + $output | Should -Be @('packageScript', 'postRunHookScript') -Because ($output -join ([Environment]::NewLine)) + } } } @@ -404,4 +444,29 @@ Describe "Ensuring Chocolatey is correctly installed" -Tag Environment, Chocolat $Output.Lines | Should -Contain '.NET 4.8 is not installed or may need a reboot to complete installation.' } } + + + Context 'Chocolatey lib directory missing' { + BeforeAll { + New-ChocolateyInstallSnapshot + Remove-Item -Path $env:ChocolateyInstall/lib/ -Recurse -Force + $Output = Invoke-Choco list + } + + AfterAll { + Remove-ChocolateyInstallSnapshot + } + + It 'Exits with success (0)' { + $Output.ExitCode | Should -Be 0 -Because $Output.String + } + + It 'Emits a warning about the missing directory' { + $Output.Lines | Should -Contain "Directory '$($env:ChocolateyInstall)\lib' does not exist." -Because $Output.String + } + + It 'Does not emit a NuGet error for the missing directory and fall over' { + $Output.Lines | Should -Not -Contain "The path '$($env:ChocolateyInstall)\lib' for the selected source could not be resolved." + } + } } diff --git a/tests/chocolatey-tests/chocolateyProfile.Tests.ps1 b/tests/chocolatey-tests/chocolateyProfile.Tests.ps1 index 862188693e..c9fbf31b92 100644 --- a/tests/chocolatey-tests/chocolateyProfile.Tests.ps1 +++ b/tests/chocolatey-tests/chocolateyProfile.Tests.ps1 @@ -19,22 +19,33 @@ Describe "Chocolatey Profile" -Tag Chocolatey, Profile, Environment { [bool]((Get-Command TabExpansion).ScriptBlock -match "ChocolateyTabExpansion") | Should -BeTrue } - It "Should list completions for Top Level Commands" { + It "Should list completions for all Top Level Commands, sorted alphabetically, but not aliases or unpackself" { $Command = "choco " $Completions = (TabExpansion2 -inputScript $Command -cursorColumn $Command.Length).CompletionMatches.CompletionText - # These should be first - $Completions[0] | Should -Be "-?" - $Completions[1] | Should -Be "search" - - # TODO: Determine why these lines are commented out. Remove if not needed, get working otherwise. - <# Completions don't contain aliases, etc - foreach ($Command in $( - $(choco --help) -match " \* (?<Command>\w+) -" -replace " \* (?<Command>\w+) -.+", '$1' - )) { - $Completions | Should -Contain $Command - } - #> + $sortedCompletions = $Completions | Sort-Object -Property { $_ -replace '[^a-z](.*$)', '$1--' } + $differences = Compare-Object -ReferenceObject $sortedCompletions -DifferenceObject $Completions -SyncWindow 0 + $differences | Should -BeNullOrEmpty -Because ($differences | Format-Table | Out-String) + + # These are not provided by tab completion as they are either command aliases or not intended to be used + # by end-users. + $missingFromTabCompletion = @( + 'features' + 'find' + 'setapikey' + 'sources' + 'synchronize' + 'templates' + 'unpackself' + ) + + # Fail the test if any choco command listed by `choco --help` isn't either in the missing list or the + # tab completion. + $unaccountedForCommands = @(choco --help) -match " \* \w+ -" -replace " \* (?<Command>\w+) -.+", '${Command}' | + Where-Object { $_ -notin $missingFromTabCompletion } | + Where-Object { $_ -notin $Completions } + + $unaccountedForCommands | Should -HaveCount 0 -Because "expected all un-excluded commands to be present in tab completion, but the following were missing: $($unaccountedForCommands -join ', ')" } It "Should list completions for Pin" { diff --git a/tests/chocolatey-tests/commands/choco-config.Tests.ps1 b/tests/chocolatey-tests/commands/choco-config.Tests.ps1 index 4e6282f858..59918886ea 100644 --- a/tests/chocolatey-tests/commands/choco-config.Tests.ps1 +++ b/tests/chocolatey-tests/commands/choco-config.Tests.ps1 @@ -69,10 +69,6 @@ Describe "choco config" -Tag Chocolatey, ConfigCommand { $Output.Lines | Should -Contain $expectedLicenseHeader } - It "Displays Settings section" { - $Output.Lines | Should -Contain "Settings" - } - It "Does not display Sources section" { $Output.Lines | Should -Not -Contain "Sources" } @@ -86,19 +82,19 @@ Describe "choco config" -Tag Chocolatey, ConfigCommand { } It "Displays Available Setting <_>" -ForEach @( - "cacheLocation = |" - "containsLegacyPackageInstalls = true |" - "commandExecutionTimeoutSeconds = 2700 |" - "proxy = |" - "proxyUser = |" - "proxyPassword = |" - "webRequestTimeoutSeconds = 30 |" - "proxyBypassList = |" - "proxyBypassOnLocal = true |" - "upgradeAllExceptions = |" - "defaultTemplateName = |" + "cacheLocation = \|" + "containsLegacyPackageInstalls = true \|" + "commandExecutionTimeoutSeconds = 2700 \|" + "proxy = [^|]* \|" + "proxyUser = [^|]* \|" + "proxyPassword = [^|]* \|" + "webRequestTimeoutSeconds = 30 \|" + "proxyBypassList = \|" + "proxyBypassOnLocal = true \|" + "upgradeAllExceptions = \|" + "defaultTemplateName = \|" ) { - $Output.String | Should -MatchExactly ([Regex]::Escape($_)) + $Output.String | Should -MatchExactly $_ } } diff --git a/tests/chocolatey-tests/commands/choco-feature.Tests.ps1 b/tests/chocolatey-tests/commands/choco-feature.Tests.ps1 index 150eef7b1a..8f56cd1439 100644 --- a/tests/chocolatey-tests/commands/choco-feature.Tests.ps1 +++ b/tests/chocolatey-tests/commands/choco-feature.Tests.ps1 @@ -19,6 +19,9 @@ Describe "choco <_>" -ForEach $Command -Tag Chocolatey, FeatureCommand { Initialize-ChocolateyTestInstall New-ChocolateyInstallSnapshot + + $InitialConfiguration = ([xml](Get-Content $env:ChocolateyInstall\config\chocolatey.config)).chocolatey + $expectedLicenseHeader = Get-ExpectedChocolateyHeader } AfterAll { @@ -214,6 +217,58 @@ Describe "choco <_>" -ForEach $Command -Tag Chocolatey, FeatureCommand { } } + Context "Getting a feature (<_.Name>)" -ForEach $CurrentFeatures { + BeforeAll { + $Output = Invoke-Choco feature get $_.Name + } + + It "Exits with Success (0)" { + $Output.ExitCode | Should -Be 0 -Because $Output.String + } + + It "Displays chocolatey name with version" { + $Output.Lines | Should -Contain $expectedLicenseHeader + } + + It "Displays value of feature" { + $expectedResult = If ($InitialConfiguration.SelectSingleNode("//features/feature[@name='$($_.Name)']").enabled -eq "true" ) { "Enabled" } Else { "Disabled" } + $Output.Lines | Should -Contain $expectedResult -Because $Output.String + } + } + + Context "Getting a feature by argument (<_.Name>)" -ForEach $CurrentFeatures { + BeforeAll { + $Output = Invoke-Choco feature get --name $_.Name + } + + It "Exits with Success (0)" { + $Output.ExitCode | Should -Be 0 -Because $Output.String + } + + It "Displays chocolatey name with version" { + $Output.Lines | Should -Contain $expectedLicenseHeader + } + + It "Displays value of feature" { + $expectedResult = If ($InitialConfiguration.SelectSingleNode("//features/feature[@name='$($_.Name)']").enabled -eq "true" ) { "Enabled" } Else { "Disabled" } + $Output.Lines | Should -Contain $expectedResult -Because $Output.String + } + } + + Context "Getting a feature that doesn't exist" { + BeforeAll { + $Output = Invoke-Choco feature get noFeatureValue + } + + It "Exits with failure (1)" { + $Output.ExitCode | Should -Be 1 -Because $Output.String + } + + It "Outputs an error indicating that there's no feature by that name" { + $Output.Lines | Should -Contain "No feature value by the name 'noFeatureValue'" + } + } + # This needs to be the last test in this block, to ensure NuGet configurations aren't being created. Test-NuGetPaths } diff --git a/tests/chocolatey-tests/commands/choco-help.Tests.ps1 b/tests/chocolatey-tests/commands/choco-help.Tests.ps1 index 46dd6a8761..68f854ec2f 100644 --- a/tests/chocolatey-tests/commands/choco-help.Tests.ps1 +++ b/tests/chocolatey-tests/commands/choco-help.Tests.ps1 @@ -1,6 +1,6 @@ param( # Which help command to test - [string[]]$Command = @( + [string[]]$HelpOptions = @( "--help" "-?" "-help" @@ -9,19 +9,17 @@ # Commands that don't have full help [string[]]$SkipCommand = @( "unpackself" # Out of spec - "version" # Deprecated - "update" # Deprecated "support" # This should be tested separately ) ) Import-Module helpers/common-helpers BeforeDiscovery { - $AllTopLevelCommands = (Invoke-Choco $Command[0]).Lines -match " \* (?<Command>\w+) -" -replace " \* (?<Command>\w+) -.+", '$1' + $AllTopLevelCommands = (Invoke-Choco $HelpOptions[0]).Lines -match "\* (?<Command>\w+) -" -replace "\* (?<Command>\w+) -.+", '${Command}' $TopLevelCommands = $AllTopLevelCommands.Where{ $_ -notin $SkipCommand } } -Describe "choco help sections with command <_>" -ForEach $Command -Tag Chocolatey, HelpCommand { +Describe "choco help sections with option <_>" -ForEach $HelpOptions -Tag Chocolatey, HelpCommand { BeforeDiscovery { $helpArgument = $_ } @@ -30,7 +28,9 @@ Describe "choco help sections with command <_>" -ForEach $Command -Tag Chocolate Remove-NuGetPaths $helpArgument = $_ Initialize-ChocolateyTestInstall - New-ChocolateyInstallSnapshot + + # We're just testing help output here, we don't need to copy config/package files + New-ChocolateyInstallSnapshot -NoSnapshotCopy } AfterAll { @@ -39,7 +39,7 @@ Describe "choco help sections with command <_>" -ForEach $Command -Tag Chocolate Context "Top Level Help" { BeforeAll { - $Output = Invoke-Choco $_ $helpArgument + $Output = Invoke-Choco $_ } It "Exits with Success (0)" { diff --git a/tests/chocolatey-tests/commands/choco-info.Tests.ps1 b/tests/chocolatey-tests/commands/choco-info.Tests.ps1 index 7fc0a27afd..bc3eaa1a47 100644 --- a/tests/chocolatey-tests/commands/choco-info.Tests.ps1 +++ b/tests/chocolatey-tests/commands/choco-info.Tests.ps1 @@ -1,11 +1,10 @@ -Import-Module helpers/common-helpers - -Describe "choco info" -Tag Chocolatey, InfoCommand { +Describe "choco info" -Tag Chocolatey, InfoCommand { BeforeDiscovery { $licensedProxyFixed = Test-PackageIsEqualOrHigher 'chocolatey.extension' 2.2.0-beta -AllowMissingPackage } BeforeAll { + Remove-NuGetPaths Initialize-ChocolateyTestInstall } @@ -23,13 +22,12 @@ Describe "choco info" -Tag Chocolatey, InfoCommand { } BeforeAll { - Remove-NuGetPaths $Output = Invoke-Choco info mvcmusicstore-web $Output.Lines = $Output.Lines } It "Exits with Success (0)" { - $Output.ExitCode | Should -Be 0 + $Output.ExitCode | Should -Be 0 -Because $Output.String } It "Displays <Title> with value <Value>" -ForEach $infoItems { @@ -72,7 +70,7 @@ Describe "choco info" -Tag Chocolatey, InfoCommand { } It "Exists with Failure (<ExitCode>)" { - $Output.ExitCode | Should -Be $ExitCode + $Output.ExitCode | Should -Be $ExitCode -Because $Output.String } It "Displays no packages could be found" { @@ -80,8 +78,37 @@ Describe "choco info" -Tag Chocolatey, InfoCommand { } } + Context "Listing package information when more than one package ID is provided" { + BeforeAll { + $Output = Invoke-Choco info foo bar + } + + It "Exits with Failure (1)" { + $Output.ExitCode | Should -Be 1 -Because $Output.String + } + + It "Reports a package ID is required" { + $Output.Lines | Should -Contain 'Only a single package name can be passed to the choco info command.' + } + } + + Context "Listing package information when no package ID is provided" { + BeforeAll { + $Output = Invoke-Choco info + } + + It "Exits with Failure (1)" { + $Output.ExitCode | Should -Be 1 -Because $Output.String + } + + It "Reports a package ID is required" { + $Output.Lines | Should -Contain 'A single package name is required to run the choco info command.' + } + } + # Issue: https://gitlab.com/chocolatey/collaborators/choco-licensed/-/issues/530 (NOTE: Proxy bypassing also works on Chocolatey FOSS) - Context "Listing package information when using proxy and proxy bypass list in config" -Skip:(!$licensedProxyFixed) { + # These are skipped on Proxy tests because the proxy server can't be bypassed in that test environment. + Context "Listing package information when using proxy and proxy bypass list in config" -Tag ProxySkip -Skip:(!$licensedProxyFixed) { BeforeDiscovery { $infoItems = @( @{ Title = "Tags"; Value = "mvcmusicstore db" } @@ -101,7 +128,7 @@ Describe "choco info" -Tag Chocolatey, InfoCommand { } It "Exits with Success (0)" { - $Output.ExitCode | Should -Be 0 + $Output.ExitCode | Should -Be 0 -Because $Output.String } It "Displays the package mvcmusicstore-db 1.2.0" { @@ -114,7 +141,8 @@ Describe "choco info" -Tag Chocolatey, InfoCommand { } # Issue: https://gitlab.com/chocolatey/collaborators/choco-licensed/-/issues/530 (NOTE: Proxy bypassing also works on Chocolatey FOSS) - Context "Listing package information when using proxy and proxy bypass list on command" -Skip:(!$licensedProxyFixed) { + # These are skipped on Proxy tests because the proxy server can't be bypassed in that test environment. + Context "Listing package information when using proxy and proxy bypass list on command" -Tag ProxySkip -Skip:(!$licensedProxyFixed) { BeforeDiscovery { $infoItems = @( @{ Title = "Tags"; Value = "mvcmusicstore db" } @@ -133,7 +161,7 @@ Describe "choco info" -Tag Chocolatey, InfoCommand { } It "Exits with Success (0)" { - $Output.ExitCode | Should -Be 0 + $Output.ExitCode | Should -Be 0 -Because $Output.String } It "Displays the package mvcmusicstore-db 1.2.0" { @@ -145,6 +173,53 @@ Describe "choco info" -Tag Chocolatey, InfoCommand { } } + Context "Listing package information when invalid package source is being used" { + BeforeAll { + Restore-ChocolateyInstallSnapshot + $InvalidSource = "https://invalid.chocolatey.org/api/v2/" + $null = Invoke-Choco source add -n "invalid" -s $InvalidSource + + $Output = Invoke-Choco info chocolatey + } + + It 'Exits with Success (0)' { + $Output.ExitCode | Should -Be 0 -Because $Output.String + } + + It 'Outputs warning about unable to load service index' { + $Output.Lines | Should -Contain "Unable to load the service index for source $InvalidSource." + } + + It 'Output information about the package' { + $Output.String | Should -Match "Title: Chocolatey " + } + } + + Context "Listing package information for non-normalized exact package version" -ForEach @( + @{ ExpectedPackageVersion = '1.0.0' ; SearchVersion = '1' } + @{ ExpectedPackageVersion = '1.0.0' ; SearchVersion = '1.0' } + @{ ExpectedPackageVersion = '1.0.0' ; SearchVersion = '1.0.0' } + @{ ExpectedPackageVersion = '4.0.1' ; SearchVersion = '4.0.1' } + @{ ExpectedPackageVersion = '1.0.0' ; SearchVersion = '01.0.0.0' } + @{ ExpectedPackageVersion = '4.0.1' ; SearchVersion = '004.0.01.0' } + @{ ExpectedPackageVersion = '4.0.1' ; SearchVersion = '0000004.00000.00001.0000' } + ) -Tag VersionNormalization { + BeforeAll { + Restore-ChocolateyInstallSnapshot + $PackageUnderTest = 'nonnormalizedversions' + + $Output = Invoke-Choco info $PackageUnderTest --version $SearchVersion + } + + It "Should exit with success (0)" { + $Output.ExitCode | Should -Be 0 -Because $Output.String + } + + It "Should find and report the normalized package version" { + $Output.Lines | Should -Contain "$PackageUnderTest $ExpectedPackageVersion" -Because $Output.String + } + } + # This needs to be the last test in this block, to ensure NuGet configurations aren't being created. Test-NuGetPaths } diff --git a/tests/chocolatey-tests/commands/choco-install.Tests.ps1 b/tests/chocolatey-tests/commands/choco-install.Tests.ps1 index e31792ba4f..14190788b4 100644 --- a/tests/chocolatey-tests/commands/choco-install.Tests.ps1 +++ b/tests/chocolatey-tests/commands/choco-install.Tests.ps1 @@ -1,8 +1,4 @@ -Import-Module helpers/common-helpers - -# https://github.com/chocolatey/choco/blob/master/src/chocolatey.tests.integration/scenarios/InstallScenarios.cs - -Describe "choco install" -Tag Chocolatey, InstallCommand { +Describe "choco install" -Tag Chocolatey, InstallCommand { BeforeDiscovery { $isLicensed30OrMissingVersion = Test-PackageIsEqualOrHigher 'chocolatey.extension' '3.0.0-beta' -AllowMissingPackage $licensedProxyFixed = Test-PackageIsEqualOrHigher 'chocolatey.extension' 2.2.0-beta -AllowMissingPackage @@ -35,7 +31,7 @@ Describe "choco install" -Tag Chocolatey, InstallCommand { } It "Exits with Success (0)" { - $Output.ExitCode | Should -Be 0 + $Output.ExitCode | Should -Be 0 -Because $Output.String } It "Doesn't install the package to the lib directory" { @@ -65,7 +61,7 @@ Describe "choco install" -Tag Chocolatey, InstallCommand { } It "Exits with Success (0)" { - $Output.ExitCode | Should -Be 0 + $Output.ExitCode | Should -Be 0 -Because $Output.String } It "Doesn't install the package to the lib directory" { @@ -91,7 +87,7 @@ Describe "choco install" -Tag Chocolatey, InstallCommand { } It "Exits with Success (0)" { - $Output.ExitCode | Should -Be 0 + $Output.ExitCode | Should -Be 0 -Because $Output.String } It "Installed a package to the lib directory" { @@ -173,7 +169,7 @@ Describe "choco install" -Tag Chocolatey, InstallCommand { } It "Exits with Failure (1), due to the missing 'missingpackage'" { - $Output.ExitCode | Should -Be 1 + $Output.ExitCode | Should -Be 1 -Because $Output.String } It "Installs the package '<_>' in the Lib directory" -ForEach @("InstallPackage"; "HasDependency"; "IsDependency"; "UpgradePackage") { @@ -334,7 +330,7 @@ Describe "choco install" -Tag Chocolatey, InstallCommand { } It "Exits with Success (0)" { - $Output.ExitCode | Should -Be 0 + $Output.ExitCode | Should -Be 0 -Because $Output.String } It "Should still have a package in the lib directory" { @@ -371,7 +367,7 @@ Describe "choco install" -Tag Chocolatey, InstallCommand { } It "Exits with Success (0)" { - $Output.ExitCode | Should -Be 0 + $Output.ExitCode | Should -Be 0 -Because $Output.String } It "Should install the package in the lib directory" { @@ -410,7 +406,7 @@ Describe "choco install" -Tag Chocolatey, InstallCommand { } It "Exits with Success (0)" { - $Output.ExitCode | Should -Be 0 + $Output.ExitCode | Should -Be 0 -Because $Output.String } It "Should install the package in the lib directory" { @@ -436,6 +432,51 @@ Describe "choco install" -Tag Chocolatey, InstallCommand { } } + Context "Force Installing a Package that is already installed (with a delete locked file)" { + BeforeAll { + Restore-ChocolateyInstallSnapshot + + $PackageUnderTest = "installpackage" + + Invoke-Choco install $PackageUnderTest --confirm + + $LockedFile = [System.IO.File]::Open( + "$env:ChocolateyInstall\lib\$PackageUnderTest\tools\chocolateyInstall.ps1", + "OpenOrCreate", + "ReadWrite", + "Delete" + ) + + $Output = Invoke-Choco install installpackage --force --confirm + } + + AfterAll { + $LockedFile.Close() + } + + It "Exits with Success (0)" { + $Output.ExitCode | Should -Be 0 -Because $Output.String + } + + It "Has successfully retained an install of the original package" { + "$env:ChocolateyInstall\lib\$PackageUnderTest\" + } + + It "Has successfully retained the original version" { + "$env:ChocolateyInstall\lib\$PackageUnderTest\$PackageUnderTest.nuspec" | Should -Exist + [xml]$XML = Get-Content "$env:ChocolateyInstall\lib\$PackageUnderTest\$PackageUnderTest.nuspec" + $XML.package.metadata.version | Should -Be "1.0.0" + } + + It "Should not have been able to delete the rollback" { + "$env:ChocolateyInstall\lib-bkp\$PackageUnderTest" | Should -Exist + } + + It "Outputs a message showing that installation succeeded." { + $Output.String | Should -Match "Chocolatey installed 1/1 packages\." + } + } + Context "Force Installing a Package that is already installed (with a read/delete locked file)" { BeforeAll { Restore-ChocolateyInstallSnapshot @@ -459,7 +500,7 @@ Describe "choco install" -Tag Chocolatey, InstallCommand { } It "Exits with Success (0)" { - $Output.ExitCode | Should -Be 0 + $Output.ExitCode | Should -Be 0 -Because $Output.String } It "Has successfully retained an install of the original package" { @@ -482,22 +523,9 @@ Describe "choco install" -Tag Chocolatey, InstallCommand { } } - Context "Force Installing a Package that is already installed (with an exclusively locked file)" -Tag Broken { + Context "Force Installing a Package that is already installed (with an exclusively locked file)" { BeforeDiscovery { $PackageUnderTest = "installpackage" - $expectedFiles = @( - "$PackageUnderTest.nuspec" - "$PackageUnderTest.nupkg" - 'tools\casemismatch.exe' - 'tools\chocolateyinstall.ps1' - 'tools\chocolateyuninstall.ps1' - 'console.exe' - 'graphical.exe' - 'graphical.exe.gui' - 'not.installed.exe' - 'not.installed.exe.ignored' - 'simplefile.txt' - ) } BeforeAll { @@ -522,7 +550,7 @@ Describe "choco install" -Tag Chocolatey, InstallCommand { } It "Exits with Failure (1)" { - $Output.ExitCode | Should -Be 1 + $Output.ExitCode | Should -Be 1 -Because $Output.String } It "Has successfully retained an install of the original package" { @@ -535,27 +563,54 @@ Describe "choco install" -Tag Chocolatey, InstallCommand { $XML.package.metadata.version | Should -Be "1.0.0" } - It "Should not have been able to delete the rollback" -Tag Broken { - "$env:ChocolateyInstall\lib-bkp\$PackageUnderTest" | Should -Exist + It "Should have been able to delete the rollback" { + # It is important to know that the behavior may be different on different operating + # systems. It depends on how the operating system implements locking of files. + "$env:ChocolateyInstall\lib-bkp\$PackageUnderTest" | Should -Not -Exist } - It "Should have kept file in rollback folder (<_>)" -ForEach $expectedFiles { - "$env:ChocolateyInstall\lib-bkp\$_" | Should -Exist + It "Should have created the package in lib-bad" { + "$env:ChocolateyInstall\lib-bad\$PackageUnderTest" | Should -Exist } - It "Should have been able to delete the rollback" -Tag Licensed { - "$env:ChocolateyInstall\lib-bkp\$PackageUnderTest" | Should -Not -Exist + It "Should have stored pending file in bad folder" { + # Because the package itself fails to extract, due to the install script being locked. + # The only file in the original package that could be copied over is the pending file (can't copy the exclusively locked file either). + "$env:ChocolateyInstall\lib-bad\$PackageUnderTest\1.0.0\.chocolateyPending" | Should -Exist } - It "Should have created the package in lib-bad" { - "$env:ChocolateyInstall\lib-bad\$PackageUnderTest" | Should -Exist + It "Outputs a message showing that installation failed." { + $Output.String | Should -Match "Chocolatey installed 0/1 packages\." } + } - It "Should have stored file in bad folder (<_>)" -ForEach $expectedFiles { - "$env:ChocolateyInstall\lib-bad\$PackageUnderTest\$_" | Should -Exist + Context "Installing a failing package created backup in lib-bad" { + BeforeAll { + Restore-ChocolateyInstallSnapshot + + $PackageUnderTest = "failingdependency" + $PackageVersion = '0.9.9' + + $Output = Invoke-Choco install $PackageUnderTest --version $PackageVersion --confirm } - It "Outputs a message showing that installation succeeded." { + It "Exits with Failure (15608)" { + $Output.ExitCode | Should -Be 15608 -Because $Output.String + } + + It "Doesn't install the package to lib directory" { + "$env:ChocolateyInstall\lib\$PackageUnderTest" | Should -Not -Exist + } + + It "Doesn't keep a package backup in lib-bkp" { + "$env:ChocolateyInstall\lib-bkp\$PackageUnderTest" | Should -Not -Exist + } + + It "Creates backup of file '<_>' in lib-bad" -ForEach @('failingdependency.nupkg', 'failingdependency.nuspec', '.chocolateyPending', 'tools\chocolateyinstall.ps1', 'tools\test-file.txt') { + "$env:ChocolateyInstall\lib-bad\$PackageUnderTest\$PackageVersion\$_" | Should -Exist + } + + It "Outputs a message showing that installation failed." { $Output.String | Should -Match "Chocolatey installed 0/1 packages\." } } @@ -570,7 +625,7 @@ Describe "choco install" -Tag Chocolatey, InstallCommand { } It "Exits with Failure (1)" { - $Output.ExitCode | Should -Be 1 + $Output.ExitCode | Should -Be 1 -Because $Output.String } It "Doesn't install the package to the lib directory" { @@ -592,7 +647,7 @@ Describe "choco install" -Tag Chocolatey, InstallCommand { } It "Exits with Failure (1)" { - $Output.ExitCode | Should -Be 1 + $Output.ExitCode | Should -Be 1 -Because $Output.String } It "Doesn't install the package to the lib directory" { @@ -614,7 +669,7 @@ Describe "choco install" -Tag Chocolatey, InstallCommand { } It "Exits with Failure (-1)" { - $Output.ExitCode | Should -Be -1 + $Output.ExitCode | Should -Be -1 -Because $Output.String } It "Doesn't install the package to the lib directory" { @@ -642,7 +697,7 @@ Describe "choco install" -Tag Chocolatey, InstallCommand { } It "Exits with Success (0)" { - $Output.ExitCode | Should -Be 0 + $Output.ExitCode | Should -Be 0 -Because $Output.String } It "Installed a package to the lib directory" { @@ -672,7 +727,7 @@ Describe "choco install" -Tag Chocolatey, InstallCommand { } It "Exits with Failure (1)" { - $Output.ExitCode | Should -Be 1 + $Output.ExitCode | Should -Be 1 -Because $Output.String } It "Doesn't install the package to the lib directory" { @@ -698,7 +753,7 @@ Describe "choco install" -Tag Chocolatey, InstallCommand { } It "Exits with Success (0)" { - $Output.ExitCode | Should -Be 0 + $Output.ExitCode | Should -Be 0 -Because $Output.String } It "Installed the package to the lib directory" { @@ -732,7 +787,7 @@ Describe "choco install" -Tag Chocolatey, InstallCommand { } It "Exits with Success (0)" { - $Output.ExitCode | Should -Be 0 + $Output.ExitCode | Should -Be 0 -Because $Output.String } It "Installed the package to the lib directory" { @@ -771,7 +826,7 @@ Describe "choco install" -Tag Chocolatey, InstallCommand { } It "Exits with Success (0)" { - $Output.ExitCode | Should -Be 0 + $Output.ExitCode | Should -Be 0 -Because $Output.String } It "Installed the package to the lib directory" { @@ -821,7 +876,7 @@ Describe "choco install" -Tag Chocolatey, InstallCommand { } It "Exits with Success (0)" { - $Output.ExitCode | Should -Be 0 + $Output.ExitCode | Should -Be 0 -Because $Output.String } It "Installed the package to the lib directory" { @@ -870,7 +925,7 @@ Describe "choco install" -Tag Chocolatey, InstallCommand { } It "Exits with Success (0)" { - $Output.ExitCode | Should -Be 0 + $Output.ExitCode | Should -Be 0 -Because $Output.String } It "Installed the package to the lib directory" { @@ -908,7 +963,7 @@ Describe "choco install" -Tag Chocolatey, InstallCommand { } It "Exits with Failure (1)" { - $Output.ExitCode | Should -Be 1 + $Output.ExitCode | Should -Be 1 -Because $Output.String } It "Doesn't install the package to the lib directory" { @@ -934,7 +989,7 @@ Describe "choco install" -Tag Chocolatey, InstallCommand { } It "Exits with Success (0)" { - $Output.ExitCode | Should -Be 0 + $Output.ExitCode | Should -Be 0 -Because $Output.String } It "Has installed a package to the lib directory" { @@ -968,7 +1023,7 @@ Describe "choco install" -Tag Chocolatey, InstallCommand { } It "Exits with Success (0)" { - $Output.ExitCode | Should -Be 0 + $Output.ExitCode | Should -Be 0 -Because $Output.String } It "Installed the package to the lib directory" { @@ -1007,7 +1062,7 @@ Describe "choco install" -Tag Chocolatey, InstallCommand { } It "Exits with Failure (1)" { - $Output.ExitCode | Should -Be 1 + $Output.ExitCode | Should -Be 1 -Because $Output.String } It "Has not installed the package to the lib directory" { @@ -1030,7 +1085,7 @@ Describe "choco install" -Tag Chocolatey, InstallCommand { } It "Exits with Success (0)" { - $Output.ExitCode | Should -Be 0 + $Output.ExitCode | Should -Be 0 -Because $Output.String } It "Has installed the package to the lib directory" { @@ -1059,7 +1114,7 @@ Describe "choco install" -Tag Chocolatey, InstallCommand { } It "Exits with Failure (1)" { - $Output.ExitCode | Should -Be 1 + $Output.ExitCode | Should -Be 1 -Because $Output.String } It "Has not installed the package to the lib directory" { @@ -1098,7 +1153,7 @@ Describe "choco install" -Tag Chocolatey, InstallCommand { } It "Exits with Success (0)" { - $Output.ExitCode | Should -Be 0 + $Output.ExitCode | Should -Be 0 -Because $Output.String } It "Has installed the package to the lib directory" { @@ -1133,7 +1188,7 @@ Describe "choco install" -Tag Chocolatey, InstallCommand { } It "Exits with Failure (1)" { - $Output.ExitCode | Should -Be 1 + $Output.ExitCode | Should -Be 1 -Because $Output.String } It "Not Installed a package to the lib directory" { @@ -1167,7 +1222,7 @@ To install a local, or remote file, you may use: } It "Exits with Success (0)" { - $Output.ExitCode | Should -Be 0 + $Output.ExitCode | Should -Be 0 -Because $Output.String } It "Outputs a message showing that installation was successful" { @@ -1197,7 +1252,7 @@ To install a local, or remote file, you may use: } It "Exits with Failure (1)" { - $Output.ExitCode | Should -Be 1 + $Output.ExitCode | Should -Be 1 -Because $Output.String } It "Outputs a message indicating that there were no sources enabled" { @@ -1210,7 +1265,8 @@ To install a local, or remote file, you may use: } # Issue: https://gitlab.com/chocolatey/collaborators/choco-licensed/-/issues/530 (NOTE: Proxy bypassing also works on Chocolatey FOSS) - Context "Installing a Package with proxy and proxy bypass list" -Skip:(!$licensedProxyFixed) { + # These are skipped on Proxy tests because the proxy server can't be bypassed in that test environment. + Context "Installing a Package with proxy and proxy bypass list" -Tag ProxySkip -Skip:(!$licensedProxyFixed) { BeforeAll { Restore-ChocolateyInstallSnapshot $null = Invoke-Choco config set --name=proxy --value="https://invalid.chocolatey.org/" @@ -1220,7 +1276,7 @@ To install a local, or remote file, you may use: } It "Exits with Success (0)" { - $Output.ExitCode | Should -Be 0 + $Output.ExitCode | Should -Be 0 -Because $Output.String } It "Displays package files install completed" { @@ -1229,7 +1285,8 @@ To install a local, or remote file, you may use: } # Issue: https://gitlab.com/chocolatey/collaborators/choco-licensed/-/issues/530 (NOTE: Proxy bypassing also works on Chocolatey FOSS) - Context "Installing a Package with proxy and proxy bypass list on command" -Skip:(!$licensedProxyFixed) { + # These are skipped on Proxy tests because the proxy server can't be bypassed in that test environment. + Context "Installing a Package with proxy and proxy bypass list on command" -Tag ProxySkip -Skip:(!$licensedProxyFixed) { BeforeAll { Restore-ChocolateyInstallSnapshot $null = Invoke-Choco config set --name=proxy --value="https://invalid.chocolatey.org/" @@ -1238,7 +1295,7 @@ To install a local, or remote file, you may use: } It "Exits with Success (0)" { - $Output.ExitCode | Should -Be 0 + $Output.ExitCode | Should -Be 0 -Because $Output.String } It "Displays package files install completed" { @@ -1265,7 +1322,7 @@ To install a local, or remote file, you may use: } It "Exits with Success (0)" { - $Output.ExitCode | Should -Be 0 + $Output.ExitCode | Should -Be 0 -Because $Output.String } # TODO: Background service only works with Chocolatey Licensed Extension. Assess moving this test to CLE test suite @@ -1301,7 +1358,7 @@ To install a local, or remote file, you may use: } It "Exits with Success (0)" { - $Output.ExitCode | Should -Be 0 + $Output.ExitCode | Should -Be 0 -Because $Output.String } # TODO: Background service only works with Chocolatey Licensed Extension. Assess moving this test to CLE test suite @@ -1326,7 +1383,7 @@ To install a local, or remote file, you may use: } It "Exits with Failure (-1)" { - $Output.ExitCode | Should -Be -1 + $Output.ExitCode | Should -Be -1 -Because $Output.String } } @@ -1339,7 +1396,7 @@ To install a local, or remote file, you may use: } It "Exits with Failure (-1)" { - $Output.ExitCode | Should -Be -1 + $Output.ExitCode | Should -Be -1 -Because $Output.String } It "Outputs warning message about needing commercial edition" { @@ -1351,7 +1408,8 @@ To install a local, or remote file, you may use: } } - Context "Installing package with beforeInstall scriptblock defined" -Skip:(!$hasBeforeInstallBlock) { + # These are skipped in the Proxy Test environment because the beforeInstall reaches out to GitHub which is not permitted through our proxy. + Context "Installing package with beforeInstall scriptblock defined" -Tag ProxySkip -Skip:(!$hasBeforeInstallBlock) { BeforeAll { New-ChocolateyInstallSnapshot Remove-Item "$env:ChocolateyInstall\logs\*" -ErrorAction Ignore @@ -1360,7 +1418,7 @@ To install a local, or remote file, you may use: } It "Exits with Success (0)" { - $Output.ExitCode | Should -Be 0 + $Output.ExitCode | Should -Be 0 -Because $Output.String } It "Outputs string defined in before installation block" { @@ -1381,8 +1439,8 @@ To install a local, or remote file, you may use: } It "Exits with Failure (1)" { - $result1.ExitCode | Should -Be 1 - $result2.ExitCode | Should -Be 1 + $result1.ExitCode | Should -Be 1 -Because $result1.String + $result2.ExitCode | Should -Be 1 -Because $result2.String } It "should identify a circular dependency" { @@ -1430,7 +1488,7 @@ To install a local, or remote file, you may use: } It "Exits with Success (0)" { - $Output.ExitCode | Should -Be 0 + $Output.ExitCode | Should -Be 0 -Because $Output.String } It "Does not output extracted file path '<_>'" -ForEach @('tools\'; 'tools\chocolateybeforemodify.ps1'; 'tools\chocolateyinstall.ps1'; 'tools\chocolateyuninstall.ps1'; 'zip-log-disable-test.nuspec') { @@ -1446,7 +1504,7 @@ To install a local, or remote file, you may use: } It "Exits with Success (0)" { - $Output.ExitCode | Should -Be 0 + $Output.ExitCode | Should -Be 0 -Because $Output.String } It "Does not output extracted file path '<_>'" -ForEach @('tools\'; 'tools\chocolateybeforemodify.ps1'; 'tools\chocolateyinstall.ps1'; 'tools\chocolateyuninstall.ps1'; 'zip-log-disable-test.nuspec') { @@ -1486,7 +1544,7 @@ To install a local, or remote file, you may use: } It "Installs successfully and exits with success (0)" { - $Output.ExitCode | Should -Be 0 + $Output.ExitCode | Should -Be 0 -Because $Output.String } It "Installed the packages to the lib directory" { @@ -1578,7 +1636,7 @@ To install a local, or remote file, you may use: } It 'Exits with Success (0)' { - $Output.ExitCode | Should -Be 0 + $Output.ExitCode | Should -Be 0 -Because $Output.String } It 'Installs package to expected directory' { @@ -1604,7 +1662,7 @@ To install a local, or remote file, you may use: } It 'Exits with Success (0)' { - $Output.ExitCode | Should -Be 0 + $Output.ExitCode | Should -Be 0 -Because $Output.String } It 'Installs package to expected directory' { @@ -1630,7 +1688,7 @@ To install a local, or remote file, you may use: } It 'Exits with Success (0)' { - $Output.ExitCode | Should -Be 0 + $Output.ExitCode | Should -Be 0 -Because $Output.String } It 'Installs package to expected directory' { @@ -1656,7 +1714,7 @@ To install a local, or remote file, you may use: } It 'Exits with Success (0)' { - $Output.ExitCode | Should -Be 0 + $Output.ExitCode | Should -Be 0 -Because $Output.String } It 'Installs package to expected directory' { @@ -1674,6 +1732,80 @@ To install a local, or remote file, you may use: } } + Context "Installing a package when invalid package source is being used" { + BeforeAll { + Restore-ChocolateyInstallSnapshot + $InvalidSource = "https://invalid.chocolatey.org/api/v2/" + $null = Invoke-Choco source add -n "invalid" -s $InvalidSource + + $Output = Invoke-Choco install installpackage --confirm + } + + It 'Exits with Success (0)' { + $Output.ExitCode | Should -Be 0 -Because $Output.String + } + + It 'Outputs warning about unable to load service index' { + $Output.Lines | Should -Contain "Unable to load the service index for source $InvalidSource." + } + + It 'Outputs successful installation of single package' { + $Output.Lines | Should -Contain 'Chocolatey installed 1/1 packages.' + } + } + + Context "Installing a package when the user specifies a non-conforming casing of the id" { + BeforeAll { + Restore-ChocolateyInstallSnapshot + + $Output = Invoke-Choco install InstAlLpAckaGe --confirm + } + + It 'Exits with Success' { + $Output.ExitCode | Should -Be 0 -Because $Output.String + } + + It 'Outputs successful installation of single package' { + $Output.Lines | Should -Contain 'Chocolatey installed 1/1 packages.' -Because $Output.String + } + + It 'Installed package to expected location' { + "$env:ChocolateyInstall\lib\installpackage" | Should -Exist + } + } + + Context "Installing a package with a non-normalized version number" -ForEach @( + @{ ExpectedPackageVersion = '1.0.0' ; SearchVersion = '1' ; NuspecVersion = '01.0.0.0'} + @{ ExpectedPackageVersion = '1.0.0' ; SearchVersion = '1.0' ; NuspecVersion = '01.0.0.0'} + @{ ExpectedPackageVersion = '1.0.0' ; SearchVersion = '1.0.0' ; NuspecVersion = '01.0.0.0' } + @{ ExpectedPackageVersion = '4.0.1' ; SearchVersion = '4.0.1' ; NuspecVersion = '004.0.01.0' } + @{ ExpectedPackageVersion = '1.0.0' ; SearchVersion = '01.0.0.0' ; NuspecVersion = '01.0.0.0' } + @{ ExpectedPackageVersion = '4.0.1' ; SearchVersion = '004.0.01.0' ; NuspecVersion = '004.0.01.0' } + @{ ExpectedPackageVersion = '4.0.1' ; SearchVersion = '0000004.00000.00001.0000' ; NuspecVersion = '004.0.01.0' } + ) -Tag VersionNormalization { + BeforeAll { + Restore-ChocolateyInstallSnapshot + $PackageUnderTest = 'nonnormalizedversions' + $Output = Invoke-Choco install $PackageUnderTest --Version $SearchVersion + } + + It "Should exit with success (0)" { + $Output.ExitCode | Should -Be 0 -Because $Output.String + } + + It "Should report successful installation" { + $Output.Lines | Should -Contain "$PackageUnderTest v$ExpectedPackageVersion" -Because $Output.String + $Output.Lines | Should -Contain 'Chocolatey installed 1/1 packages.' -Because $Output.String + } + + It "Should have installed the correct files" { + $ExpectedFiles = "${env:ChocolateyInstall}/lib/$PackageUnderTest/$PackageUnderTest" + "$ExpectedFiles.nupkg" | Should -Exist -Because $Output.String + $NuspecContents = [xml](Get-Content "$ExpectedFiles.nuspec") + $NuspecContents.package.metadata.version | Should -Be $NuspecVersion + } + } + # This needs to be the last test in this block, to ensure NuGet configurations aren't being created. # Any tests after this block are expected to generate the configuration as they're explicitly using the NuGet CLI Test-NuGetPaths @@ -1736,7 +1868,7 @@ To install a local, or remote file, you may use: } It 'Installs successfully and exits with success (0)' { - $Output.ExitCode | Should -Be 0 + $Output.ExitCode | Should -Be 0 -Because $Output.String } It 'Shows a warning about the unsupported nuspec metadata element "<_>"' -TestCases $testCases { diff --git a/tests/chocolatey-tests/commands/choco-list.Tests.ps1 b/tests/chocolatey-tests/commands/choco-list.Tests.ps1 index cc9f53feef..d30e8465f4 100644 --- a/tests/chocolatey-tests/commands/choco-list.Tests.ps1 +++ b/tests/chocolatey-tests/commands/choco-list.Tests.ps1 @@ -99,17 +99,31 @@ Describe "choco list" -Tag Chocolatey, ListCommand { } } - Context "Listing local packages with unsupported argument outputs warning" -ForEach @('-l', '-lo', '--lo', '--local', '--localonly', '--local-only', '--order-by-popularity', '-a', '--all', '--allversions', '--all-versions') { + Context "Listing local packages with unsupported argument errors out" -ForEach @('-l', '-lo', '--lo', '--local', '--localonly', '--local-only', '--order-by-popularity', '-a', '--all', '--allversions', '--all-versions', '-li', '-il', '-lai', '-lia', '-ali', '-ail', '-ial', '-ila') { BeforeAll { $Output = Invoke-Choco list $_ } + It "Exits with Failure (1)" { + $Output.ExitCode | Should -Be 1 + } + + It "Should output expected error message" { + $Output.Lines | Should -Contain "Invalid argument $_. This argument has been removed from the list command and cannot be used." -Because $Output.String + } + } + + Context "Listing local packages with unsupported argument and --limit-output allows listing packages" -Foreach @('-l', '-lo', '--lo', '--local', '--localonly', '--local-only', '--order-by-popularity', '-a', '--all', '--allversions', '--all-versions', '-li', '-il', '-lai', '-lia', '-ali', '-ail', '-ial', '-ila') { + BeforeAll { + $Output = Invoke-Choco list $_ --limit-output + } + It "Exits with Success (0)" { $Output.ExitCode | Should -Be 0 } - It "Should contain expected warning message" { - $Output.Lines | Should -Contain "UNSUPPORTED ARGUMENT: Ignoring the argument $_. This argument is unsupported for locally installed packages, and will be treated as a package name in Chocolatey CLI v3!" + It "Should not output the error message" { + $Output.Lines | Should -Not -Contain "Invalid argument $_. This argument has been removed from the list command and cannot be used." -Because $Output.String } } } diff --git a/tests/chocolatey-tests/commands/choco-pack.Tests.ps1 b/tests/chocolatey-tests/commands/choco-pack.Tests.ps1 index e1af5497e0..7ddc606167 100644 --- a/tests/chocolatey-tests/commands/choco-pack.Tests.ps1 +++ b/tests/chocolatey-tests/commands/choco-pack.Tests.ps1 @@ -1,34 +1,35 @@ -Import-Module helpers/common-helpers - -$successPack = @('basic'; 'basic-dependencies'; "cdata"; "full") -# Required elements, that can also not be empty -$missingFailures = @('id'; 'version'; 'authors'; 'description') -# Elements that can not be set to an empty string, but are not required -$emptyFailures = @( - "projectUrl" - "projectSourceUrl" - "docsUrl" - "bugTrackerUrl" - "mailingListUrl" - "iconUrl" - "licenseUrl" -) -# Elements that will return an invalid failure (usually due to serialization) -$invalidFailures = @( - @{id = 'projectUrl'; message = "ERROR: CHCU0001: 'invalid project url' is not a valid URL for the projectUrl element in the package nuspec file." } - @{id = 'projectSourceUrl'; message = "ERROR: CHCU0001: 'invalid project source url' is not a valid URL for the projectSourceUrl element in the package nuspec file." } - @{id = 'docsUrl'; message = "ERROR: CHCU0001: 'invalid docs url' is not a valid URL for the docsUrl element in the package nuspec file." } - @{id = 'bugTrackerUrl'; message = "ERROR: CHCU0001: 'invalid bug tracker url' is not a valid URL for the bugTrackerUrl element in the package nuspec file." } - @{id = 'mailingListUrl'; message = "ERROR: CHCU0001: 'invalid mailing list url' is not a valid URL for the mailingListUrl element in the package nuspec file." } - @{id = 'iconUrl'; message = "ERROR: CHCU0001: 'invalid icon url' is not a valid URL for the iconUrl element in the package nuspec file." } - @{id = 'licenseUrl'; message = "ERROR: CHCU0001: 'invalid license url' is not a valid URL for the licenseUrl element in the package nuspec file." } - @{id = "version"; message = "ERROR: CHCU0001: 'INVALID' is not a valid version string in the package nuspec file." } - @{id = "no-content"; message = "Cannot create a package that has no dependencies nor content." } # This is a message from NuGet.Client, we may want to take ownership of it eventually. - @{id = "id"; message = "The package ID 'invalid id' contains invalid characters. Examples of valid package IDs include 'MyPackage' and 'MyPackage.Sample'." } # This is a message from NuGet.Client, we may want to take ownership of it eventually. - @{id = "requirelicenseacceptance"; message = "ERROR: CHCR0002: Enabling license acceptance requires a license url." } -) - + Describe "choco pack" -Tag Chocolatey, PackCommand { + BeforeDiscovery { + $successPack = @('basic'; 'basic-dependencies'; "cdata"; "full") + # Required elements, that can also not be empty + $missingFailures = @('id'; 'version'; 'authors'; 'description') + # Elements that can not be set to an empty string, but are not required + $emptyFailures = @( + "projectUrl" + "projectSourceUrl" + "docsUrl" + "bugTrackerUrl" + "mailingListUrl" + "iconUrl" + "licenseUrl" + ) + # Elements that will return an invalid failure (usually due to serialization) + $invalidFailures = @( + @{id = 'projectUrl'; message = "ERROR: CHCU0001: 'invalid project url' is not a valid URL for the projectUrl element in the package nuspec file." } + @{id = 'projectSourceUrl'; message = "ERROR: CHCU0001: 'invalid project source url' is not a valid URL for the projectSourceUrl element in the package nuspec file." } + @{id = 'docsUrl'; message = "ERROR: CHCU0001: 'invalid docs url' is not a valid URL for the docsUrl element in the package nuspec file." } + @{id = 'bugTrackerUrl'; message = "ERROR: CHCU0001: 'invalid bug tracker url' is not a valid URL for the bugTrackerUrl element in the package nuspec file." } + @{id = 'mailingListUrl'; message = "ERROR: CHCU0001: 'invalid mailing list url' is not a valid URL for the mailingListUrl element in the package nuspec file." } + @{id = 'iconUrl'; message = "ERROR: CHCU0001: 'invalid icon url' is not a valid URL for the iconUrl element in the package nuspec file." } + @{id = 'licenseUrl'; message = "ERROR: CHCU0001: 'invalid license url' is not a valid URL for the licenseUrl element in the package nuspec file." } + @{id = "version"; message = "ERROR: CHCU0001: 'INVALID' is not a valid version string in the package nuspec file." } + @{id = "no-content"; message = "Cannot create a package that has no dependencies nor content." } # This is a message from NuGet.Client, we may want to take ownership of it eventually. + @{id = "id"; message = "The package ID 'invalid id' contains invalid characters. Examples of valid package IDs include 'MyPackage' and 'MyPackage.Sample'." } # This is a message from NuGet.Client, we may want to take ownership of it eventually. + @{id = "requirelicenseacceptance"; message = "ERROR: CHCR0002: Enabling license acceptance requires a license url." } + ) + } + BeforeAll { Remove-NuGetPaths $testPackageLocation = "$(Get-TempDirectory)ChocolateyTests\packages" @@ -584,6 +585,46 @@ Describe "choco pack" -Tag Chocolatey, PackCommand { } } + Context 'Packing a package with non-normalized versions generates normalized versions' -ForEach @( + @{ ExpectedPackageVersion = '0.1.0' ; ProvidedVersion = '0.1.0.0' } + @{ ExpectedPackageVersion = '1.2.3.4' ; ProvidedVersion = '01.02.03.04' } + @{ ExpectedPackageVersion = '1.2.4' ; ProvidedVersion = '01.02.04' } + @{ ExpectedPackageVersion = '1.2.0' ; ProvidedVersion = '01.02' } + @{ ExpectedPackageVersion = '1.2.3' ; ProvidedVersion = '0001.0002.0003' } + @{ ExpectedPackageVersion = '2.0.0' ; ProvidedVersion = '02' } + ) -Tag VersionNormalization { + BeforeAll { + Restore-ChocolateyInstallSnapshot + $PackageUnderTest = 'nonnormalizedversions' + Push-Location (New-Item "$(Get-TempDirectory)/$(New-Guid)" -ItemType Directory) + $null = Invoke-Choco new $PackageUnderTest --version $ProvidedVersion + $SourceNuspec = "$PWD/$PackageUnderTest/$PackageUnderTest.nuspec" + $Output = Invoke-Choco pack $SourceNuspec + } + + AfterAll { + Pop-Location + } + + It "Should exit with success (0)" { + $Output.ExitCode | Should -Be 0 -Because $Output.String + } + + It "Should report successful installation" { + $Output.Lines | Should -Contain "Successfully created package '$PWD\$PackageUnderTest.$ExpectedPackageVersion.nupkg'" -Because $Output.String + } + + It "Should have generated the correct files" { + $ExpectedNupkg = "$PWD/$PackageUnderTest.$ExpectedPackageVersion.nupkg" + $ExpectedNupkg | Should -Exist -Because $Output.String + Expand-ZipArchive -Source $ExpectedNupkg -Destination "$PWD/$PackageUnderTest-expanded" + $SourceNuspecContents = [xml](Get-Content $SourceNuspec) + $PackedNuspecContents = [xml](Get-Content "$PWD/$PackageUnderTest-expanded/$PackageUnderTest.nuspec") + $SourceNuspecContents.package.metadata.version | Should -Be $ProvidedVersion + $PackedNuspecContents.package.metadata.version | Should -Be $ExpectedPackageVersion + } + } + # This needs to be the last test in this block, to ensure NuGet configurations aren't being created. Test-NuGetPaths } diff --git a/tests/chocolatey-tests/commands/choco-push.Tests.ps1 b/tests/chocolatey-tests/commands/choco-push.Tests.ps1 index 1504b8a22f..218ada4d9f 100644 --- a/tests/chocolatey-tests/commands/choco-push.Tests.ps1 +++ b/tests/chocolatey-tests/commands/choco-push.Tests.ps1 @@ -1,6 +1,7 @@ Import-Module helpers/common-helpers -Describe "choco push" -Tag Chocolatey, PushCommand -Skip:($null -eq $env:API_KEY -or $null -eq $env:PUSH_REPO) { +# These are skipped in the Proxy Test environment because they push to a port outside of 8443 which is not allowed by our proxy. +Describe "choco push" -Tag Chocolatey, PushCommand, ProxySkip -Skip:($null -eq $env:API_KEY -or $null -eq $env:PUSH_REPO) { BeforeAll { Remove-NuGetPaths $ApiKey = $env:API_KEY diff --git a/tests/chocolatey-tests/commands/choco-removed.Tests.ps1 b/tests/chocolatey-tests/commands/choco-removed.Tests.ps1 index 1f2f441a9e..e74c9e3304 100644 --- a/tests/chocolatey-tests/commands/choco-removed.Tests.ps1 +++ b/tests/chocolatey-tests/commands/choco-removed.Tests.ps1 @@ -64,7 +64,7 @@ exit $command.Count $null = Invoke-Choco new testPackage --version 1.0.0 $null = Invoke-Choco pack testPackage/testPackage.nuspec $null = Invoke-Choco apikey add -s https://chocolatey.org -k None - $Output = Invoke-Choco push ./testPackage.1.0.0.nupkg + $Output = Invoke-Choco push ./testPackage.1.0.0.nupkg --source https://push.chocolatey.org/ } It 'Exits with Failure (1)' { @@ -109,7 +109,7 @@ exit $command.Count Context 'Ensure WebPI source removal' -Skip:(-not (Test-ChocolateyVersionEqualOrHigherThan '1.999.999')) { BeforeAll { - $Output = Invoke-Choco list --source webpi + $Output = Invoke-Choco search --source webpi } It 'Exits with Failure (1)' { @@ -135,9 +135,9 @@ exit $command.Count } } - Context 'Ensure --allow-multiple removed from Chocolatey' -Tag InstallCommand, UpgradeCommand, UninstallCommand, AllowMultiple -Foreach @( + Context 'Ensure --allow-multiple removed from Chocolatey <Command> command' -Tag InstallCommand, UpgradeCommand, UninstallCommand, AllowMultiple, cory -Foreach @( @{ Command = 'install' } - @{ Command = 'update' } + @{ Command = 'upgrade' } @{ Command = 'uninstall' } ){ BeforeAll { @@ -156,11 +156,13 @@ exit $command.Count $Output = Invoke-Choco $Command $package @options } - It 'Exits with Success (0)' { + # Skipping on Upgrade as that exits with -1 due to the BeforeModify script. + It 'Exits with Success (0)' -Skip:($Command -eq 'upgrade') { $Output.ExitCode | Should -Be 0 -Because $Output.String } - It 'Does not use a versioned package folder' -Skip:($Command -eq 'upgrade') { + # Skipping on uninstall because there shouldn't be a folder after uninstall. + It 'Does not use a versioned package folder' -Skip:($Command -eq 'uninstall') { $expectedPath = Join-Path $env:ChocolateyInstall -ChildPath 'lib' | Join-Path -ChildPath $package diff --git a/tests/chocolatey-tests/commands/choco-search.Tests.ps1 b/tests/chocolatey-tests/commands/choco-search.Tests.ps1 index 6109c162bb..442fdd3b8a 100644 --- a/tests/chocolatey-tests/commands/choco-search.Tests.ps1 +++ b/tests/chocolatey-tests/commands/choco-search.Tests.ps1 @@ -1,4 +1,4 @@ -<# +<# .Synopsis Tests for `choco search` and aliases @@ -18,6 +18,7 @@ Import-Module helpers/common-helpers Describe "choco <_>" -ForEach $Command -Tag Chocolatey, SearchCommand, FindCommand { BeforeDiscovery { $licensedProxyFixed = Test-PackageIsEqualOrHigher 'chocolatey.extension' 2.2.0-beta -AllowMissingPackage + $hasEnabledV3Feed = Test-HasNuGetV3Source } BeforeAll { @@ -35,7 +36,8 @@ Describe "choco <_>" -ForEach $Command -Tag Chocolatey, SearchCommand, FindComma Remove-ChocolateyTestInstall } - Context "Searching packages with no filter (Happy Path)" { + # Skip when searching against a v3 source as our current source is not returning consistent results. + Context "Searching packages with no filter (Happy Path)" -Skip:$hasEnabledV3Feed { BeforeAll { $Output = Invoke-Choco $_ } @@ -84,7 +86,8 @@ Describe "choco <_>" -ForEach $Command -Tag Chocolatey, SearchCommand, FindComma } } - Context "Searching all available packages" { + # Skip when searching against a v3 source as our current source is not returning consistent results. + Context "Searching all available packages" -Skip:$hasEnabledV3Feed { BeforeAll { $Output = Invoke-Choco $_ --AllVersions } @@ -110,7 +113,7 @@ Describe "choco <_>" -ForEach $Command -Tag Chocolatey, SearchCommand, FindComma } } - Context "Searching all available packages (allowing prerelease)" -Tag Testing { + Context "Searching all available packages (allowing prerelease)" { BeforeAll { $Output = Invoke-Choco $_ --AllVersions --PreRelease } @@ -154,7 +157,8 @@ Describe "choco <_>" -ForEach $Command -Tag Chocolatey, SearchCommand, FindComma } } - Context "Searching packages with Verbose" { + # Skip when searching against a v3 source as our current source is not returning consistent results. + Context "Searching packages with Verbose" -Skip:$hasEnabledV3Feed { BeforeAll { $Output = Invoke-Choco $_ --Verbose } @@ -250,7 +254,8 @@ Describe "choco <_>" -ForEach $Command -Tag Chocolatey, SearchCommand, FindComma } # Issue: https://gitlab.com/chocolatey/collaborators/choco-licensed/-/issues/530 (NOTE: Proxy bypassing also works on Chocolatey FOSS) - Context "Searching packages on source using proxy and proxy bypass list" -Skip:(!$licensedProxyFixed) { + # These are skipped on Proxy tests because the proxy server can't be bypassed in that test environment. + Context "Searching packages on source using proxy and proxy bypass list" -Tag ProxySkip -Skip:(!$licensedProxyFixed) { BeforeAll { Restore-ChocolateyInstallSnapshot $null = Invoke-Choco config set --name=proxy --value="https://invalid.chocolatey.org/" @@ -273,7 +278,8 @@ Describe "choco <_>" -ForEach $Command -Tag Chocolatey, SearchCommand, FindComma } # Issue: https://gitlab.com/chocolatey/collaborators/choco-licensed/-/issues/530 (NOTE: Proxy bypassing also works on Chocolatey FOSS) - Context "Searching packages on source using proxy and proxy bypass list on command" -Skip:(!$licensedProxyFixed) { + # These are skipped on Proxy tests because the proxy server can't be bypassed in that test environment. + Context "Searching packages on source using proxy and proxy bypass list on command" -Tag ProxySkip -Skip:(!$licensedProxyFixed) { BeforeAll { Restore-ChocolateyInstallSnapshot $null = Invoke-Choco config set --name=proxy --value="https://invalid.chocolatey.org/" @@ -442,7 +448,29 @@ Describe "choco <_>" -ForEach $Command -Tag Chocolatey, SearchCommand, FindComma } It "Uses search term '--local-only'" { - $Output.String | Should -BeLike "*searchTerm='--local-only'*" + $Output.String | Should -Match "searchTerm='--local-only'|q=--local-only" + } + } + + Context "Searching for package when invalid package source is being used" { + BeforeAll { + Restore-ChocolateyInstallSnapshot + $InvalidSource = "https://invalid.chocolatey.org/api/v2/" + $null = Invoke-Choco source add -n "invalid" -s $InvalidSource + + $Output = Invoke-Choco search dependency + } + + It 'Exits with Success (0)' { + $Output.ExitCode | Should -Be 0 -Because $Output.String + } + + It 'Outputs warning about unable to load service index' { + $Output.Lines | Should -Contain "Unable to load the service index for source $InvalidSource." -Because $Output.String + } + + It 'Outputs the results of the search' { + $Output.Lines | Should -Contain 'hasrebootdependency 1.0.0' } } diff --git a/tests/chocolatey-tests/commands/choco-uninstall.Tests.ps1 b/tests/chocolatey-tests/commands/choco-uninstall.Tests.ps1 index c2935bc253..220b68ea2c 100644 --- a/tests/chocolatey-tests/commands/choco-uninstall.Tests.ps1 +++ b/tests/chocolatey-tests/commands/choco-uninstall.Tests.ps1 @@ -1,5 +1,3 @@ -Import-Module helpers/common-helpers - Describe "choco uninstall" -Tag Chocolatey, UninstallCommand { BeforeAll { Remove-NuGetPaths @@ -37,6 +35,419 @@ Describe "choco uninstall" -Tag Chocolatey, UninstallCommand { } } + Context "Uninstalling a package when chocolateyBeforeModify fails" { + BeforeAll { + Restore-ChocolateyInstallSnapshot + + $null = Invoke-Choco install upgradepackage --version 1.0.0 --confirm + + $Output = Invoke-Choco uninstall upgradepackage --confirm + } + + # Broken since v1.0.0 + It "Exits with Success (0)" -Tag Broken { + $Output.ExitCode | Should -Be 0 -Because $Output.String + } + + It "Should have removed lib package directory" { + "$env:ChocolateyInstall\lib\upgradepackage" | Should -Not -Exist + } + + It "Should not have created lib-bad directory" { + "$env:ChocolateyInstall\lib-bad\upgradepackage" | Should -Not -Exist + } + + It "Should have removed lib-bkp directory" { + "$env:ChocolateyInstall\lib-bkp\upgradepackage" | Should -Not -Exist + } + + It "Outputs Successful uninstall" { + $Output.Lines | Should -Contain "Chocolatey uninstalled 1/1 packages." + } + + It "Outputs additiontal warning about before modify script" { + $Output.Lines | Should -Contain "- upgradepackage - Error while running the 'chocolateyBeforeModify.ps1'." -Because $Output.String + } + } + + Context "Uninstalling a package with a failing uninstall script" { + BeforeAll { + Restore-ChocolateyInstallSnapshot + + $null = Invoke-Choco install uninstallfailure --confirm --no-progress + + "Test file" | Out-File "$env:ChocolateyInstall\lib\uninstallfailure\test-file.txt" + + $Output = Invoke-Choco uninstall uninstallfailure --confirm + } + + It "Exits with Failure (-1)" { + $Output.ExitCode | Should -Be -1 -Because $Output.String + } + + It "Should have kept file '<_>' in lib directory" -ForEach @('uninstallfailure.nupkg', 'uninstallfailure.nuspec', 'tools\chocolateyuninstall.ps1', "test-file.txt") { + "$env:ChocolateyInstall\lib\uninstallfailure\$_" | Should -Exist + } + + It "Should have created backup of file '<_>' in lib directory" -ForEach @('uninstallfailure.nupkg', 'uninstallfailure.nuspec', 'tools\chocolateyuninstall.ps1', "test-file.txt") { + "$env:ChocolateyInstall\lib-bad\uninstallfailure\1.0.0\$_" | Should -Exist + } + + It "Should not have kept backup files" { + "$env:ChocolateyInstall\lib-bkp\uninstallfailure" | Should -Not -Exist + } + + It "Outputs no package uninstalled" { + $Output.Lines | Should -Contain "Chocolatey uninstalled 0/1 packages. 1 packages failed." + } + } + + Context "Uninstalling a package where non-package file is locked" { + BeforeAll { + Restore-ChocolateyInstallSnapshot + + $null = Invoke-Choco install installpackage --confirm --no-progress + + $LockedFile = [System.IO.File]::Open("$env:ChocolateyInstall\lib\installpackage\a-locked-file.txt", 'OpenOrCreate', 'Read', 'Read') + + $Output = Invoke-Choco uninstall installpackage --confirm + } + + AfterAll { + $LockedFile.Dispose() + } + + It "Exits with Success (0)" { + $Output.ExitCode | Should -Be 0 -Because $Output.String + } + + It "Should have kept locked file in lib directory" { + "$env:ChocolateyInstall\lib\installpackage\a-locked-file.txt" | Should -Exist + } + + It "Should have removed file '<_>' in lib directory" -ForEach @('installpackage.nupkg', 'installpackage.nuspec', 'tools\casemismatch.exe', 'tools\Casemismatch.exe.ignore', 'tools\chocolateyBeforeModify.ps1', 'tools\chocolateyinstall.ps1', 'tools\chocolateyuninstall.ps1', 'tools\console.exe', 'tools\graphical.exe', 'tools\graphical.exe.gui', 'tools\not.installed.exe', 'tools\not.installed.exe.ignore', 'tools\simplefile.txt') { + "$env:ChocolateyInstall\lib\installpackage\$_" | Should -Not -Exist + } + + It "Should not have created lib-bad directory" { + "$env:ChocolateyInstall\lib-bad\upgradepackage" | Should -Not -Exist + } + + It "Should have removed lib-bkp directory" { + "$env:ChocolateyInstall\lib-bkp\upgradepackage" | Should -Not -Exist + } + + It "Outputs Successful uninstall" { + $Output.Lines | Should -Contain "Chocolatey uninstalled 1/1 packages." + } + } + + # When a file exists before initial installation, it will be considered as part of the + # package files. This is NuGet behavior. This happens during existing files for upgrades as well. + # We might want to rollback files in this case, but it is not possible as the backup has been removed before + # any locked files are being tried to be removed. + Context "Uninstalling a package where non-package file is locked before initial installation" { + BeforeAll { + Restore-ChocolateyInstallSnapshot + + mkdir "$env:ChocolateyInstall\lib\installpackage" + $LockedFile = [System.IO.File]::Open("$env:ChocolateyInstall\lib\installpackage\a-locked-file.txt", 'OpenOrCreate', 'Read', 'Read') + + $null = Invoke-Choco install installpackage --confirm --no-progress + + $Output = Invoke-Choco uninstall installpackage --confirm + } + + AfterAll { + $LockedFile.Dispose() + } + + It "Exits with Failure (1)" { + $Output.ExitCode | Should -Be 1 -Because $Output.String + } + + It "Should have kept locked file in lib directory" { + "$env:ChocolateyInstall\lib\installpackage\a-locked-file.txt" | Should -Exist + } + + It "Should have removed file '<_>' in lib directory" -ForEach @('installpackage.nupkg', 'installpackage.nuspec', 'tools\casemismatch.exe', 'tools\Casemismatch.exe.ignore', 'tools\chocolateyBeforeModify.ps1', 'tools\chocolateyinstall.ps1', 'tools\chocolateyuninstall.ps1', 'tools\console.exe', 'tools\graphical.exe', 'tools\graphical.exe.gui', 'tools\not.installed.exe', 'tools\not.installed.exe.ignore', 'tools\simplefile.txt') { + "$env:ChocolateyInstall\lib\installpackage\$_" | Should -Not -Exist + } + + It "Should not have created lib-bad directory" { + "$env:ChocolateyInstall\lib-bad\upgradepackage" | Should -Not -Exist + } + + It "Should have removed lib-bkp directory" { + "$env:ChocolateyInstall\lib-bkp\upgradepackage" | Should -Not -Exist + } + + It "Reports no package uninstalled" { + $Output.Lines | Should -Contain "Chocolatey uninstalled 0/1 packages. 1 packages failed." + } + + It "Outputs not able to remove all package files" { + $Output.String | Should -Match "installpackage - Unable to delete all existing package files. There will be leftover files requiring manual cleanup" + } + } + + Context "When specifying multiple packages where one is a dependency should not fail uninstallation" { + BeforeAll { + Restore-ChocolateyInstallSnapshot + + $null = Invoke-Choco install hasdependency --confirm + + $Output = Invoke-Choco uninstall isdependency hasdependency --confirm + } + + It "Exits with Success (0)" { + $Output.ExitCode | Should -Be 0 -Because $Output.String + } + + It "Should have removed <_>" -ForEach @('isdependency', 'hasdependency') { + "$env:ChocolateyInstall\lib\$_" | Should -Not -Exist -Because $Output.String + } + + It "Should not have removed isexactversiondependency" { + "$env:ChocolateyInstall\lib\isexactversiondependency" | Should -Exist -Because $Output.String + } + + It "Outputs <_> was succcesfully uninstalled" -ForEach @('isdependency', 'hasdependency') { + $Output.Lines | Should -Contain "$_ has been successfully uninstalled." -Because $Output.String + } + + It "Does not output isexactversiondependency being uninstalled" { + $Output.Lines | Should -Not -Contain "isexactversiondependency has been successfully uninstalled." -Because $Output.String + } + + It "Outputs 2/2 packages uninstalled" { + $Output.Lines | Should -Contain "Chocolatey uninstalled 2/2 packages." -Because $Output.String + } + } + + Context "When specifying multiple packages where one is a dependency should not fail uninstallation (forced dependencies)" { + BeforeAll { + Restore-ChocolateyInstallSnapshot + + $null = Invoke-Choco install hasdependency --confirm + + $Output = Invoke-Choco uninstall isdependency hasdependency --confirm --force-dependencies + } + + It "Exits with Success (0)" { + $Output.ExitCode | Should -Be 0 -Because $Output.String + } + + It "Should have removed <_>" -ForEach @('isdependency', 'hasdependency', 'isexactversiondependency') { + "$env:ChocolateyInstall\lib\$_" | Should -Not -Exist -Because $Output.String + } + + It "Outputs <_> was succcesfully uninstalled" -ForEach @('isdependency', 'hasdependency', 'isexactversiondependency') { + $Output.Lines | Should -Contain "$_ has been successfully uninstalled." -Because $Output.String + } + + It "Outputs 3/3 packages uninstalled" { + $Output.Lines | Should -Contain "Chocolatey uninstalled 3/3 packages." -Because $Output.String + } + } + + Context "When specifying non-existing package before and after failing package does not abort execution" { + BeforeAll { + $null = Invoke-Choco install uninstallfailure installpackage --confirm + + $Output = Invoke-Choco uninstall packageA uninstallfailure packageB installpackage --confirm + } + + It "Exits with Failure (-1)" { + $Output.ExitCode | Should -Be -1 -Because $Output.String + } + + It "Outputs package not existing (<_>)" -ForEach @('packageA', 'packageB') { + $Output.Lines | Should -Contain "$_ is not installed. Cannot uninstall a non-existent package." -Because $Output.String + $Output.Lines | Should -Contain "- $_ - $_ is not installed. Cannot uninstall a non-existent package." -Because $Output.String + } + + It "Outputs failing to uninstall package uninstallfailure" { + $Output.Lines | Should -Contain "uninstallfailure not uninstalled. An error occurred during uninstall:" -Because $Output.String + $Output.Lines | Should -Contain "uninstallfailure uninstall not successful." -Because $Output.String + $Output.String | Should -Match "- uninstallfailure \(exited -1\) - Error while running" + } + + It "Should have uninstall package installpackage" { + "$env:ChocolateyInstall\lib\installpackage" | Should -Not -Exist -Because $Output.String + } + + It "Outputs successful uninstall of installpackage" { + $Output.Lines | Should -Contain "installpackage has been successfully uninstalled." -Because $Output.String + } + + It "Outputs 1/3 successful uninstalls" { + $Output.Lines | Should -Contain "Chocolatey uninstalled 1/4 packages. 3 packages failed." -Because $Output.String + } + } + + Context "When specifying multiple packages where one is a nested dependency should not fail uninstallation" { + BeforeAll { + Restore-ChocolateyInstallSnapshot + + $null = Invoke-Choco install toplevelwithnesteddependencies --confirm + + $Output = Invoke-Choco uninstall isdependency toplevelwithnesteddependencies --confirm + } + + It "Exits with Failure (1)" { + $Output.ExitCode | Should -Be 1 -Because $Output.String + } + + It "Should have removed package toplevelwithnesteddependencies" { + "$env:ChocolateyInstall\lib\toplevelwithnesteddependencies" | Should -Not -Exist -Because $Output.String + } + + It "Should not have removed <_>" -ForEach @('hasdependency', 'hasnesteddependency', 'isdependency', 'isexactversiondependency', 'toplevelhasexactversiondependency') { + "$env:ChocolateyInstall\lib\$_" | Should -Exist -Because $Output.String + } + + It "Outputs toplevelwithnesteddependencies was succcesfully uninstalled" { + $Output.Lines | Should -Contain "toplevelwithnesteddependencies has been successfully uninstalled." -Because $Output.String + } + + It "Does not output <_> being uninstalled" -ForEach @('hasdependency', 'hasnesteddependency', 'isdependency', 'isexactversiondependency', 'toplevelhasexactversiondependency') { + $Output.Lines | Should -Not -Contain "$_ has been successfully uninstalled." -Because $Output.String + } + + It "Outputs warning about package being unable to be uninstalled due to being a dependency" { + $Output.Lines | Should -Contain "[NuGet]: Unable to uninstall 'isdependency.2.1.0' because 'hasdependency.2.0.1' depends on it." + } + + It "Outputs 1/2 packages uninstalled with 1 failed package" { + $Output.Lines | Should -Contain "Chocolatey uninstalled 1/2 packages. 1 packages failed." -Because $Output.String + } + + It "Outputs failure to uninstall one of the packages" { + $Output.Lines | Should -Contain "- isdependency - Unable to uninstall 'isdependency.2.1.0' because 'hasdependency.2.0.1' depends on it." + } + } + + Context "When specifying multiple packages where one is a nested dependency should not fail uninstallation (forced dependencies)" { + BeforeAll { + Restore-ChocolateyInstallSnapshot + + $null = Invoke-Choco install toplevelwithnesteddependencies --confirm + + $Output = Invoke-Choco uninstall isdependency toplevelwithnesteddependencies --confirm --force-dependencies + } + + It "Exits with Success (0)" { + $Output.ExitCode | Should -Be 0 -Because $Output.String + } + + It "Should have removed <_>" -ForEach @('hasdependency', 'hasnesteddependency', 'isdependency', 'isexactversiondependency', 'toplevelhasexactversiondependency', 'toplevelwithnesteddependencies') { + "$env:ChocolateyInstall\lib\$_" | Should -Not -Exist -Because $Output.String + } + + It "Outputs <_> was succcesfully uninstalled" -ForEach @('hasdependency', 'hasnesteddependency', 'isdependency', 'isexactversiondependency', 'toplevelhasexactversiondependency', 'toplevelwithnesteddependencies') { + $Output.Lines | Should -Contain "$_ has been successfully uninstalled." -Because $Output.String + } + + It "Outputs warning about package being unable to be uninstalled due to being a dependency" { + $Output.Lines | Should -Contain "[NuGet]: Unable to uninstall 'isdependency.2.1.0' because 'hasdependency.2.0.1' depends on it." + } + + It "Outputs 7/7 packages uninstalled" { + $Output.Lines | Should -Contain "Chocolatey uninstalled 7/7 packages." -Because $Output.String + } + + It "Does not output failure to uninstall one of the packages" { + $Output.Lines | Should -Not -Contain "- isdependency - Unable to uninstall 'isdependency.2.1.0' because 'hasdependency.2.0.1' depends on it." + } + } + + Context "When uninstalling a package, forcing dependencies to uninstall and dependency is referenced by other packages" { + BeforeAll { + Restore-ChocolateyInstallSnapshot + + $null = Invoke-Choco install hasdependency --version 1.0.0 --confirm + $null = Invoke-Choco install toplevelhasexactversiondependency --confirm + + $Output = Invoke-Choco uninstall hasdependency --force-dependencies --confirm + } + + It "Exits with Success (0)" { + $Output.ExitCode | Should -Be 0 -Because $Output.String + } + + It "Should have removed <_>" -ForEach @('hasdependency', 'isdependency') { + "$env:ChocolateyInstall\lib\$_" | Should -Not -Exist -Because $Output.String + } + + It "Should not have removed <_>" -ForEach @('isexactversiondependency', 'childdependencywithlooserversiondependency', 'toplevelhasexactversiondependency') { + "$env:ChocolateyInstall\lib\$_" | Should -Exist -Because $Output.String + } + + It "Outputs <_> was successfully uninstalled" -ForEach @('hasdependency', 'isdependency') { + $Output.Lines | Should -Contain "$_ has been successfully uninstalled." -Because $Output.String + } + + It "Outputs warning about dependency being skipped" { + $Output.Lines | Should -Contain "[NuGet] 'isexactversiondependency 1.0.0' skipped, because it is in use by 'childdependencywithlooserversiondependency 1.0.0,toplevelhasexactversiondependency 1.0.0'." -Because $Output.String + } + + It "Outputs 2/2 packages uninstalled" { + $Output.Lines | Should -Contain "Chocolatey uninstalled 2/2 packages." + } + } + + Context "Uninstalling package when user specifies non-confirming package id" { + BeforeAll { + Restore-ChocolateyInstallSnapshot + + $null = Invoke-Choco install isdependency --confirm + + $Output = Invoke-Choco uninstall IsDePeNDency --confirm + } + + It "Exits with Success (0)" { + $Output.ExitCode | Should -Be 0 + } + + It "Uninstall package successfully" { + $Output.Lines | Should -Contain "isdependency 2.1.0 Uninstalled" -Because $Output.String + } + + It "Removed package successfully from lib directory" { + "$env:ChocolateyInstall\lib\isdependency" | Should -Not -Exist + } + } + + Context "Uninstalling a package with a non-normalized version number" -ForEach @( + @{ ExpectedPackageVersion = '1.0.0' ; SearchVersion = '01.0.0.0' } + @{ ExpectedPackageVersion = '4.0.1' ; SearchVersion = '004.0.01.0' } + ) -Tag VersionNormalization { + BeforeAll { + Restore-ChocolateyInstallSnapshot + $PackageUnderTest = 'nonnormalizedversions' + $null = Invoke-Choco install $PackageUnderTest --Version $SearchVersion + $Output = Invoke-Choco uninstall $PackageUnderTest + } + + It "Should exit with success (0)" { + $Output.ExitCode | Should -Be 0 -Because $Output.String + } + + It "Should report successful uninstallation" { + $Output.Lines | Should -Contain "$PackageUnderTest v$ExpectedPackageVersion" -Because $Output.String + $Output.Lines | Should -Contain 'Chocolatey uninstalled 1/1 packages.' -Because $Output.String + } + + It "Should have removed any <Directory> directory" -ForEach @( + @{ Directory = 'lib' } + @{ Directory = 'lib-bkp' } + ) { + $InstallDirectory = "${env:ChocolateyInstall}/$Directory/$PackageUnderTest/" + $InstallDirectory | Should -Not -Exist -Because $Output.String + } + } + # This needs to be the last test in this block, to ensure NuGet configurations aren't being created. Test-NuGetPaths } diff --git a/tests/chocolatey-tests/commands/choco-upgrade.Tests.ps1 b/tests/chocolatey-tests/commands/choco-upgrade.Tests.ps1 index 7eb6cc2ddf..64020e5880 100644 --- a/tests/chocolatey-tests/commands/choco-upgrade.Tests.ps1 +++ b/tests/chocolatey-tests/commands/choco-upgrade.Tests.ps1 @@ -1,6 +1,4 @@ -Import-Module helpers/common-helpers - -Describe "choco upgrade" -Tag Chocolatey, UpgradeCommand { +Describe "choco upgrade" -Tag Chocolatey, UpgradeCommand { BeforeAll { Remove-NuGetPaths Initialize-ChocolateyTestInstall @@ -27,7 +25,7 @@ Describe "choco upgrade" -Tag Chocolatey, UpgradeCommand { } It "Exits with Success (0)" { - $Output.ExitCode | Should -Be 0 + $Output.ExitCode | Should -Be 0 -Because $Output.String } It "Output should include pinned package" { @@ -45,6 +43,7 @@ Describe "choco upgrade" -Tag Chocolatey, UpgradeCommand { Restore-ChocolateyInstallSnapshot $null = Enable-ChocolateyFeature useRememberedArgumentsForUpgrades + Enable-ChocolateySource -Name hermes-setup $null = Invoke-Choco install curl --package-parameters="'/CurlOnlyParam'" --version="7.77.0" --ia="'/CurlIAParam'" --x86 -y $null = Invoke-Choco install wget --version=1.21.1 -y @@ -52,7 +51,7 @@ Describe "choco upgrade" -Tag Chocolatey, UpgradeCommand { } It 'Exits with Success (0)' { - $Output.ExitCode | Should -Be 0 + $Output.ExitCode | Should -Be 0 -Because $Output.String } It 'Outputs running curl script with correct arguments' { @@ -81,6 +80,7 @@ Describe "choco upgrade" -Tag Chocolatey, UpgradeCommand { Restore-ChocolateyInstallSnapshot $null = Enable-ChocolateyFeature useRememberedArgumentsForUpgrades + Enable-ChocolateySource -Name hermes-setup $null = Invoke-Choco install curl --package-parameters="'/CurlOnlyParam'" --version="7.77.0" --ia="'/CurlIAParam'" --forcex86 -y $null = Invoke-Choco install wget --version=1.21.1 -y --forcex86 $null = Invoke-Choco install firefox --version=99.0.1 --package-parameters="'/l=eu'" -y --ia="'/RemoveDistributionDir=true'" @@ -93,7 +93,7 @@ Describe "choco upgrade" -Tag Chocolatey, UpgradeCommand { } It 'Exits with Success (0)' { - $Output.ExitCode | Should -Be 0 + $Output.ExitCode | Should -Be 0 -Because $Output.String } It 'Outputs running curl script with correct arguments' { @@ -140,7 +140,7 @@ Describe "choco upgrade" -Tag Chocolatey, UpgradeCommand { } It "Installs successfully and exits with success (0)" { - $Output.ExitCode | Should -Be 0 + $Output.ExitCode | Should -Be 0 -Because $Output.String } It "Installed the packages to the lib directory" { @@ -167,7 +167,7 @@ Describe "choco upgrade" -Tag Chocolatey, UpgradeCommand { } It "Exits with Failure (1)" { - $Output.ExitCode | Should -Be 1 + $Output.ExitCode | Should -Be 1 -Because $Output.String } It "Not Installed a package to the lib directory" { @@ -259,6 +259,295 @@ To upgrade a local, or remote file, you may use: } } + Context "Upgrading a package when invalid package source is being used" { + BeforeAll { + Restore-ChocolateyInstallSnapshot + + $null = Invoke-Choco install upgradepackage --version 1.0.0 --confirm + $InvalidSource = "https://invalid.chocolatey.org/api/v2/" + $null = Invoke-Choco source add -n "invalid" -s $InvalidSource + + $Output = Invoke-Choco upgrade upgradepackage --confirm + } + + + # `upgradepackage` contains a beforeModify that throws, which triggers an incorrect -1 exit code. + # See https://app.clickup.com/t/20540031/PROJ-615 + It 'Exits with Success (0)' -Tag Broken { + $Output.ExitCode | Should -Be 0 -Because $Output.String + } + + It 'Outputs warning about unable to load service index' { + $Output.Lines | Should -Contain "Unable to load the service index for source $InvalidSource." + } + + It 'Outputs successful installation of single package' { + $Output.Lines | Should -Contain 'Chocolatey upgraded 1/1 packages.' + } + } + + Context "Upgrading package should not downgrade existing package" { + BeforeAll { + Restore-ChocolateyInstallSnapshot + $DependentPackageName = 'isdependency' + + $null = Invoke-Choco install $DependentPackageName --version 1.1.0 --confirm + $null = Invoke-Choco install hasdependency --version 1.0.0 --confirm + + $Output = Invoke-Choco upgrade hasdependency + $Packages = (Invoke-Choco list -r).Lines | ConvertFrom-ChocolateyOutput -Command List + $DependentPackage = $Packages | Where-Object Name -EQ $DependentPackageName + } + + It 'Exits with Success (0)' { + $Output.ExitCode | Should -Be 0 -Because $Output.String + } + + It 'should not have downgraded isdependency' { + Test-VersionEqualOrHigher -InstalledVersion $DependentPackage.Version -CompareVersion 1.1.0 | Should -BeTrue + } + } + + Context "Upgrading a failing package creates creates bad backup and rolls back lib directory" { + BeforeAll { + Restore-ChocolateyInstallSnapshot + + $PackageUnderTest = "failingdependency" + $PackageVersion = '1.0.0' + + $null = Invoke-Choco install $PackageUnderTest --version 0.9.9 -n + + $Output = Invoke-Choco upgrade $PackageUnderTest --version $PackageVersion --confirm + } + + It "Exits with Failure (15608)" { + $Output.ExitCode | Should -Be 15608 -Because $Output.String + } + + It "Doesn't keep a package backup in lib-bkp" { + "$env:ChocolateyInstall\lib-bkp\$PackageUnderTest" | Should -Not -Exist + } + + It "Creates backup of file '<_>' in lib-bad" -ForEach @('failingdependency.nupkg', 'failingdependency.nuspec', '.chocolateyPending', 'tools\chocolateyinstall.ps1') { + "$env:ChocolateyInstall\lib-bad\$PackageUnderTest\$PackageVersion\$_" | Should -Exist + } + + It "Outputs a message showing that installation failed." { + $Output.String | Should -Match "Chocolatey upgraded 0/1 packages\." + } + } + + Context "Upgrading a package when installer is locked" { + BeforeAll { + Restore-ChocolateyInstallSnapshot + + $PackageUnderTest = "hasinnoinstaller" + $PackageVersion = '6.2.0.3' + + # We are purposely using the --reduce-nupkg-only option (both here and in the next call to Invoke-Choco), to make the + # test as close to default operation, when running both in the context of OSS and CLE. It was found during testing, that + # the Package Optimizer would remove the application installer, which is the file that is being locked during the test, + # which means then that the test doesn't actually test what we want it to. We are locking the exe here instead of say a + # PowerShell script, is to simulate the exe being used when the test is running. + $null = Invoke-Choco install $PackageUnderTest --version 6.2.0.0 --confirm --no-progress --reduce-nupkg-only + + $LockedFile = [System.IO.File]::Open("$env:ChocolateyInstall\lib\$PackageUnderTest\tools\helloworld-1.0.0.exe", 'Open', 'Read', + 'Read') + + $Output = Invoke-Choco upgrade $PackageUnderTest --version $PackageVersion --confirm --no-progress --reduce-nupkg-only + } + + AfterAll { + $LockedFile.Dispose() + $null = Invoke-Choco uninstall $PackageUnderTest --confirm + } + + It "Exits with Failure (1)" { + $Output.ExitCode | Should -Be 1 -Because $Output.String + } + + It "Keeps file '<_>' in the lib directory" -ForEach @('hasinnoinstaller.nuspec', 'hasinnoinstaller.nupkg', 'tools\chocolateyinstall.ps1', 'tools\chocolateyuninstall.ps1', 'tools\helloworld-1.0.0.exe', 'tools\helloworld-1.0.0.exe.ignore') { + "$env:ChocolateyInstall\lib\$PackageUnderTest\$_" | Should -Exist + } + + It "Doesn't keep a package backup in lib-bkp" { + "$env:ChocolateyInstall\lib-bkp\$PackageUnderTest" | Should -Not -Exist + } + + # Only two files are backed up as we was not able to download and extract the new package + It "Creates backup of file '<_>' in lib-bad" -ForEach @('.chocolateyPending', 'tools\helloworld-1.0.0.exe') { + "$env:ChocolateyInstall\lib-bad\$PackageUnderTest\$PackageVersion\$_" | Should -Exist + } + + It "Outputs a message showing that installation failed." { + $Output.Lines | Should -Contain "Chocolatey upgraded 0/1 packages. 1 packages failed." + } + } + + Context "Upgrading a package when non-package file is locked before initial installation" { + BeforeAll { + Restore-ChocolateyInstallSnapshot + + $PackageUnderTest = "hasinnoinstaller" + $PackageVersion = '6.2.0.3' + + mkdir "$env:ChocolateyInstall\lib\$PackageUnderTest\tools" + $LockedFile = [System.IO.File]::Open("$env:ChocolateyInstall\lib\$PackageUnderTest\tools\a-locked-file.txt", 'OpenOrCreate', 'Read', + 'Read') + + # We are purposely using the --reduce-nupkg-only option here to make the test as close to default operation, when running + # both in the context of OSS and CLE. It was found during testing, that the Package Optimizer can remove files that are + # normally left in place, and this test is specifically for testing the back-up/restore process. + $null = Invoke-Choco install $PackageUnderTest --version 6.2.0.0 --confirm --no-progress --reduce-nupkg-only + + $Output = Invoke-Choco upgrade $PackageUnderTest --version $PackageVersion --confirm --no-progress + } + + AfterAll { + $LockedFile.Dispose() + $null = Invoke-Choco uninstall $PackageUnderTest --confirm + } + + It "Exits with Failure (1)" { + $Output.ExitCode | Should -Be 1 -Because $Output.String + } + + It "Keeps file '<_>' in the lib directory" -ForEach @('hasinnoinstaller.nuspec', 'hasinnoinstaller.nupkg', 'tools\chocolateyinstall.ps1', 'tools\chocolateyuninstall.ps1', 'tools\helloworld-1.0.0.exe', 'tools\helloworld-1.0.0.exe.ignore') { + "$env:ChocolateyInstall\lib\$PackageUnderTest\$_" | Should -Exist + } + + It "Doesn't keep a package backup in lib-bkp" { + "$env:ChocolateyInstall\lib-bkp\$PackageUnderTest" | Should -Not -Exist + } + + It "Creates backup of file '<_>' in lib-bad" -ForEach @('.chocolateyPending', 'tools\a-locked-file.txt') { + "$env:ChocolateyInstall\lib-bad\$PackageUnderTest\$PackageVersion\$_" | Should -Exist + } + + It "Did not create backup of file '<_>' in lib-bad" -ForEach @('hasinnoinstaller.nuspec', 'tools\chocolateyinstall.ps1', 'tools\chocolateyuninstall.ps1', 'tools\helloworld-1.0.0.exe', 'helloworld-1.0.0.exe.ignore') { + "$env:ChocolateyInstall\lib-bad\$PackageUnderTest\$PackageVersion\$_" | Should -Not -Exist + } + + It "Did not create backup of file 'hasinnoinstaller.nupkg' in lib-bad" -Tag FossOnly { + "$env:ChocolateyInstall\lib-bad\$PackageUnderTest\$PackageVersion\hasinnoinstaller.nupkg" | Should -Not -Exist + } + + It "Outputs a message showing that installation failed." { + $Output.Lines | Should -Contain "Chocolatey upgraded 0/1 packages. 1 packages failed." -Because $Output.String + } + } + + Context "Upgrading a package when non-package file is locked after initial installation" { + BeforeAll { + Restore-ChocolateyInstallSnapshot + + $PackageUnderTest = "hasinnoinstaller" + $PackageVersion = '6.2.0.3' + + $null = Invoke-Choco install $PackageUnderTest --version 6.2.0.0 --confirm --no-progress + + $LockedFile = [System.IO.File]::Open("$env:ChocolateyInstall\lib\$PackageUnderTest\a-locked-file.txt", 'OpenOrCreate', 'Read', + 'Read') + + $Output = Invoke-Choco upgrade $PackageUnderTest --version $PackageVersion --confirm --no-progress + } + + AfterAll { + $LockedFile.Dispose() + $null = Invoke-Choco uninstall $PackageUnderTest --confirm + } + + It "Exits with Success (0)" { + $Output.ExitCode | Should -Be 0 -Because $Output.String + } + + It "Keeps have file '<_>' in the lib directory" -ForEach @('hasinnoinstaller.nuspec', 'hasinnoinstaller.nupkg', 'tools\chocolateyinstall.ps1', 'tools\chocolateyuninstall.ps1', 'tools\helloworld-1.0.0.exe', 'tools\helloworld-1.0.0.exe.ignore') { + "$env:ChocolateyInstall\lib\$PackageUnderTest\$_" | Should -Exist + } + + It "Doesn't keep a package backup in lib-bkp" { + "$env:ChocolateyInstall\lib-bkp\$PackageUnderTest" | Should -Not -Exist + } + + It "Doesn't keep a package backup in lib-bad" { + "$env:ChocolateyInstall\lib-bad\$PackageUnderTest" | Should -Not -Exist + } + + It "Outputs a message showing that package was upgraded." { + $Output.Lines | Should -Contain "Chocolatey upgraded 1/1 packages." -Because $Output.String + } + } + + Context "Upgrading a package where beforeModify fails still succeeds the installation" { + BeforeAll { + Restore-ChocolateyInstallSnapshot + + $PackageUnderTest = 'upgradepackage' + + $null = Invoke-Choco install upgradepackage --version 1.0.0 --confirm + + $Output = Invoke-Choco upgrade upgradepackage --confirm + } + + # This was broken in v1.3.1 + It "Exits with Success (0)" -Tag Broken { + $Output.ExitCode | Should -Be 0 + } + + It "Outputs a message showing that installation was successful" { + $Output.Lines | Should -Contain "Chocolatey upgraded 1/1 packages." + } + + It "Outputs additiontal warning about before modify script" { + $Output.Lines | Should -Contain "- upgradepackage - v1.0.0 - Error while running the 'chocolateyBeforeModify.ps1'." -Because $Output.String + } + } + + Context "Upgrading a package when user specifies non-conforming case and is latest available version (no-op)" { + BeforeAll { + Restore-ChocolateyInstallSnapshot + + $null = Invoke-Choco install isdependency --confirm + + $Output = Invoke-Choco upgrade IsDePeNDency --noop -r + } + + It "Exits with Success (0)" { + $Output.ExitCode | Should -Be 0 + } + + It "Outputs line with package name version and old version" { + $Output.String | Should -MatchExactly "isdependency\|2\.1\.0\|2\.1\.0\|false" + } + } + + Context "Upgrading a package with a non-normalized version number" -Tag VersionNormalization { + BeforeAll { + Restore-ChocolateyInstallSnapshot + $PackageUnderTest = 'nonnormalizedversions' + $VersionUnderTest = '004.0.01.0' + $ExpectedPackageVersion = '4.0.1' + $null = Invoke-Choco install $PackageUnderTest --version 1.0.0 + $Output = Invoke-Choco upgrade $PackageUnderTest + } + + It "Should exit with success (0)" { + $Output.ExitCode | Should -Be 0 -Because $Output.String + } + + It "Should report successful upgrade" { + $Output.Lines | Should -Contain "$PackageUnderTest v$ExpectedPackageVersion" -Because $Output.String + $Output.Lines | Should -Contain 'Chocolatey upgraded 1/1 packages.' -Because $Output.String + } + + It "Should have upgraded the correct files" { + $ExpectedFiles = "${env:ChocolateyInstall}/lib/$PackageUnderTest/$PackageUnderTest" + "$ExpectedFiles.Nupkg" | Should -Exist -Because $Output.String + $NuspecContents = [xml](Get-Content "$ExpectedFiles.nuspec") + $NuspecContents.package.metadata.version | Should -Be $VersionUnderTest + } + } + # This needs to be (almost) the last test in this block, to ensure NuGet configurations aren't being created. # Any tests after this block are expected to generate the configuration as they're explicitly using the NuGet CLI Test-NuGetPaths @@ -319,7 +608,7 @@ To upgrade a local, or remote file, you may use: } It 'Installs successfully and exits with success (0)' { - $Output.ExitCode | Should -Be 0 + $Output.ExitCode | Should -Be 0 -Because $Output.String } It 'Shows a warning about the unsupported nuspec metadata element "<_>"' -TestCases $testCases { diff --git a/tests/chocolatey-tests/features/Proxy.Tests.ps1 b/tests/chocolatey-tests/features/Proxy.Tests.ps1 new file mode 100644 index 0000000000..08926f0dcd --- /dev/null +++ b/tests/chocolatey-tests/features/Proxy.Tests.ps1 @@ -0,0 +1,266 @@ +Import-Module helpers/common-helpers + +$TestCases = @( + @{ + Name = 'None' + ConfigurationsToTest = @{ + System = $false + EnvironmentVariable = $false + ConfigFile = $false + CliArgument = $false + } + } + @{ + Name = 'System' + ConfigurationsToTest = @{ + System = $true + EnvironmentVariable = $false + ConfigFile = $false + CliArgument = $false + } + } + @{ + Name = 'SystemConfig' + ConfigurationsToTest = @{ + System = $true + EnvironmentVariable = $false + ConfigFile = $true + CliArgument = $false + } + } + @{ + Name = 'SystemEnvironmentVariable' + ConfigurationsToTest = @{ + System = $true + EnvironmentVariable = $true + ConfigFile = $false + CliArgument = $false + } + } + @{ + Name = 'SystemCliArgument' + ConfigurationsToTest = @{ + System = $true + EnvironmentVariable = $true + ConfigFile = $false + CliArgument = $false + } + } + @{ + Name = 'SystemConfigFileEnvironmentVariable' + ConfigurationsToTest = @{ + System = $true + EnvironmentVariable = $true + ConfigFile = $true + CliArgument = $false + } + } + @{ + Name = 'SystemConfigFileCliArgument' + ConfigurationsToTest = @{ + System = $true + EnvironmentVariable = $false + ConfigFile = $true + CliArgument = $true + } + } + @{ + Name = 'SystemEnvironmentVariableCliAgrument' + ConfigurationsToTest = @{ + System = $true + EnvironmentVariable = $true + ConfigFile = $false + CliArgument = $true + } + } + @{ + Name = 'SystemConfigFileEnvironmentVariableCliArgument' + ConfigurationsToTest = @{ + System = $true + EnvironmentVariable = $true + ConfigFile = $true + CliArgument = $true + } + } + @{ + Name = 'ConfigFile' + ConfigurationsToTest = @{ + System = $false + EnvironmentVariable = $false + ConfigFile = $true + CliArgument = $false + } + } + @{ + Name = 'ConfigFileEnvironmentVariable' + ConfigurationsToTest = @{ + System = $false + EnvironmentVariable = $true + ConfigFile = $true + CliArgument = $false + } + } + @{ + Name = 'ConfigFileCliArgument' + ConfigurationsToTest = @{ + System = $false + EnvironmentVariable = $false + ConfigFile = $true + CliArgument = $true + } + } + @{ + Name = 'ConfigFileEnvironmentVariableCliArgument' + ConfigurationsToTest = @{ + System = $false + EnvironmentVariable = $true + ConfigFile = $true + CliArgument = $true + } + } + @{ + Name = 'EnvironmentVariable' + ConfigurationsToTest = @{ + System = $false + EnvironmentVariable = $true + ConfigFile = $false + CliArgument = $false + } + } + @{ + Name = 'EnvironmentVariableCliArgument' + ConfigurationsToTest = @{ + System = $false + EnvironmentVariable = $true + ConfigFile = $false + CliArgument = $true + } + } + @{ + Name = 'CliArgument' + ConfigurationsToTest = @{ + System = $false + EnvironmentVariable = $false + ConfigFile = $false + CliArgument = $true + } + } +) + +$CommandsToTest = @( + @{ Command = 'install'; ExtraArguments = @('dummypackage') } + @{ Command = 'upgrade'; ExtraArguments = @('dummypackage') } + @{ Command = 'search'; ExtraArguments = @('') } + @{ Command = 'find'; ExtraArguments = @('') } + @{ Command = 'outdated'; ExtraArguments = @('') } + @{ Command = 'push'; ExtraArguments = @("--source='https://example.com'", "--api-key='my-key'") } +) + +# Skip when not on Test Kitchen as this changes the system proxy +# Skip when run in Proxy Test Kitchen as the Proxy test kitchen sets some of these... +Describe "Proxy configuration (<Name>)" -Tag Proxy, ProxySkip -ForEach $TestCases -Skip:(-not $env:TEST_KITCHEN) { + BeforeAll { + Initialize-ChocolateyTestInstall + New-ChocolateyInstallSnapshot + $arguments = $null + + $SystemSet = "SystemSetProxy" + $ConfigFileSet = "ConfigFileSetProxy" + $EnvironmentVariableSet = "EnvironmentVariableSetProxy" + $CliArgumentSet = "CliArgumentSetProxy" + + if ($ConfigurationsToTest.System) { + Set-ItemProperty -Path 'HKCU:/Software/Microsoft/Windows/CurrentVersion/Internet Settings' -Name ProxyServer -Value "https=$SystemSet;ftp=someFtp;socks=socksProxy" + Set-ItemProperty -Path 'HKCU:/Software/Microsoft/Windows/CurrentVersion/Internet Settings' -Name ProxyEnable -Value 1 + } + + if ($ConfigurationsToTest.ConfigFile) { + Invoke-Choco config set proxy $ConfigFileSet + Invoke-Choco config set proxyBypassList $ConfigFileSet + } + + if ($ConfigurationsToTest.EnvironmentVariable) { + $env:https_proxy = $EnvironmentVariableSet + $env:no_proxy = $EnvironmentVariableSet + } + + if ($ConfigurationsToTest.CliArgument) { + $arguments = @("--proxy='$CliArgumentSet'", "--proxy-bypass-list='$CliArgumentSet'") + } + } + + AfterAll { + Remove-ChocolateyTestInstall + Remove-ItemProperty -Path 'HKCU:/Software/Microsoft/Windows/CurrentVersion/Internet Settings' -Name ProxyServer -ErrorAction Ignore + Remove-ItemProperty -Path 'HKCU:/Software/Microsoft/Windows/CurrentVersion/Internet Settings' -Name ProxyEnable -ErrorAction Ignore + $env:https_proxy = $null + } + + Context "Configured for command (<Command>)" -ForEach $CommandsToTest { + BeforeAll { + $Output = Invoke-Choco $Command @arguments @ExtraArguments --debug --verbose --noop + } + + It "Should output the correct Proxy setting" { + switch ($true) { + $ConfigurationsToTest.CliArgument { + $Output.String | Should -MatchExactly "Proxy\.Location='$CliArgumentSet'" + $Output.String | Should -MatchExactly "Proxy\.BypassList='$CliArgumentSet'" + continue + } + + $ConfigurationsToTest.ConfigFile { + $Output.String | Should -MatchExactly "Proxy\.Location='$ConfigFileSet'" + $Output.String | Should -MatchExactly "Proxy\.BypassList='$ConfigFileSet'" + continue + } + + $ConfigurationsToTest.EnvironmentVariable { + $Output.String | Should -MatchExactly "Proxy\.Location='$EnvironmentVariableSet'" + $Output.String | Should -MatchExactly "Proxy\.BypassList='$EnvironmentVariableSet'" + continue + } + + $ConfigurationsToTest.System { + $Output.String | Should -MatchExactly "Proxy\.Location='$SystemSet'" + continue + } + + default { + $Output.String | Should -Not -Match "Proxy\.Location" + $Output.String | Should -Not -Match "Proxy\.BypassList" + } + } + } + } +} + +Describe "Multi-Protocol Proxy configuration" -Tag Proxy, ProxySkip -Skip:(-not $env:TEST_KITCHEN) { + BeforeAll { + Initialize-ChocolateyTestInstall + New-ChocolateyInstallSnapshot + $arguments = $null + + $SystemSet = "SystemSetProxy" + Set-ItemProperty -Path 'HKCU:/Software/Microsoft/Windows/CurrentVersion/Internet Settings' -Name ProxyServer -Value "ftp=something;socks=another" + Set-ItemProperty -Path 'HKCU:/Software/Microsoft/Windows/CurrentVersion/Internet Settings' -Name ProxyEnable -Value 1 + } + + AfterAll { + Remove-ChocolateyTestInstall + Remove-ItemProperty -Path 'HKCU:/Software/Microsoft/Windows/CurrentVersion/Internet Settings' -Name ProxyServer -ErrorAction Ignore + Remove-ItemProperty -Path 'HKCU:/Software/Microsoft/Windows/CurrentVersion/Internet Settings' -Name ProxyEnable -ErrorAction Ignore + $env:https_proxy = $null + } + + Context "Configured for command (<Command>)" -ForEach $CommandsToTest { + BeforeAll { + $Output = Invoke-Choco $Command @arguments @ExtraArguments --debug --verbose --noop + } + + It "Should output the correct Proxy setting" { + $Output.String | Should -Not -MatchExactly "Proxy\.Location='$SystemSet'" + $Output.String | Should -Not -MatchExactly "Proxy\.Location" + } + } +} diff --git a/tests/chocolatey-tests/features/PythonSource.Tests.ps1 b/tests/chocolatey-tests/features/PythonSource.Tests.ps1 index ce9eb4a314..d6323c7cbf 100644 --- a/tests/chocolatey-tests/features/PythonSource.Tests.ps1 +++ b/tests/chocolatey-tests/features/PythonSource.Tests.ps1 @@ -1,12 +1,13 @@ Import-Module helpers/common-helpers # This is skipped when not run in CI because it modifies the local system. -Describe "Python Source" -Tag Chocolatey, UpgradeCommand, PythonSource -Skip:(-not $env:TEST_KITCHEN) { +# This is skipped on Proxy as Python needs to reach out to pypi which our proxy server does not allow. +Describe "Python Source" -Tag Chocolatey, UpgradeCommand, PythonSource, ProxySkip -Skip:(-not $env:TEST_KITCHEN) { BeforeAll { Initialize-ChocolateyTestInstall New-ChocolateyInstallSnapshot - # TODO: Internalize Python and most dependencies. (KB perhaps not internalized due to excessive size...) - $null = Invoke-Choco install python3 --source https://community.chocolatey.org/api/v2/ + Enable-ChocolateySource -Name hermes-setup + $null = Invoke-Choco install python3 } AfterAll { diff --git a/tests/helpers/common-helpers.psm1 b/tests/helpers/common-helpers.psm1 index f17f9b7d0a..b10e13b917 100644 --- a/tests/helpers/common-helpers.psm1 +++ b/tests/helpers/common-helpers.psm1 @@ -10,7 +10,7 @@ $script:snapshotStack = @() $script:ChocoCommandHeaders = @{ "List" = @("Name", "Version") "PinList" = @("Name", "Version") - "SourceList" = @("Name", "Url", "1", "2", "3", "Priority", "BypassProxy", "SelfService", "AdminOnly") + "SourceList" = @("Name", "Url", "Disabled", "Username", "Certificate", "Priority", "BypassProxy", "SelfService", "AdminOnly") "Feature" = @("Name", "State", "Description") } $script:features = $null diff --git a/tests/helpers/common/Chocolatey/Invoke-Choco.ps1 b/tests/helpers/common/Chocolatey/Invoke-Choco.ps1 index cf6799987a..8ee4e7bb34 100644 --- a/tests/helpers/common/Chocolatey/Invoke-Choco.ps1 +++ b/tests/helpers/common/Chocolatey/Invoke-Choco.ps1 @@ -33,9 +33,11 @@ $remainingArguments ) - } end { + $stopwatch = [System.Diagnostics.Stopwatch]::new() + $stopwatch.Start() + $output = if ($PipelineInput) { $PipelineInput | & $chocoPath @arguments } @@ -43,18 +45,30 @@ & $chocoPath @arguments } + $CommandExitCode = $LastExitCode + $stopwatch.Stop() + # We do not use env:ChocolateyInstall here as it is not guaranteed due to snapshots. + # Saving into the default Chocolatey install location as .log so Test Kitchen can pick up the file. + [PSCustomObject]@{ + Date = Get-Date -Format 'o' + Duration = $stopwatch.Elapsed + Invocation = ($MyInvocation.PositionMessage -split "`r`n")[0] + ExitCode = $CommandExitCode + } | Export-Csv -Path $env:ALLUSERSPROFILE/chocolatey/logs/testInvocations.log -NoTypeInformation -Append + [PSCustomObject]@{ # We trim all the lines, so we do not take into account # trimming the lines when asserting, and that extra whitespace # is not considered in our assertions. - Lines = if ($output) { + Lines = if ($output) { $output.Trim() } else { @() } - String = $output -join "`r`n" - ExitCode = $LastExitCode + String = $output -join "`r`n" + ExitCode = $CommandExitCode + Duration = $stopwatch.Elapsed } } } diff --git a/tests/helpers/common/Chocolatey/Test-ChocolateyVersionEqualOrHigherThan.ps1 b/tests/helpers/common/Chocolatey/Test-ChocolateyVersionEqualOrHigherThan.ps1 index 99bb7104d0..cd6cc888a1 100644 --- a/tests/helpers/common/Chocolatey/Test-ChocolateyVersionEqualOrHigherThan.ps1 +++ b/tests/helpers/common/Chocolatey/Test-ChocolateyVersionEqualOrHigherThan.ps1 @@ -1,4 +1,4 @@ -function Test-ChocolateyVersionEqualOrHigherThan { +function Test-ChocolateyVersionEqualOrHigherThan { <# .Synopsis Helper function that can be used to assert whether the current @@ -10,7 +10,9 @@ param( [NuGet.Versioning.NuGetVersion]$Version ) - $installedVersion = ((Invoke-Choco list -r).Lines | ConvertFrom-ChocolateyOutput -Command List | Where-Object Name -EQ 'chocolatey').Version + if (-not $script:ChocolateyInstalledVersion) { + $script:ChocolateyInstalledVersion = ((Invoke-Choco list -r).Lines | ConvertFrom-ChocolateyOutput -Command List | Where-Object Name -EQ 'chocolatey').Version + } - return Test-VersionEqualOrHigher -InstalledVersion $installedVersion -CompareVersion $Version + return Test-VersionEqualOrHigher -InstalledVersion $script:ChocolateyInstalledVersion -CompareVersion $Version } diff --git a/tests/helpers/common/Chocolatey/Test-HasNuGetV3Source.ps1 b/tests/helpers/common/Chocolatey/Test-HasNuGetV3Source.ps1 new file mode 100644 index 0000000000..1071aead61 --- /dev/null +++ b/tests/helpers/common/Chocolatey/Test-HasNuGetV3Source.ps1 @@ -0,0 +1,10 @@ +function Test-HasNuGetV3Source { + [CmdletBinding()] + [OutputType([boolean])] + param( + ) + if (-not $script:ChocolateyEnabledSources) { + $script:ChocolateyEnabledSources = (Invoke-Choco source list --limitoutput).Lines | ConvertFrom-ChocolateyOutput -Command SourceList | Where-Object Disabled -NE $true + } + $null -ne ($script:ChocolateyEnabledSources | Where-Object Url -match 'index\.json') +} diff --git a/tests/helpers/common/Chocolatey/Test-PackageIsEqualOrHigher.ps1 b/tests/helpers/common/Chocolatey/Test-PackageIsEqualOrHigher.ps1 index e2549a0f77..8b15cee517 100644 --- a/tests/helpers/common/Chocolatey/Test-PackageIsEqualOrHigher.ps1 +++ b/tests/helpers/common/Chocolatey/Test-PackageIsEqualOrHigher.ps1 @@ -1,4 +1,3 @@ -# TODO: Should we cache the result function Test-PackageIsEqualOrHigher { [CmdletBinding()] [OutputType([boolean])] @@ -9,12 +8,15 @@ function Test-PackageIsEqualOrHigher { [NuGet.Versioning.NuGetVersion]$Version, [switch]$AllowMissingPackage ) - - $package = (Invoke-Choco list --limitoutput).Lines | + if (-not $script:ChocolateyInstalledPackages) { + $script:ChocolateyInstalledPackages = (Invoke-Choco list --limitoutput).Lines | Where-Object { $_ -notmatch 'please upgrade' } | - ConvertFrom-ChocolateyOutput -Command List | - Where-Object Name -EQ $PackageName - if (!$package) { + ConvertFrom-ChocolateyOutput -Command List + } + + $package = $script:ChocolateyInstalledPackages | Where-Object Name -EQ $PackageName + + if (-not $package) { return $AllowMissingPackage.IsPresent } diff --git a/tests/packages/nonnormalizedversions/nonnormalizedversions.004.0.01.0.nupkg b/tests/packages/nonnormalizedversions/nonnormalizedversions.004.0.01.0.nupkg new file mode 100644 index 0000000000..17a790d21e Binary files /dev/null and b/tests/packages/nonnormalizedversions/nonnormalizedversions.004.0.01.0.nupkg differ diff --git a/tests/packages/nonnormalizedversions/nonnormalizedversions.01.0.0.0.nupkg b/tests/packages/nonnormalizedversions/nonnormalizedversions.01.0.0.0.nupkg new file mode 100644 index 0000000000..413f40031e Binary files /dev/null and b/tests/packages/nonnormalizedversions/nonnormalizedversions.01.0.0.0.nupkg differ diff --git a/update-nuget-client.ps1 b/update-nuget-client.ps1 index 061cf7ae13..8cb964eb63 100644 --- a/update-nuget-client.ps1 +++ b/update-nuget-client.ps1 @@ -27,8 +27,8 @@ if ($build -or !(Test-Path "$sourceLocation\artifacts")) { "Configuring NuGet.Client repository dependencies" #.\configure.ps1 - "Calling .\build.ps1 -CI -SkipUnitTest -Configuration Debug -BuildNumber $buildNumber -ReleaseLabel 'zlocal'" - .\build.ps1 -CI -SkipUnitTest -Configuration Debug -BuildNumber $buildNumber -ReleaseLabel 'zlocal' + "Calling .\build.ps1 -CI -SkipUnitTest -ChocolateyBuild -Configuration Debug -BuildNumber $buildNumber -ReleaseLabel 'zlocal'" + .\build.ps1 -CI -SkipUnitTest -ChocolateyBuild -Configuration Debug -BuildNumber $buildNumber -ReleaseLabel 'zlocal' } Get-ChildItem "$thisLocation\src\packages\Chocolatey.NuGet.*" | ForEach-Object {