diff --git a/.globalconfig b/.globalconfig index c22cb5a96c8..f0cc41c388e 100644 --- a/.globalconfig +++ b/.globalconfig @@ -1,7 +1,8 @@ is_global = true # CA1000: Do not declare static members on generic types -dotnet_diagnostic.CA1000.severity = silent +dotnet_diagnostic.CA1000.severity = warning +dotnet_code_quality.ca1000.api_surface = all # CA1001: Types that own disposable fields should be disposable dotnet_diagnostic.CA1001.severity = silent @@ -23,7 +24,8 @@ dotnet_diagnostic.CA1008.severity = none dotnet_diagnostic.CA1010.severity = silent # CA1012: Abstract types should not have public constructors -dotnet_diagnostic.CA1012.severity = none +dotnet_diagnostic.CA1012.severity = warning +dotnet_code_quality.ca1012.api_surface = all # CA1014: Mark assemblies with CLSCompliant dotnet_diagnostic.CA1014.severity = none @@ -128,7 +130,7 @@ dotnet_diagnostic.CA1063.severity = none dotnet_diagnostic.CA1064.severity = none # CA1065: Do not raise exceptions in unexpected locations -dotnet_diagnostic.CA1065.severity = none +dotnet_diagnostic.CA1065.severity = warning # CA1066: Implement IEquatable when overriding Object.Equals dotnet_diagnostic.CA1066.severity = none @@ -266,7 +268,7 @@ dotnet_diagnostic.CA1814.severity = none dotnet_diagnostic.CA1815.severity = none # CA1816: Dispose methods should call SuppressFinalize -dotnet_diagnostic.CA1816.severity = suggestion +dotnet_diagnostic.CA1816.severity = warning # CA1819: Properties should not return arrays dotnet_diagnostic.CA1819.severity = none @@ -278,7 +280,8 @@ dotnet_diagnostic.CA1820.severity = none dotnet_diagnostic.CA1821.severity = warning # CA1822: Mark members as static -dotnet_diagnostic.CA1822.severity = suggestion +dotnet_diagnostic.CA1822.severity = warning +dotnet_code_quality.ca1822.api_surface = private # CA1823: Avoid unused private fields dotnet_diagnostic.CA1823.severity = none @@ -389,7 +392,7 @@ dotnet_diagnostic.CA2207.severity = warning dotnet_diagnostic.CA2208.severity = suggestion # CA2211: Non-constant fields should not be visible -dotnet_diagnostic.CA2211.severity = suggestion +dotnet_diagnostic.CA2211.severity = warning # CA2213: Disposable fields should be disposed dotnet_diagnostic.CA2213.severity = none @@ -401,7 +404,7 @@ dotnet_diagnostic.CA2214.severity = none dotnet_diagnostic.CA2215.severity = silent # CA2216: Disposable types should declare finalizer -dotnet_diagnostic.CA2216.severity = none +dotnet_diagnostic.CA2216.severity = warning # CA2217: Do not mark enums with FlagsAttribute dotnet_diagnostic.CA2217.severity = none @@ -818,7 +821,7 @@ dotnet_diagnostic.IDE0029.severity = silent dotnet_diagnostic.IDE0030.severity = silent # IDE0031: UseNullPropagation -dotnet_diagnostic.IDE0031.severity = silent +dotnet_diagnostic.IDE0031.severity = warning # IDE0032: UseAutoProperty dotnet_diagnostic.IDE0032.severity = silent @@ -848,7 +851,7 @@ dotnet_diagnostic.IDE0039.severity = silent dotnet_diagnostic.IDE0040.severity = warning # IDE0041: UseIsNullCheck -dotnet_diagnostic.IDE0041.severity = silent +dotnet_diagnostic.IDE0041.severity = warning # IDE0042: UseDeconstruction dotnet_diagnostic.IDE0042.severity = silent @@ -947,10 +950,10 @@ dotnet_diagnostic.IDE0072.severity = silent dotnet_diagnostic.IDE0073.severity = suggestion # IDE0074: UseCoalesceCompoundAssignment -dotnet_diagnostic.IDE0074.severity = silent +dotnet_diagnostic.IDE0074.severity = warning # IDE0075: SimplifyConditionalExpression -dotnet_diagnostic.IDE0075.severity = silent +dotnet_diagnostic.IDE0075.severity = warning # IDE0076: InvalidSuppressMessageAttribute dotnet_diagnostic.IDE0076.severity = silent @@ -971,7 +974,7 @@ dotnet_diagnostic.IDE0080.severity = silent dotnet_diagnostic.IDE0081.severity = silent # IDE0082: ConvertTypeOfToNameOf -dotnet_diagnostic.IDE0082.severity = silent +dotnet_diagnostic.IDE0082.severity = warning # IDE0083: UseNotPattern dotnet_diagnostic.IDE0083.severity = silent @@ -1002,3 +1005,549 @@ dotnet_diagnostic.IDE1007.severity = silent # IDE1008: UnboundConstructor dotnet_diagnostic.IDE1008.severity = silent + +# SA0001: XML comment analysis disabled +dotnet_diagnostic.SA0001.severity = none + +# SA0002: Invalid settings file +dotnet_diagnostic.SA0002.severity = none + +# SA1000: Keywords should be spaced correctly +dotnet_diagnostic.SA1000.severity = warning + +# SA1001: Commas should be spaced correctly +dotnet_diagnostic.SA1001.severity = none + +# SA1002: Semicolons should be spaced correctly +dotnet_diagnostic.SA1002.severity = warning + +# SA1003: Symbols should be spaced correctly +dotnet_diagnostic.SA1003.severity = none + +# SA1004: Documentation lines should begin with single space +dotnet_diagnostic.SA1004.severity = none + +# SA1005: Single line comments should begin with single space +dotnet_diagnostic.SA1005.severity = none + +# SA1006: Preprocessor keywords should not be preceded by space +dotnet_diagnostic.SA1006.severity = warning + +# SA1007: Operator keyword should be followed by space +dotnet_diagnostic.SA1007.severity = warning + +# SA1008: Opening parenthesis should be spaced correctly +dotnet_diagnostic.SA1008.severity = none + +# SA1009: Closing parenthesis should be spaced correctly +dotnet_diagnostic.SA1009.severity = none + +# SA1010: Opening square brackets should be spaced correctly +dotnet_diagnostic.SA1010.severity = none + +# SA1011: Closing square brackets should be spaced correctly +dotnet_diagnostic.SA1011.severity = none + +# SA1012: Opening braces should be spaced correctly +dotnet_diagnostic.SA1012.severity = none + +# SA1013: Closing braces should be spaced correctly +dotnet_diagnostic.SA1013.severity = none + +# SA1014: Opening generic brackets should be spaced correctly +dotnet_diagnostic.SA1014.severity = none + +# SA1015: Closing generic brackets should be spaced correctly +dotnet_diagnostic.SA1015.severity = none + +# SA1016: Opening attribute brackets should be spaced correctly +dotnet_diagnostic.SA1016.severity = none + +# SA1017: Closing attribute brackets should be spaced correctly +dotnet_diagnostic.SA1017.severity = none + +# SA1018: Nullable type symbols should be spaced correctly +dotnet_diagnostic.SA1018.severity = none + +# SA1019: Member access symbols should be spaced correctly +dotnet_diagnostic.SA1019.severity = none + +# SA1020: Increment decrement symbols should be spaced correctly +dotnet_diagnostic.SA1020.severity = none + +# SA1021: Negative signs should be spaced correctly +dotnet_diagnostic.SA1021.severity = none + +# SA1022: Positive signs should be spaced correctly +dotnet_diagnostic.SA1022.severity = none + +# SA1023: Dereference and access of symbols should be spaced correctly +dotnet_diagnostic.SA1023.severity = none + +# SA1024: Colons Should Be Spaced Correctly +dotnet_diagnostic.SA1024.severity = none + +# SA1025: Code should not contain multiple whitespace in a row +dotnet_diagnostic.SA1025.severity = none + +# SA1026: Code should not contain space after new or stackalloc keyword in implicitly typed array allocation +dotnet_diagnostic.SA1026.severity = none + +# SA1027: Use tabs correctly +dotnet_diagnostic.SA1027.severity = none + +# SA1028: Code should not contain trailing whitespace +dotnet_diagnostic.SA1028.severity = none + +# SA1100: Do not prefix calls with base unless local implementation exists +dotnet_diagnostic.SA1100.severity = none + +# SA1101: Prefix local calls with this +dotnet_diagnostic.SA1101.severity = none + +# SA1102: Query clause should follow previous clause +dotnet_diagnostic.SA1102.severity = none + +# SA1103: Query clauses should be on separate lines or all on one line +dotnet_diagnostic.SA1103.severity = none + +# SA1104: Query clause should begin on new line when previous clause spans multiple lines +dotnet_diagnostic.SA1104.severity = none + +# SA1105: Query clauses spanning multiple lines should begin on own line +dotnet_diagnostic.SA1105.severity = none + +# SA1106: Code should not contain empty statements +dotnet_diagnostic.SA1106.severity = warning + +# SA1107: Code should not contain multiple statements on one line +dotnet_diagnostic.SA1107.severity = none + +# SA1108: Block statements should not contain embedded comments +dotnet_diagnostic.SA1108.severity = none + +# SA1110: Opening parenthesis or bracket should be on declaration line +dotnet_diagnostic.SA1110.severity = none + +# SA1111: Closing parenthesis should be on line of last parameter +dotnet_diagnostic.SA1111.severity = none + +# SA1112: Closing parenthesis should be on line of opening parenthesis +dotnet_diagnostic.SA1112.severity = none + +# SA1113: Comma should be on the same line as previous parameter +dotnet_diagnostic.SA1113.severity = none + +# SA1114: Parameter list should follow declaration +dotnet_diagnostic.SA1114.severity = none + +# SA1115: Parameter should follow comma +dotnet_diagnostic.SA1115.severity = none + +# SA1116: Split parameters should start on line after declaration +dotnet_diagnostic.SA1116.severity = none + +# SA1117: Parameters should be on same line or separate lines +dotnet_diagnostic.SA1117.severity = none + +# SA1118: Parameter should not span multiple lines +dotnet_diagnostic.SA1118.severity = none + +# SA1119: Statement should not use unnecessary parenthesis +dotnet_diagnostic.SA1119.severity = none + +# SA1120: Comments should contain text +dotnet_diagnostic.SA1120.severity = none + +# SA1121: Use built-in type alias +dotnet_diagnostic.SA1121.severity = none + +# SA1122: Use string.Empty for empty strings +dotnet_diagnostic.SA1122.severity = warning + +# SA1123: Do not place regions within elements +dotnet_diagnostic.SA1123.severity = none + +# SA1124: Do not use regions +dotnet_diagnostic.SA1124.severity = none + +# SA1125: Use shorthand for nullable types +dotnet_diagnostic.SA1125.severity = none + +# SA1127: Generic type constraints should be on their own line +dotnet_diagnostic.SA1127.severity = none + +# SA1128: Put constructor initializers on their own line +dotnet_diagnostic.SA1128.severity = none + +# SA1129: Do not use default value type constructor +dotnet_diagnostic.SA1129.severity = none + +# SA1130: Use lambda syntax +dotnet_diagnostic.SA1130.severity = none + +# SA1131: Use readable conditions +dotnet_diagnostic.SA1131.severity = warning + +# SA1132: Do not combine fields +dotnet_diagnostic.SA1132.severity = none + +# SA1133: Do not combine attributes +dotnet_diagnostic.SA1133.severity = none + +# SA1134: Attributes should not share line +dotnet_diagnostic.SA1134.severity = none + +# SA1135: Using directives should be qualified +dotnet_diagnostic.SA1135.severity = none + +# SA1136: Enum values should be on separate lines +dotnet_diagnostic.SA1136.severity = none + +# SA1137: Elements should have the same indentation +dotnet_diagnostic.SA1137.severity = none + +# SA1139: Use literal suffix notation instead of casting +dotnet_diagnostic.SA1139.severity = none + +# SA1141: Use tuple syntax +dotnet_diagnostic.SA1141.severity = none + +# SA1142: Refer to tuple fields by name +dotnet_diagnostic.SA1142.severity = none + +# SA1200: Using directives should be placed correctly +dotnet_diagnostic.SA1200.severity = none + +# SA1201: Elements should appear in the correct order +dotnet_diagnostic.SA1201.severity = none + +# SA1202: Elements should be ordered by access +dotnet_diagnostic.SA1202.severity = none + +# SA1203: Constants should appear before fields +dotnet_diagnostic.SA1203.severity = none + +# SA1204: Static elements should appear before instance elements +dotnet_diagnostic.SA1204.severity = none + +# SA1205: Partial elements should declare access +dotnet_diagnostic.SA1205.severity = none + +# SA1206: Declaration keywords should follow order +dotnet_diagnostic.SA1206.severity = none + +# SA1207: Protected should come before internal +dotnet_diagnostic.SA1207.severity = none + +# SA1208: System using directives should be placed before other using directives +dotnet_diagnostic.SA1208.severity = none + +# SA1209: Using alias directives should be placed after other using directives +dotnet_diagnostic.SA1209.severity = none + +# SA1210: Using directives should be ordered alphabetically by namespace +dotnet_diagnostic.SA1210.severity = none + +# SA1211: Using alias directives should be ordered alphabetically by alias name +dotnet_diagnostic.SA1211.severity = none + +# SA1212: Property accessors should follow order +dotnet_diagnostic.SA1212.severity = warning + +# SA1213: Event accessors should follow order +dotnet_diagnostic.SA1213.severity = none + +# SA1214: Readonly fields should appear before non-readonly fields +dotnet_diagnostic.SA1214.severity = none + +# SA1216: Using static directives should be placed at the correct location +dotnet_diagnostic.SA1216.severity = none + +# SA1217: Using static directives should be ordered alphabetically +dotnet_diagnostic.SA1217.severity = none + +# SA1300: Element should begin with upper-case letter +dotnet_diagnostic.SA1300.severity = none + +# SA1302: Interface names should begin with I +dotnet_diagnostic.SA1302.severity = none + +# SA1303: Const field names should begin with upper-case letter +dotnet_diagnostic.SA1303.severity = none + +# SA1304: Non-private readonly fields should begin with upper-case letter +dotnet_diagnostic.SA1304.severity = none + +# SA1305: Field names should not use Hungarian notation +dotnet_diagnostic.SA1305.severity = none + +# SA1306: Field names should begin with lower-case letter +dotnet_diagnostic.SA1306.severity = none + +# SA1307: Accessible fields should begin with upper-case letter +dotnet_diagnostic.SA1307.severity = none + +# SA1308: Variable names should not be prefixed +dotnet_diagnostic.SA1308.severity = none + +# SA1309: Field names should not begin with underscore +dotnet_diagnostic.SA1309.severity = none + +# SA1310: Field names should not contain underscore +dotnet_diagnostic.SA1310.severity = none + +# SA1311: Static readonly fields should begin with upper-case letter +dotnet_diagnostic.SA1311.severity = none + +# SA1312: Variable names should begin with lower-case letter +dotnet_diagnostic.SA1312.severity = none + +# SA1313: Parameter names should begin with lower-case letter +dotnet_diagnostic.SA1313.severity = none + +# SA1314: Type parameter names should begin with T +dotnet_diagnostic.SA1314.severity = none + +# SA1316: Tuple element names should use correct casing +dotnet_diagnostic.SA1316.severity = none + +# SA1400: Access modifier should be declared +dotnet_diagnostic.SA1400.severity = none + +# SA1401: Fields should be private +dotnet_diagnostic.SA1401.severity = none + +# SA1402: File may only contain a single type +dotnet_diagnostic.SA1402.severity = none + +# SA1403: File may only contain a single namespace +dotnet_diagnostic.SA1403.severity = none + +# SA1404: Code analysis suppression should have justification +dotnet_diagnostic.SA1404.severity = none + +# SA1405: Debug.Assert should provide message text +dotnet_diagnostic.SA1405.severity = none + +# SA1406: Debug.Fail should provide message text +dotnet_diagnostic.SA1406.severity = none + +# SA1407: Arithmetic expressions should declare precedence +dotnet_diagnostic.SA1407.severity = none + +# SA1408: Conditional expressions should declare precedence +dotnet_diagnostic.SA1408.severity = none + +# SA1410: Remove delegate parenthesis when possible +dotnet_diagnostic.SA1410.severity = none + +# SA1411: Attribute constructor should not use unnecessary parenthesis +dotnet_diagnostic.SA1411.severity = none + +# SA1412: Store files as UTF-8 with byte order mark +dotnet_diagnostic.SA1412.severity = none + +# SA1413: Use trailing comma in multi-line initializers +dotnet_diagnostic.SA1413.severity = none + +# SA1414: Tuple types in signatures should have element names +dotnet_diagnostic.SA1414.severity = none + +# SA1500: Braces for multi-line statements should not share line +dotnet_diagnostic.SA1500.severity = none + +# SA1501: Statement should not be on a single line +dotnet_diagnostic.SA1501.severity = none + +# SA1502: Element should not be on a single line +dotnet_diagnostic.SA1502.severity = none + +# SA1503: Braces should not be omitted +dotnet_diagnostic.SA1503.severity = none + +# SA1504: All accessors should be single-line or multi-line +dotnet_diagnostic.SA1504.severity = none + +# SA1505: Opening braces should not be followed by blank line +dotnet_diagnostic.SA1505.severity = none + +# SA1506: Element documentation headers should not be followed by blank line +dotnet_diagnostic.SA1506.severity = none + +# SA1507: Code should not contain multiple blank lines in a row +dotnet_diagnostic.SA1507.severity = warning + +# SA1508: Closing braces should not be preceded by blank line +dotnet_diagnostic.SA1508.severity = none + +# SA1509: Opening braces should not be preceded by blank line +dotnet_diagnostic.SA1509.severity = none + +# SA1510: Chained statement blocks should not be preceded by blank line +dotnet_diagnostic.SA1510.severity = none + +# SA1511: While-do footer should not be preceded by blank line +dotnet_diagnostic.SA1511.severity = none + +# SA1512: Single-line comments should not be followed by blank line +dotnet_diagnostic.SA1512.severity = none + +# SA1513: Closing brace should be followed by blank line +dotnet_diagnostic.SA1513.severity = none + +# SA1514: Element documentation header should be preceded by blank line +dotnet_diagnostic.SA1514.severity = none + +# SA1515: Single-line comment should be preceded by blank line +dotnet_diagnostic.SA1515.severity = none + +# SA1516: Elements should be separated by blank line +dotnet_diagnostic.SA1516.severity = warning + +# SA1517: Code should not contain blank lines at start of file +dotnet_diagnostic.SA1517.severity = warning + +# SA1518: Use line endings correctly at end of file +dotnet_diagnostic.SA1518.severity = warning + +# SA1519: Braces should not be omitted from multi-line child statement +dotnet_diagnostic.SA1519.severity = none + +# SA1520: Use braces consistently +dotnet_diagnostic.SA1520.severity = none + +# SA1600: Elements should be documented +dotnet_diagnostic.SA1600.severity = none + +# SA1601: Partial elements should be documented +dotnet_diagnostic.SA1601.severity = none + +# SA1602: Enumeration items should be documented +dotnet_diagnostic.SA1602.severity = none + +# SA1604: Element documentation should have summary +dotnet_diagnostic.SA1604.severity = none + +# SA1605: Partial element documentation should have summary +dotnet_diagnostic.SA1605.severity = none + +# SA1606: Element documentation should have summary text +dotnet_diagnostic.SA1606.severity = none + +# SA1607: Partial element documentation should have summary text +dotnet_diagnostic.SA1607.severity = none + +# SA1608: Element documentation should not have default summary +dotnet_diagnostic.SA1608.severity = none + +# SA1609: Property documentation should have value +dotnet_diagnostic.SA1609.severity = none + +# SA1610: Property documentation should have value text +dotnet_diagnostic.SA1610.severity = none + +# SA1611: Element parameters should be documented +dotnet_diagnostic.SA1611.severity = none + +# SA1612: Element parameter documentation should match element parameters +dotnet_diagnostic.SA1612.severity = none + +# SA1613: Element parameter documentation should declare parameter name +dotnet_diagnostic.SA1613.severity = none + +# SA1614: Element parameter documentation should have text +dotnet_diagnostic.SA1614.severity = none + +# SA1615: Element return value should be documented +dotnet_diagnostic.SA1615.severity = none + +# SA1616: Element return value documentation should have text +dotnet_diagnostic.SA1616.severity = none + +# SA1617: Void return value should not be documented +dotnet_diagnostic.SA1617.severity = none + +# SA1618: Generic type parameters should be documented +dotnet_diagnostic.SA1618.severity = none + +# SA1619: Generic type parameters should be documented partial class +dotnet_diagnostic.SA1619.severity = none + +# SA1620: Generic type parameter documentation should match type parameters +dotnet_diagnostic.SA1620.severity = none + +# SA1621: Generic type parameter documentation should declare parameter name +dotnet_diagnostic.SA1621.severity = none + +# SA1622: Generic type parameter documentation should have text +dotnet_diagnostic.SA1622.severity = none + +# SA1623: Property summary documentation should match accessors +dotnet_diagnostic.SA1623.severity = none + +# SA1624: Property summary documentation should omit accessor with restricted access +dotnet_diagnostic.SA1624.severity = none + +# SA1625: Element documentation should not be copied and pasted +dotnet_diagnostic.SA1625.severity = none + +# SA1626: Single-line comments should not use documentation style slashes +dotnet_diagnostic.SA1626.severity = none + +# SA1627: Documentation text should not be empty +dotnet_diagnostic.SA1627.severity = none + +# SA1629: Documentation text should end with a period +dotnet_diagnostic.SA1629.severity = none + +# SA1633: File should have header +dotnet_diagnostic.SA1633.severity = none + +# SA1634: File header should show copyright +dotnet_diagnostic.SA1634.severity = none + +# SA1635: File header should have copyright text +dotnet_diagnostic.SA1635.severity = none + +# SA1636: File header copyright text should match +dotnet_diagnostic.SA1636.severity = none + +# SA1637: File header should contain file name +dotnet_diagnostic.SA1637.severity = none + +# SA1638: File header file name documentation should match file name +dotnet_diagnostic.SA1638.severity = none + +# SA1639: File header should have summary +dotnet_diagnostic.SA1639.severity = none + +# SA1640: File header should have valid company text +dotnet_diagnostic.SA1640.severity = none + +# SA1641: File header company name text should match +dotnet_diagnostic.SA1641.severity = none + +# SA1642: Constructor summary documentation should begin with standard text +dotnet_diagnostic.SA1642.severity = none + +# SA1643: Destructor summary documentation should begin with standard text +dotnet_diagnostic.SA1643.severity = warning + +# SA1648: inheritdoc should be used with inheriting class +dotnet_diagnostic.SA1648.severity = none + +# SA1649: File name should match first type name +dotnet_diagnostic.SA1649.severity = none + +# SA1651: Do not use placeholder elements +dotnet_diagnostic.SA1651.severity = none + +# SX1101: Do not prefix local calls with 'this.' +dotnet_diagnostic.SX1101.severity = none + +# SX1309: Field names should begin with underscore +dotnet_diagnostic.SX1309.severity = none + +# SX1309S: Static field names should begin with underscore +dotnet_diagnostic.SX1309S.severity = none diff --git a/Analyzers.props b/Analyzers.props new file mode 100644 index 00000000000..d0b16622b8c --- /dev/null +++ b/Analyzers.props @@ -0,0 +1,5 @@ + + + + + diff --git a/CHANGELOG/preview.md b/CHANGELOG/preview.md index 2e89bcd37df..afc36040313 100644 --- a/CHANGELOG/preview.md +++ b/CHANGELOG/preview.md @@ -1,5 +1,188 @@ # Current preview release +## [7.2.0-preview.2] - 2020-12-15 + +### Breaking Changes + +- Improve detection of mutable value types (#12495) (Thanks @vexx32!) +- Ensure `-PipelineVariable` is set for all output from script cmdlets (#12766) (Thanks @vexx32!) + +### Experimental Features + +- `PSAnsiRendering`: Enable ANSI formatting via `$PSStyle` and support suppressing ANSI output (#13758) + +### Performance + +- Optimize `IEnumerable` variant of replace operator (#14221) (Thanks @iSazonov!) +- Refactor multiply operation for better performance in two `Microsoft.PowerShell.Commands.Utility` methods (#14148) (Thanks @xtqqczze!) +- Use `Environment.TickCount64` instead of `Datetime.Now` as the random seed for AppLocker test file content (#14283) (Thanks @iSazonov!) +- Avoid unnecessary array allocations when searching in GAC (#14291) (Thanks @xtqqczze!) +- Use `OrdinalIgnoreCase` in `CommandLineParser` (#14303) (Thanks @iSazonov!) +- Use `StringComparison.Ordinal` instead of `StringComparison.CurrentCulture` (#14298) (Thanks @iSazonov!) +- Avoid creating instances of the generated delegate helper class in `-replace` implementation (#14128) + +### General Cmdlet Updates and Fixes + +- Write better error message if config file is broken (#13496) (Thanks @iSazonov!) +- Make AppLocker Enforce mode take precedence over UMCI Audit mode (#14353) +- Add `-SkipLimitCheck` switch to `Import-PowerShellDataFile` (#13672) +- Restrict `New-Object` in NoLanguage mode under lock down (#14140) (Thanks @krishnayalavarthi!) +- The `-Stream` parameter now works with directories (#13941) (Thanks @kyanha!) +- Avoid an exception if file system does not support reparse points (#13634) (Thanks @iSazonov!) +- Enable `CA1012`: Abstract types should not have public constructors (#13940) (Thanks @xtqqczze!) +- Enable `SA1212`: Property accessors should follow order (#14051) (Thanks @xtqqczze!) + +### Code Cleanup + +
+ + + +

We thank the following contributors!

+

@xtqqczze, @matthewjdegarmo, @powercode, @Gimly

+ +
+ + + +
+ +### Tools + +- Fixing formatting in `Reset-PWSHSystemPath.ps1` (#13689) (Thanks @dgoldman-msft!) + +### Tests + +- Reinstate `Test-Connection` tests (#13324) +- Update markdown test packages with security fixes (#14145) + +### Build and Packaging Improvements + +
+ + + +
+ +### Documentation and Help Content + +- Fix example `nuget.config` (#14349) +- Fix a broken link in Code Guidelines doc (#14314) (Thanks @iSazonov!) + +[7.2.0-preview.2]: https://github.com/PowerShell/PowerShell/compare/v7.2.0-preview.1...v7.2.0-preview.2 + ## [7.2.0-preview.1] - 2020-11-17 ### Engine Updates and Fixes diff --git a/PowerShell.Common.props b/PowerShell.Common.props index e03bf2cd1a9..2e9f8e6f63b 100644 --- a/PowerShell.Common.props +++ b/PowerShell.Common.props @@ -1,4 +1,5 @@ + - - - - - diff --git a/src/Microsoft.PowerShell.MarkdownRender/ParagraphBlockRenderer.cs b/src/Microsoft.PowerShell.MarkdownRender/ParagraphBlockRenderer.cs deleted file mode 100644 index 3b854cb2189..00000000000 --- a/src/Microsoft.PowerShell.MarkdownRender/ParagraphBlockRenderer.cs +++ /dev/null @@ -1,22 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -using Markdig.Syntax; - -namespace Microsoft.PowerShell.MarkdownRender -{ - /// - /// Renderer for adding VT100 escape sequences for paragraphs. - /// - internal class ParagraphBlockRenderer : VT100ObjectRenderer - { - protected override void Write(VT100Renderer renderer, ParagraphBlock obj) - { - // Call the renderer for children, leaf inline or line breaks. - renderer.WriteChildren(obj.Inline); - - // Add new line at the end of the paragraph. - renderer.WriteLine(); - } - } -} diff --git a/src/Microsoft.PowerShell.MarkdownRender/QuoteBlockRenderer.cs b/src/Microsoft.PowerShell.MarkdownRender/QuoteBlockRenderer.cs deleted file mode 100644 index 7e0bda6bda8..00000000000 --- a/src/Microsoft.PowerShell.MarkdownRender/QuoteBlockRenderer.cs +++ /dev/null @@ -1,25 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -using Markdig.Syntax; - -namespace Microsoft.PowerShell.MarkdownRender -{ - /// - /// Renderer for adding VT100 escape sequences for quote blocks. - /// - internal class QuoteBlockRenderer : VT100ObjectRenderer - { - protected override void Write(VT100Renderer renderer, QuoteBlock obj) - { - // Iterate through each item and add the quote character before the content. - foreach (var item in obj) - { - renderer.Write(obj.QuoteChar).Write(" ").Write(item); - } - - // Add blank line after the quote block. - renderer.WriteLine(); - } - } -} diff --git a/src/Microsoft.PowerShell.MarkdownRender/VT100EscapeSequences.cs b/src/Microsoft.PowerShell.MarkdownRender/VT100EscapeSequences.cs deleted file mode 100644 index 311522ac0aa..00000000000 --- a/src/Microsoft.PowerShell.MarkdownRender/VT100EscapeSequences.cs +++ /dev/null @@ -1,478 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -using System; -using System.Management.Automation; - -namespace Microsoft.PowerShell.MarkdownRender -{ - /// - /// Enum to name all the properties of PSMarkdownOptionInfo. - /// - public enum MarkdownOptionInfoProperty - { - /// - /// Property name Header1. - /// - Header1, - - /// - /// Property name Header2. - /// - Header2, - - /// - /// Property name Header3. - /// - Header3, - - /// - /// Property name Header4. - /// - Header4, - - /// - /// Property name Header5. - /// - Header5, - - /// - /// Property name Header6. - /// - Header6, - - /// - /// Property name Code. - /// - Code, - - /// - /// Property name Link. - /// - Link, - - /// - /// Property name Image. - /// - Image, - - /// - /// Property name EmphasisBold. - /// - EmphasisBold, - - /// - /// Property name EmphasisItalics. - /// - EmphasisItalics - } - - /// - /// Class to represent color preference options for various Markdown elements. - /// - public sealed class PSMarkdownOptionInfo - { - private const char Esc = (char)0x1b; - private const string EndSequence = "[0m"; - - /// - /// Gets or sets current VT100 escape sequence for header 1. - /// - public string Header1 { get; set; } - - /// - /// Gets or sets current VT100 escape sequence for header 2. - /// - public string Header2 { get; set; } - - /// - /// Gets or sets current VT100 escape sequence for header 3. - /// - public string Header3 { get; set; } - - /// - /// Gets or sets current VT100 escape sequence for header 4. - /// - public string Header4 { get; set; } - - /// - /// Gets or sets current VT100 escape sequence for header 5. - /// - public string Header5 { get; set; } - - /// - /// Gets or sets current VT100 escape sequence for header 6. - /// - public string Header6 { get; set; } - - /// - /// Gets or sets current VT100 escape sequence for code inline and code blocks. - /// - public string Code { get; set; } - - /// - /// Gets or sets current VT100 escape sequence for links. - /// - public string Link { get; set; } - - /// - /// Gets or sets current VT100 escape sequence for images. - /// - public string Image { get; set; } - - /// - /// Gets or sets current VT100 escape sequence for bold text. - /// - public string EmphasisBold { get; set; } - - /// - /// Gets or sets current VT100 escape sequence for italics text. - /// - public string EmphasisItalics { get; set; } - - /// - /// Gets or sets a value indicating whether VT100 escape sequences should be added. Default it true. - /// - public bool EnableVT100Encoding { get; set; } - - /// - /// Get the property as an rendered escape sequence. - /// This is used by formatting system for displaying. - /// - /// Name of the property to get as escape sequence. - /// Specified property name as escape sequence. - public string AsEscapeSequence(MarkdownOptionInfoProperty propertyName) - { - switch (propertyName) - { - case MarkdownOptionInfoProperty.Header1: - return string.Concat(Esc, Header1, Header1, Esc, EndSequence); - - case MarkdownOptionInfoProperty.Header2: - return string.Concat(Esc, Header2, Header2, Esc, EndSequence); - - case MarkdownOptionInfoProperty.Header3: - return string.Concat(Esc, Header3, Header3, Esc, EndSequence); - - case MarkdownOptionInfoProperty.Header4: - return string.Concat(Esc, Header4, Header4, Esc, EndSequence); - - case MarkdownOptionInfoProperty.Header5: - return string.Concat(Esc, Header5, Header5, Esc, EndSequence); - - case MarkdownOptionInfoProperty.Header6: - return string.Concat(Esc, Header6, Header6, Esc, EndSequence); - - case MarkdownOptionInfoProperty.Code: - return string.Concat(Esc, Code, Code, Esc, EndSequence); - - case MarkdownOptionInfoProperty.Link: - return string.Concat(Esc, Link, Link, Esc, EndSequence); - - case MarkdownOptionInfoProperty.Image: - return string.Concat(Esc, Image, Image, Esc, EndSequence); - - case MarkdownOptionInfoProperty.EmphasisBold: - return string.Concat(Esc, EmphasisBold, EmphasisBold, Esc, EndSequence); - - case MarkdownOptionInfoProperty.EmphasisItalics: - return string.Concat(Esc, EmphasisItalics, EmphasisItalics, Esc, EndSequence); - - default: - break; - } - - return null; - } - - /// - /// Initializes a new instance of the class and sets dark as the default theme. - /// - public PSMarkdownOptionInfo() - { - SetDarkTheme(); - EnableVT100Encoding = true; - } - - private const string Header1Dark = "[7m"; - private const string Header2Dark = "[4;93m"; - private const string Header3Dark = "[4;94m"; - private const string Header4Dark = "[4;95m"; - private const string Header5Dark = "[4;96m"; - private const string Header6Dark = "[4;97m"; - private const string CodeDark = "[48;2;155;155;155;38;2;30;30;30m"; - private const string CodeMacOS = "[107;95m"; - private const string LinkDark = "[4;38;5;117m"; - private const string ImageDark = "[33m"; - private const string EmphasisBoldDark = "[1m"; - private const string EmphasisItalicsDark = "[36m"; - - private const string Header1Light = "[7m"; - private const string Header2Light = "[4;33m"; - private const string Header3Light = "[4;34m"; - private const string Header4Light = "[4;35m"; - private const string Header5Light = "[4;36m"; - private const string Header6Light = "[4;30m"; - private const string CodeLight = "[48;2;155;155;155;38;2;30;30;30m"; - private const string LinkLight = "[4;38;5;117m"; - private const string ImageLight = "[33m"; - private const string EmphasisBoldLight = "[1m"; - private const string EmphasisItalicsLight = "[36m"; - - /// - /// Set all preference for dark theme. - /// - public void SetDarkTheme() - { - Header1 = Header1Dark; - Header2 = Header2Dark; - Header3 = Header3Dark; - Header4 = Header4Dark; - Header5 = Header5Dark; - Header6 = Header6Dark; - Link = LinkDark; - Image = ImageDark; - EmphasisBold = EmphasisBoldDark; - EmphasisItalics = EmphasisItalicsDark; - SetCodeColor(isDarkTheme: true); - } - - /// - /// Set all preference for light theme. - /// - public void SetLightTheme() - { - Header1 = Header1Light; - Header2 = Header2Light; - Header3 = Header3Light; - Header4 = Header4Light; - Header5 = Header5Light; - Header6 = Header6Light; - Link = LinkLight; - Image = ImageLight; - EmphasisBold = EmphasisBoldLight; - EmphasisItalics = EmphasisItalicsLight; - SetCodeColor(isDarkTheme: false); - } - - private void SetCodeColor(bool isDarkTheme) - { - // MacOS terminal app does not support extended colors for VT100, so we special case for it. - Code = Platform.IsMacOS ? CodeMacOS : isDarkTheme ? CodeDark : CodeLight; - } - } - - /// - /// Class to represent default VT100 escape sequences. - /// - public class VT100EscapeSequences - { - private const char Esc = (char)0x1B; - - private readonly string endSequence = Esc + "[0m"; - - // For code blocks, [500@ make sure that the whole line has background color. - private const string LongBackgroundCodeBlock = "[500@"; - - private readonly PSMarkdownOptionInfo options; - - /// - /// Initializes a new instance of the class. - /// - /// PSMarkdownOptionInfo object to initialize with. - public VT100EscapeSequences(PSMarkdownOptionInfo optionInfo) - { - if (optionInfo == null) - { - throw new ArgumentNullException(nameof(optionInfo)); - } - - options = optionInfo; - } - - /// - /// Class to represent default VT100 escape sequences. - /// - /// Text of the header to format. - /// Formatted Header 1 string. - public string FormatHeader1(string headerText) - { - return FormatHeader(headerText, options.Header1); - } - - /// - /// Class to represent default VT100 escape sequences. - /// - /// Text of the header to format. - /// Formatted Header 2 string. - public string FormatHeader2(string headerText) - { - return FormatHeader(headerText, options.Header2); - } - - /// - /// Class to represent default VT100 escape sequences. - /// - /// Text of the header to format. - /// Formatted Header 3 string. - public string FormatHeader3(string headerText) - { - return FormatHeader(headerText, options.Header3); - } - - /// - /// Class to represent default VT100 escape sequences. - /// - /// Text of the header to format. - /// Formatted Header 4 string. - public string FormatHeader4(string headerText) - { - return FormatHeader(headerText, options.Header4); - } - - /// - /// Class to represent default VT100 escape sequences. - /// - /// Text of the header to format. - /// Formatted Header 5 string. - public string FormatHeader5(string headerText) - { - return FormatHeader(headerText, options.Header5); - } - - /// - /// Class to represent default VT100 escape sequences. - /// - /// Text of the header to format. - /// Formatted Header 6 string. - public string FormatHeader6(string headerText) - { - return FormatHeader(headerText, options.Header6); - } - - /// - /// Class to represent default VT100 escape sequences. - /// - /// Text of the code block to format. - /// True if it is a inline code block, false otherwise. - /// Formatted code block string. - public string FormatCode(string codeText, bool isInline) - { - bool isVT100Enabled = options.EnableVT100Encoding; - - if (isInline) - { - if (isVT100Enabled) - { - return string.Concat(Esc, options.Code, codeText, endSequence); - } - else - { - return codeText; - } - } - else - { - if (isVT100Enabled) - { - return string.Concat(Esc, options.Code, codeText, Esc, LongBackgroundCodeBlock, endSequence); - } - else - { - return codeText; - } - } - } - - /// - /// Class to represent default VT100 escape sequences. - /// - /// Text of the link to format. - /// URL of the link. - /// True url should be hidden, false otherwise. Default is true. - /// Formatted link string. - public string FormatLink(string linkText, string url, bool hideUrl = true) - { - bool isVT100Enabled = options.EnableVT100Encoding; - - if (hideUrl) - { - if (isVT100Enabled) - { - return string.Concat(Esc, options.Link, "\"", linkText, "\"", endSequence); - } - else - { - return string.Concat("\"", linkText, "\""); - } - } - else - { - if (isVT100Enabled) - { - return string.Concat("\"", linkText, "\" (", Esc, options.Link, url, endSequence, ")"); - } - else - { - return string.Concat("\"", linkText, "\" (", url, ")"); - } - } - } - - /// - /// Class to represent default VT100 escape sequences. - /// - /// Text to format as emphasis. - /// True if it is to be formatted as bold, false to format it as italics. - /// Formatted emphasis string. - public string FormatEmphasis(string emphasisText, bool isBold) - { - var sequence = isBold ? options.EmphasisBold : options.EmphasisItalics; - - if (options.EnableVT100Encoding) - { - return string.Concat(Esc, sequence, emphasisText, endSequence); - } - else - { - return emphasisText; - } - } - - /// - /// Class to represent default VT100 escape sequences. - /// - /// Text of the image to format. - /// Formatted image string. - public string FormatImage(string altText) - { - var text = altText; - - if (string.IsNullOrEmpty(altText)) - { - text = "Image"; - } - - if (options.EnableVT100Encoding) - { - return string.Concat(Esc, options.Image, "[", text, "]", endSequence); - } - else - { - return string.Concat("[", text, "]"); - } - } - - private string FormatHeader(string headerText, string headerEscapeSequence) - { - if (options.EnableVT100Encoding) - { - return string.Concat(Esc, headerEscapeSequence, headerText, endSequence); - } - else - { - return headerText; - } - } - } -} diff --git a/src/Microsoft.PowerShell.MarkdownRender/VT100ObjectRenderer.cs b/src/Microsoft.PowerShell.MarkdownRender/VT100ObjectRenderer.cs deleted file mode 100644 index 916999ecf77..00000000000 --- a/src/Microsoft.PowerShell.MarkdownRender/VT100ObjectRenderer.cs +++ /dev/null @@ -1,16 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -using Markdig.Renderers; -using Markdig.Syntax; - -namespace Microsoft.PowerShell.MarkdownRender -{ - /// - /// Implement the MarkdownObjectRenderer with VT100Renderer. - /// - /// The element type of the renderer. - public abstract class VT100ObjectRenderer : MarkdownObjectRenderer where T : MarkdownObject - { - } -} diff --git a/src/Microsoft.PowerShell.MarkdownRender/VT100Renderer.cs b/src/Microsoft.PowerShell.MarkdownRender/VT100Renderer.cs deleted file mode 100644 index 1f5da6270dc..00000000000 --- a/src/Microsoft.PowerShell.MarkdownRender/VT100Renderer.cs +++ /dev/null @@ -1,42 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -using System.IO; -using Markdig.Renderers; - -namespace Microsoft.PowerShell.MarkdownRender -{ - /// - /// Initializes an instance of the VT100 renderer. - /// - public sealed class VT100Renderer : TextRendererBase - { - /// - /// Initializes a new instance of the class. - /// - /// TextWriter to write to. - /// PSMarkdownOptionInfo object with options. - public VT100Renderer(TextWriter writer, PSMarkdownOptionInfo optionInfo) : base(writer) - { - EscapeSequences = new VT100EscapeSequences(optionInfo); - - // Add the various element renderers. - ObjectRenderers.Add(new HeaderBlockRenderer()); - ObjectRenderers.Add(new LineBreakRenderer()); - ObjectRenderers.Add(new CodeInlineRenderer()); - ObjectRenderers.Add(new FencedCodeBlockRenderer()); - ObjectRenderers.Add(new EmphasisInlineRenderer()); - ObjectRenderers.Add(new ParagraphBlockRenderer()); - ObjectRenderers.Add(new LeafInlineRenderer()); - ObjectRenderers.Add(new LinkInlineRenderer()); - ObjectRenderers.Add(new ListBlockRenderer()); - ObjectRenderers.Add(new ListItemBlockRenderer()); - ObjectRenderers.Add(new QuoteBlockRenderer()); - } - - /// - /// Gets the current escape sequences. - /// - public VT100EscapeSequences EscapeSequences { get; } - } -} diff --git a/src/Microsoft.PowerShell.Security/security/AclCommands.cs b/src/Microsoft.PowerShell.Security/security/AclCommands.cs index 7fa42b31424..beda593b70b 100644 --- a/src/Microsoft.PowerShell.Security/security/AclCommands.cs +++ b/src/Microsoft.PowerShell.Security/security/AclCommands.cs @@ -5,18 +5,18 @@ #pragma warning disable 56506 using System; -using System.Management.Automation; -using Dbg = System.Management.Automation; -using System.Management.Automation.Security; -using System.Security.AccessControl; -using System.Security.Principal; using System.Collections.Generic; using System.Collections.ObjectModel; +using System.ComponentModel; using System.Diagnostics.CodeAnalysis; -using System.Runtime.InteropServices; using System.Globalization; -using System.ComponentModel; -using System.Reflection; +using System.Management.Automation; +using System.Management.Automation.Security; +using System.Runtime.InteropServices; +using System.Security.AccessControl; +using System.Security.Principal; + +using Dbg = System.Management.Automation; namespace Microsoft.PowerShell.Commands { @@ -292,20 +292,17 @@ public static AuthorizationRuleCollection GetAccess(PSObject instance) } // Get DACL - AuthorizationRuleCollection dacl; CommonObjectSecurity cos = sd as CommonObjectSecurity; if (cos != null) { - dacl = cos.GetAccessRules(true, true, typeof(NTAccount)); + return cos.GetAccessRules(true, true, typeof(NTAccount)); } else { DirectoryObjectSecurity dos = sd as DirectoryObjectSecurity; Dbg.Diagnostics.Assert(dos != null, "Acl should be of type CommonObjectSecurity or DirectoryObjectSecurity"); - dacl = dos.GetAccessRules(true, true, typeof(NTAccount)); + return dos.GetAccessRules(true, true, typeof(NTAccount)); } - - return dacl; } /// @@ -330,20 +327,17 @@ public static AuthorizationRuleCollection GetAudit(PSObject instance) PSTraceSource.NewArgumentException(nameof(instance)); } - AuthorizationRuleCollection sacl; CommonObjectSecurity cos = sd as CommonObjectSecurity; if (cos != null) { - sacl = cos.GetAuditRules(true, true, typeof(NTAccount)); + return cos.GetAuditRules(true, true, typeof(NTAccount)); } else { DirectoryObjectSecurity dos = sd as DirectoryObjectSecurity; Dbg.Diagnostics.Assert(dos != null, "Acl should be of type CommonObjectSecurity or DirectoryObjectSecurity"); - sacl = dos.GetAuditRules(true, true, typeof(NTAccount)); + return dos.GetAuditRules(true, true, typeof(NTAccount)); } - - return sacl; } /// @@ -360,8 +354,7 @@ public static SecurityIdentifier GetCentralAccessPolicyId(PSObject instance) SessionState sessionState = new SessionState(); string path = sessionState.Path.GetUnresolvedProviderPathFromPSPath( GetPath(instance)); - IntPtr pOwner = IntPtr.Zero, pGroup = IntPtr.Zero; - IntPtr pDacl = IntPtr.Zero, pSacl = IntPtr.Zero, pSd = IntPtr.Zero; + IntPtr pSd = IntPtr.Zero; try { @@ -370,10 +363,10 @@ public static SecurityIdentifier GetCentralAccessPolicyId(PSObject instance) path, NativeMethods.SeObjectType.SE_FILE_OBJECT, NativeMethods.SecurityInformation.SCOPE_SECURITY_INFORMATION, - out pOwner, - out pGroup, - out pDacl, - out pSacl, + out IntPtr pOwner, + out IntPtr pGroup, + out IntPtr pDacl, + out IntPtr pSacl, out pSd); if (rs != NativeMethods.ERROR_SUCCESS) { @@ -385,8 +378,7 @@ public static SecurityIdentifier GetCentralAccessPolicyId(PSObject instance) return null; } - NativeMethods.ACL sacl = new NativeMethods.ACL(); - sacl = Marshal.PtrToStructure(pSacl); + NativeMethods.ACL sacl = Marshal.PtrToStructure(pSacl); if (sacl.AceCount == 0) { return null; @@ -396,8 +388,7 @@ public static SecurityIdentifier GetCentralAccessPolicyId(PSObject instance) IntPtr pAce = pSacl + Marshal.SizeOf(new NativeMethods.ACL()); for (ushort aceIdx = 0; aceIdx < sacl.AceCount; aceIdx++) { - NativeMethods.ACE_HEADER ace = new NativeMethods.ACE_HEADER(); - ace = Marshal.PtrToStructure(pAce); + NativeMethods.ACE_HEADER ace = Marshal.PtrToStructure(pAce); Dbg.Diagnostics.Assert(ace.AceType == NativeMethods.SYSTEM_SCOPED_POLICY_ID_ACE_TYPE, "Unexpected ACE type: " + ace.AceType.ToString(CultureInfo.CurrentCulture)); @@ -458,12 +449,11 @@ public static string GetCentralAccessPolicyName(PSObject instance) Marshal.Copy(capIdArray, 0, pCapId, capIdSize); IntPtr[] ppCapId = new IntPtr[1]; ppCapId[0] = pCapId; - uint capCount = 0; uint rs = NativeMethods.LsaQueryCAPs( ppCapId, 1, out caps, - out capCount); + out uint capCount); if (rs != NativeMethods.STATUS_SUCCESS) { throw new Win32Exception((int)rs); @@ -475,8 +465,7 @@ public static string GetCentralAccessPolicyName(PSObject instance) } // Get the CAP name. - NativeMethods.CENTRAL_ACCESS_POLICY cap = new NativeMethods.CENTRAL_ACCESS_POLICY(); - cap = Marshal.PtrToStructure(caps); + NativeMethods.CENTRAL_ACCESS_POLICY cap = Marshal.PtrToStructure(caps); // LSA_UNICODE_STRING is composed of WCHARs, but its length is given in bytes. return Marshal.PtrToStringUni(cap.Name.Buffer, cap.Name.Length / 2); } @@ -508,12 +497,11 @@ public static string[] GetAllCentralAccessPolicies(PSObject instance) try { // Retrieve all CAPs. - uint capCount = 0; uint rs = NativeMethods.LsaQueryCAPs( null, 0, out caps, - out capCount); + out uint capCount); if (rs != NativeMethods.STATUS_SUCCESS) { throw new Win32Exception((int)rs); @@ -528,14 +516,13 @@ public static string[] GetAllCentralAccessPolicies(PSObject instance) // Add CAP names and IDs to a string array. string[] policies = new string[capCount]; - NativeMethods.CENTRAL_ACCESS_POLICY cap = new NativeMethods.CENTRAL_ACCESS_POLICY(); IntPtr capPtr = caps; for (uint capIdx = 0; capIdx < capCount; capIdx++) { // Retrieve CAP name. Dbg.Diagnostics.Assert(capPtr != IntPtr.Zero, "Invalid central access policies array"); - cap = Marshal.PtrToStructure(capPtr); + NativeMethods.CENTRAL_ACCESS_POLICY cap = Marshal.PtrToStructure(capPtr); // LSA_UNICODE_STRING is composed of WCHARs, but its length is given in bytes. policies[capIdx] = "\"" + Marshal.PtrToStringUni( cap.Name.Buffer, @@ -653,7 +640,7 @@ public string[] Path } } - private PSObject _inputObject = null; + private PSObject _inputObject; /// /// InputObject Parameter @@ -695,7 +682,7 @@ public string[] LiteralPath } } - private bool _isLiteralPath = false; + private bool _isLiteralPath; /// /// Gets or sets the audit flag of the command. This flag @@ -758,7 +745,6 @@ public SwitchParameter AllCentralAccessPolicies /// protected override void ProcessRecord() { - Collection sd = null; AccessControlSections sections = AccessControlSections.Owner | AccessControlSections.Group | @@ -855,7 +841,7 @@ protected override void ProcessRecord() InvokeProvider.SecurityDescriptor.Get(rp, sections, context); - sd = context.GetAccumulatedObjects(); + Collection sd = context.GetAccumulatedObjects(); if (sd != null) { AddBrokeredProperties( @@ -921,7 +907,7 @@ public string[] Path } } - private PSObject _inputObject = null; + private PSObject _inputObject; /// /// InputObject Parameter @@ -962,7 +948,7 @@ public string[] LiteralPath } } - private bool _isLiteralPath = false; + private bool _isLiteralPath; private object _securityDescriptor; @@ -1060,7 +1046,7 @@ public SwitchParameter Passthru /// Returns a newly allocated SACL with no ACEs in it. /// Free the returned SACL by calling Marshal.FreeHGlobal. /// - private IntPtr GetEmptySacl() + private static IntPtr GetEmptySacl() { IntPtr pSacl = IntPtr.Zero; bool ret = true; @@ -1125,12 +1111,11 @@ private IntPtr GetSaclWithCapId(string capStr) // be deallocated separately (but with the entire buffer // returned by LsaQueryCAPs). freeCapId = false; - uint capCount = 0; rs = NativeMethods.LsaQueryCAPs( null, 0, out caps, - out capCount); + out uint capCount); if (rs != NativeMethods.STATUS_SUCCESS) { throw new Win32Exception((int)rs); @@ -1144,13 +1129,12 @@ private IntPtr GetSaclWithCapId(string capStr) } // Find the supplied string among available CAP names, use the corresponding CAPID. - NativeMethods.CENTRAL_ACCESS_POLICY cap = new NativeMethods.CENTRAL_ACCESS_POLICY(); IntPtr capPtr = caps; for (uint capIdx = 0; capIdx < capCount; capIdx++) { Dbg.Diagnostics.Assert(capPtr != IntPtr.Zero, "Invalid central access policies array"); - cap = Marshal.PtrToStructure(capPtr); + NativeMethods.CENTRAL_ACCESS_POLICY cap = Marshal.PtrToStructure(capPtr); // LSA_UNICODE_STRING is composed of WCHARs, but its length is given in bytes. string capName = Marshal.PtrToStringUni( cap.Name.Buffer, @@ -1246,7 +1230,7 @@ private IntPtr GetSaclWithCapId(string capStr) /// and the previous state of this privilege. Free the returned token /// by calling NativeMethods.CloseHandle. /// - private IntPtr GetTokenWithEnabledPrivilege( + private static IntPtr GetTokenWithEnabledPrivilege( string privilege, NativeMethods.TOKEN_PRIVILEGE previousState) { @@ -1334,14 +1318,13 @@ protected override void ProcessRecord() if (methodInfo != null) { - CommonSecurityDescriptor aclCommonSD = _securityDescriptor as CommonSecurityDescriptor; string sddl; if (aclObjectSecurity != null) { sddl = aclObjectSecurity.GetSecurityDescriptorSddlForm(AccessControlSections.All); } - else if (aclCommonSD != null) + else if (_securityDescriptor is CommonSecurityDescriptor aclCommonSD) { sddl = aclCommonSD.GetSddlForm(AccessControlSections.All); } @@ -1476,9 +1459,8 @@ protected override void ProcessRecord() context.PassThru = Passthru; if (_isLiteralPath) { - ProviderInfo Provider = null; - PSDriveInfo Drive = null; - string pathStr = SessionState.Path.GetUnresolvedProviderPathFromPSPath(p, out Provider, out Drive); + string pathStr = SessionState.Path.GetUnresolvedProviderPathFromPSPath( + p, out ProviderInfo Provider, out PSDriveInfo Drive); pathsToProcess.Add(new PathInfo(Drive, Provider, pathStr, SessionState)); context.SuppressWildcardExpansion = true; } @@ -1588,4 +1570,3 @@ protected override void ProcessRecord() } #pragma warning restore 56506 - diff --git a/src/Microsoft.PowerShell.Security/security/CatalogCommands.cs b/src/Microsoft.PowerShell.Security/security/CatalogCommands.cs index 895a551e057..5b542da92c2 100644 --- a/src/Microsoft.PowerShell.Security/security/CatalogCommands.cs +++ b/src/Microsoft.PowerShell.Security/security/CatalogCommands.cs @@ -4,14 +4,10 @@ #if !UNIX using System; +using System.Collections.ObjectModel; +using System.IO; using System.Management.Automation; using Dbg = System.Management.Automation.Diagnostics; -using System.Collections; -using System.IO; -using System.Management.Automation.Provider; -using System.Runtime.InteropServices; -using System.Collections.ObjectModel; -using System.Diagnostics.CodeAnalysis; namespace Microsoft.PowerShell.Commands { diff --git a/src/Microsoft.PowerShell.Security/security/CertificateCommands.cs b/src/Microsoft.PowerShell.Security/security/CertificateCommands.cs index 0da1112f5e3..46ab49ee0ab 100644 --- a/src/Microsoft.PowerShell.Security/security/CertificateCommands.cs +++ b/src/Microsoft.PowerShell.Security/security/CertificateCommands.cs @@ -1,11 +1,8 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -using System; -using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; -using System.IO; using System.Management.Automation; using System.Security; using System.Security.Cryptography; diff --git a/src/Microsoft.PowerShell.Security/security/CertificateProvider.cs b/src/Microsoft.PowerShell.Security/security/CertificateProvider.cs index e60b817d4ec..79e3eac1971 100644 --- a/src/Microsoft.PowerShell.Security/security/CertificateProvider.cs +++ b/src/Microsoft.PowerShell.Security/security/CertificateProvider.cs @@ -4,28 +4,29 @@ #if !UNIX using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.IO; using System.Management.Automation; using System.Management.Automation.Host; using System.Management.Automation.Internal; -using Runspaces = System.Management.Automation.Runspaces; -using Dbg = System.Management.Automation; -using Security = System.Management.Automation.Security; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.Collections; -using System.Runtime.InteropServices; using System.Management.Automation.Provider; +using System.Runtime.InteropServices; +using System.Security; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; using System.Text.RegularExpressions; -using System.Globalization; -using System.IO; -using System.Diagnostics; -using System.Diagnostics.CodeAnalysis; using System.Xml; using System.Xml.XPath; -using System.Security; + +using Dbg = System.Management.Automation; using DWORD = System.UInt32; +using Runspaces = System.Management.Automation.Runspaces; +using Security = System.Management.Automation.Security; namespace Microsoft.PowerShell.Commands { @@ -122,7 +123,7 @@ public int ExpiringInDays /// The structure contains punycode name and unicode name. /// [SuppressMessage("Microsoft.Performance", "CA1815:OverrideEqualsAndOperatorEqualsOnValueTypes")] - public struct DnsNameRepresentation + public readonly struct DnsNameRepresentation { /// /// Punycode version of DNS name. @@ -272,7 +273,7 @@ protected override bool ReleaseHandle() { bool fResult = false; - if (IntPtr.Zero != handle) + if (handle != IntPtr.Zero) { fResult = Security.NativeMethods.CertCloseStore(handle, 0); handle = IntPtr.Zero; @@ -349,7 +350,7 @@ public void Open(bool includeArchivedCerts) IntPtr.Zero, // hCryptProv StoreFlags, _storeName); - if (IntPtr.Zero == hCertStore) + if (hCertStore == IntPtr.Zero) { throw new System.ComponentModel.Win32Exception(Marshal.GetLastWin32Error()); } @@ -441,7 +442,7 @@ public IntPtr GetCertByName(string Name) while (true) { certContext = GetNextCert(certContext); - if (IntPtr.Zero == certContext) + if (certContext == IntPtr.Zero) { break; } @@ -634,7 +635,7 @@ private static Regex CertPathRegex { if (s_certPathRegex == null) { - RegexOptions options = RegexOptions.IgnoreCase | RegexOptions.Compiled; + const RegexOptions options = RegexOptions.IgnoreCase | RegexOptions.Compiled; s_certPathRegex = new Regex(certPathPattern, options); } } @@ -720,7 +721,7 @@ protected override void RemoveItem( string.Equals(pathElements[1], "ROOT", StringComparison.OrdinalIgnoreCase)) { string message = CertificateProviderStrings.UINotAllowed; - string errorId = "UINotAllowed"; + const string errorId = "UINotAllowed"; ThrowInvalidOperation(errorId, message); } @@ -745,7 +746,7 @@ protected override void RemoveItem( if (fUserContext) { string message = CertificateProviderStrings.CannotDeleteUserStore; - string errorId = "CannotDeleteUserStore"; + const string errorId = "CannotDeleteUserStore"; ThrowInvalidOperation(errorId, message); } @@ -755,7 +756,7 @@ protected override void RemoveItem( else // other container than a store { string message = CertificateProviderStrings.CannotRemoveContainer; - string errorId = "CannotRemoveContainer"; + const string errorId = "CannotRemoveContainer"; ThrowInvalidOperation(errorId, message); } } @@ -826,7 +827,7 @@ protected override void MoveItem( if (isContainer) { string message = CertificateProviderStrings.CannotMoveContainer; - string errorId = "CannotMoveContainer"; + const string errorId = "CannotMoveContainer"; ThrowInvalidOperation(errorId, message); } @@ -843,7 +844,7 @@ protected override void MoveItem( else { string message = CertificateProviderStrings.InvalidDestStore; - string errorId = "InvalidDestStore"; + const string errorId = "InvalidDestStore"; ThrowInvalidOperation(errorId, message); } } @@ -855,14 +856,14 @@ protected override void MoveItem( if (!string.Equals(pathElements[0], destElements[0], StringComparison.OrdinalIgnoreCase)) { string message = CertificateProviderStrings.CannotMoveCrossContext; - string errorId = "CannotMoveCrossContext"; + const string errorId = "CannotMoveCrossContext"; ThrowInvalidOperation(errorId, message); } if (string.Equals(pathElements[1], destElements[1], StringComparison.OrdinalIgnoreCase)) { string message = CertificateProviderStrings.CannotMoveToSameStore; - string errorId = "CannotMoveToSameStore"; + const string errorId = "CannotMoveToSameStore"; ThrowInvalidOperation(errorId, message); } @@ -876,7 +877,7 @@ protected override void MoveItem( string.Equals(destElements[1], "ROOT", StringComparison.OrdinalIgnoreCase))) { string message = CertificateProviderStrings.UINotAllowed; - string errorId = "UINotAllowed"; + const string errorId = "UINotAllowed"; ThrowInvalidOperation(errorId, message); } } @@ -960,7 +961,7 @@ protected override void NewItem( if (pathElements.Length != 2) { string message = CertificateProviderStrings.CannotCreateItem; - string errorId = "CannotCreateItem"; + const string errorId = "CannotCreateItem"; ThrowInvalidOperation(errorId, message); } @@ -970,11 +971,11 @@ protected override void NewItem( if (fUserContext) { string message = CertificateProviderStrings.CannotCreateUserStore; - string errorId = "CannotCreateUserStore"; + const string errorId = "CannotCreateUserStore"; ThrowInvalidOperation(errorId, message); } - Security.NativeMethods.CertOpenStoreFlags StoreFlags = + const Security.NativeMethods.CertOpenStoreFlags StoreFlags = Security.NativeMethods.CertOpenStoreFlags.CERT_STORE_CREATE_NEW_FLAG | Security.NativeMethods.CertOpenStoreFlags.CERT_STORE_MAXIMUM_ALLOWED_FLAG | Security.NativeMethods.CertOpenStoreFlags.CERT_SYSTEM_STORE_LOCAL_MACHINE; @@ -986,7 +987,7 @@ protected override void NewItem( IntPtr.Zero, // hCryptProv StoreFlags, pathElements[1]); - if (IntPtr.Zero == hCertStore) + if (hCertStore == IntPtr.Zero) { throw new System.ComponentModel.Win32Exception(Marshal.GetLastWin32Error()); } @@ -1083,7 +1084,7 @@ protected override bool HasChildItems(string path) { store.Open(IncludeArchivedCerts()); IntPtr certContext = store.GetFirstCert(); - if (IntPtr.Zero != certContext) + if (certContext != IntPtr.Zero) { store.FreeCert(certContext); result = true; @@ -1373,7 +1374,7 @@ private void AttemptToImportPkiModule() _hasAttemptedToLoadPkiModule = true; } - private string MyGetChildName(string path) + private static string MyGetChildName(string path) { // Verify the parameters @@ -1414,7 +1415,7 @@ protected override void InvokeDefaultAction(string path) { path = NormalizePath(path); string action = CertificateProviderStrings.Action_Invoke; - string certmgr = "certmgr.msc"; + const string certmgr = "certmgr.msc"; string certPath = System.IO.Path.Combine( System.Environment.ExpandEnvironmentVariables("%windir%"), "system32"); @@ -1749,7 +1750,7 @@ private void RemoveCertStore(string storeName, bool fDeleteKey, string sourcePat // if recurse is true, remove every cert in the store IntPtr localName = Security.NativeMethods.CryptFindLocalizedName(storeName); string[] pathElements = GetPathElements(sourcePath); - if (IntPtr.Zero == localName)//not find, we can remove + if (localName == IntPtr.Zero)//not find, we can remove { X509NativeStore store = null; @@ -1763,7 +1764,7 @@ private void RemoveCertStore(string storeName, bool fDeleteKey, string sourcePat // enumerate over each cert and remove it // IntPtr certContext = store.GetFirstCert(); - while (IntPtr.Zero != certContext) + while (certContext != IntPtr.Zero) { X509Certificate2 cert = new X509Certificate2(certContext); string certPath = sourcePath + cert.Thumbprint; @@ -1772,7 +1773,7 @@ private void RemoveCertStore(string storeName, bool fDeleteKey, string sourcePat certContext = store.GetNextCert(certContext); } // remove the cert store - Security.NativeMethods.CertOpenStoreFlags StoreFlags = + const Security.NativeMethods.CertOpenStoreFlags StoreFlags = Security.NativeMethods.CertOpenStoreFlags.CERT_STORE_READONLY_FLAG | Security.NativeMethods.CertOpenStoreFlags.CERT_STORE_OPEN_EXISTING_FLAG | Security.NativeMethods.CertOpenStoreFlags.CERT_STORE_DEFER_CLOSE_UNTIL_LAST_FREE_FLAG | @@ -1793,7 +1794,7 @@ private void RemoveCertStore(string storeName, bool fDeleteKey, string sourcePat CultureInfo.CurrentCulture, CertificateProviderStrings.RemoveStoreTemplate, storeName); - string errorId = "CannotRemoveSystemStore"; + const string errorId = "CannotRemoveSystemStore"; ThrowInvalidOperation(errorId, message); } } @@ -1919,7 +1920,7 @@ private void DoRemove(X509Certificate2 cert, bool fDeleteKey, bool fMachine, str /// /// An IntPtr for store handle. /// No return. - private void CommitUserDS(IntPtr storeHandle) + private static void CommitUserDS(IntPtr storeHandle) { if (!Security.NativeMethods.CertControlStore( storeHandle, @@ -2098,7 +2099,7 @@ private object GetItemAtPath(string path, bool test, out bool isContainer) store.Open(IncludeArchivedCerts()); IntPtr certContext = store.GetCertByName(pathElements[2]); - if (IntPtr.Zero == certContext) + if (certContext == IntPtr.Zero) { if (test) { @@ -2449,7 +2450,7 @@ private void GetCertificatesOrNames(string path, // IntPtr certContext = store.GetFirstCert(); - while (IntPtr.Zero != certContext) + while (certContext != IntPtr.Zero) { X509Certificate2 cert = new X509Certificate2(certContext); @@ -2827,7 +2828,7 @@ internal static bool CertContainsEku(X509Certificate2 cert, List /// Gets the location as a - /// + /// /// public StoreLocation Location { @@ -3063,7 +3064,7 @@ public X509StoreLocation(StoreLocation location) /// The structure contains friendly name and EKU oid. /// [SuppressMessage("Microsoft.Performance", "CA1815:OverrideEqualsAndOperatorEqualsOnValueTypes")] - public struct EnhancedKeyUsageRepresentation + public readonly struct EnhancedKeyUsageRepresentation { /// /// Localized friendly name of EKU. diff --git a/src/Microsoft.PowerShell.Security/security/SecureStringCommands.cs b/src/Microsoft.PowerShell.Security/security/SecureStringCommands.cs index 36316364c82..6333541e242 100644 --- a/src/Microsoft.PowerShell.Security/security/SecureStringCommands.cs +++ b/src/Microsoft.PowerShell.Security/security/SecureStringCommands.cs @@ -2,8 +2,6 @@ // Licensed under the MIT License. using System; -using System.Globalization; -using System.IO; using System.Management.Automation; using System.Runtime.InteropServices; using System.Security; diff --git a/src/Microsoft.PowerShell.Security/security/SignatureCommands.cs b/src/Microsoft.PowerShell.Security/security/SignatureCommands.cs index 3fa7c054a20..49a37d06c78 100644 --- a/src/Microsoft.PowerShell.Security/security/SignatureCommands.cs +++ b/src/Microsoft.PowerShell.Security/security/SignatureCommands.cs @@ -2,22 +2,15 @@ // Licensed under the MIT License. using System; -using System.Collections; -using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Management.Automation; using System.Management.Automation.Internal; -using System.Management.Automation.Provider; -using System.Runtime.InteropServices; -using System.Security; using System.Security.Cryptography.X509Certificates; using Dbg = System.Management.Automation.Diagnostics; -using DWORD = System.UInt32; - namespace Microsoft.PowerShell.Commands { /// diff --git a/src/Microsoft.WSMan.Management/ConfigProvider.cs b/src/Microsoft.WSMan.Management/ConfigProvider.cs index 7054766373d..208303d9b88 100644 --- a/src/Microsoft.WSMan.Management/ConfigProvider.cs +++ b/src/Microsoft.WSMan.Management/ConfigProvider.cs @@ -856,7 +856,7 @@ protected override void GetItem(string path) } } } - catch (PSArgumentNullException) { return;/*Leaving this known exception for no value found. Not Throwing error.*/} + catch (PSArgumentNullException) { return; /*Leaving this known exception for no value found. Not Throwing error.*/} catch (NullReferenceException) { return; /*Leaving this known exception for no value found. Not Throwing error.*/} } } @@ -1033,7 +1033,7 @@ protected override void SetItem(string path, object value) pluginConfiguration.UpdateOneConfiguration( ".", WSManStringLiterals.ConfigRunAsPasswordName, - this.GetStringFromSecureString(runAsCredentials.Password)); + GetStringFromSecureString(runAsCredentials.Password)); } } @@ -1050,7 +1050,7 @@ protected override void SetItem(string path, object value) AssertError(helper.GetResourceMsgFromResourcetext("SetItemOnRunAsPasswordNoRunAsUser"), false); } - value = this.GetStringFromSecureString(value); + value = GetStringFromSecureString(value); } pluginConfiguration.UpdateOneConfiguration(".", ChildName, value.ToString()); @@ -1284,7 +1284,7 @@ protected override void SetItem(string path, object value) { if (!Force) { - string query = ""; + string query = string.Empty; string caption = helper.GetResourceMsgFromResourcetext("SetItemGeneralSecurityCaption"); if (ChildName.Equals("TrustedHosts", StringComparison.OrdinalIgnoreCase)) { @@ -2290,7 +2290,7 @@ private void NewItemPluginOrPluginChild(object sessionobj, string path, string h /// /// /// - private PSObject GetItemPSObjectWithTypeName(string Name, string TypeNameOfElement, object Value, string[] keys, string ExtendedTypeName, WsManElementObjectTypes WSManElementObjectType, PSObject input = null) + private static PSObject GetItemPSObjectWithTypeName(string Name, string TypeNameOfElement, object Value, string[] keys, string ExtendedTypeName, WsManElementObjectTypes WSManElementObjectType, PSObject input = null) { PSObject mshObject = null; if (WSManElementObjectType.Equals(WsManElementObjectTypes.WSManConfigElement)) @@ -2410,7 +2410,7 @@ private void SetItemListenerOrClientCertificate(object sessionObj, string Resour /// /// /// - private string GetInputStringForCreate(string ResourceURI, Hashtable value, string host) + private static string GetInputStringForCreate(string ResourceURI, Hashtable value, string host) { string putstr = string.Empty; string nilns = string.Empty; @@ -2523,7 +2523,7 @@ private string GetHostName(string path) return sHostname; } - private string GetRootNodeName(string ResourceURI) + private static string GetRootNodeName(string ResourceURI) { string tempuri = string.Empty; if (ResourceURI.Contains('?')) @@ -2531,7 +2531,7 @@ private string GetRootNodeName(string ResourceURI) ResourceURI = ResourceURI.Split('?').GetValue(0).ToString(); } - string PTRN_URI_LAST = "([a-z_][-a-z0-9._]*)$"; + const string PTRN_URI_LAST = "([a-z_][-a-z0-9._]*)$"; Regex objregex = new Regex(PTRN_URI_LAST, RegexOptions.IgnoreCase); MatchCollection regexmatch = objregex.Matches(ResourceURI); if (regexmatch.Count > 0) @@ -2542,7 +2542,7 @@ private string GetRootNodeName(string ResourceURI) return tempuri; } - private string EscapeValuesForXML(string value) + private static string EscapeValuesForXML(string value) { StringBuilder esc_str = new StringBuilder(); for (int i = 0; i <= value.Length - 1; i++) @@ -2585,7 +2585,7 @@ private string EscapeValuesForXML(string value) return esc_str.ToString(); } - private bool IsItemContainer(XmlNodeList nodes) + private static bool IsItemContainer(XmlNodeList nodes) { bool result = false; if (nodes.Count != 0) @@ -2935,7 +2935,7 @@ private bool ContainResourceValue(object sessionobj, string ResourceURI, string #endregion "WsMan linking Operations" - private string GetURIWithFilter(string uri, Hashtable cmdlinevalues) + private static string GetURIWithFilter(string uri, Hashtable cmdlinevalues) { StringBuilder sburi = new StringBuilder(uri); if (cmdlinevalues != null) @@ -2960,7 +2960,7 @@ private string GetURIWithFilter(string uri, Hashtable cmdlinevalues) return sburi.ToString(); } - private string GetFilterString(Hashtable cmdlinevalues, string[] pkey) + private static string GetFilterString(Hashtable cmdlinevalues, string[] pkey) { StringBuilder filter = new StringBuilder(); foreach (string key in pkey) @@ -2979,7 +2979,7 @@ private string GetFilterString(Hashtable cmdlinevalues, string[] pkey) return filter.ToString(); } - private bool IsPKey(string value, string ResourceURI) + private static bool IsPKey(string value, string ResourceURI) { bool result = false; if (ResourceURI.Contains(WSManStringLiterals.containerListener)) @@ -2998,7 +2998,7 @@ private bool IsPKey(string value, string ResourceURI) return result; } - private bool CheckPkeysArray(Hashtable values, string value, string[] pkeys) + private static bool CheckPkeysArray(Hashtable values, string value, string[] pkeys) { bool result = false; if (values != null) @@ -3239,7 +3239,7 @@ private PSObject BuildHostLevelPSObjectArrayList(object objSessionObject, string /// /// /// - private PSObject ConvertToPSObject(XmlNode xmlnode) + private static PSObject ConvertToPSObject(XmlNode xmlnode) { PSObject mshObject = new PSObject(); foreach (XmlNode node in xmlnode.ChildNodes) @@ -3275,7 +3275,7 @@ private PSObject ConvertToPSObject(XmlNode xmlnode) return mshObject; } - private string SetXPathString(string uri) + private static string SetXPathString(string uri) { string parent = uri.Substring(uri.LastIndexOf(WSManStringLiterals.WinrmPathSeparator.ToString(), StringComparison.OrdinalIgnoreCase) + 1); if (parent.Equals(WSManStringLiterals.containerWinrs, StringComparison.OrdinalIgnoreCase)) @@ -3307,7 +3307,7 @@ private string SetXPathString(string uri) return parent; } - private string SetSchemaPath(string uri) + private static string SetSchemaPath(string uri) { string schemapath = string.Empty; uri = uri.Remove(0, WinrmRootName[0].Length); @@ -3334,7 +3334,7 @@ private string SetSchemaPath(string uri) /// /// /// - private string NormalizePath(string path, string host) + private static string NormalizePath(string path, string host) { string uri = string.Empty; if (path.StartsWith(host, StringComparison.OrdinalIgnoreCase)) @@ -3647,20 +3647,20 @@ private string GetCorrectCaseOfName(string ChildName, string hostname, string pa else { if (ChildName.StartsWith(WSManStringLiterals.containerListener, StringComparison.OrdinalIgnoreCase)) - result = string.Concat(WSManStringLiterals.containerListener, "_", ChildName.AsSpan().Slice(ChildName.IndexOf('_') + 1)); + result = string.Concat(WSManStringLiterals.containerListener, "_", ChildName.AsSpan(ChildName.IndexOf('_') + 1)); if (ChildName.StartsWith(WSManStringLiterals.containerSingleResource, StringComparison.OrdinalIgnoreCase)) - result = string.Concat(WSManStringLiterals.containerSingleResource, "_", ChildName.AsSpan().Slice(ChildName.IndexOf('_') + 1)); + result = string.Concat(WSManStringLiterals.containerSingleResource, "_", ChildName.AsSpan(ChildName.IndexOf('_') + 1)); if (ChildName.StartsWith(WSManStringLiterals.containerSecurity, StringComparison.OrdinalIgnoreCase)) - result = string.Concat(WSManStringLiterals.containerSecurity, "_", ChildName.AsSpan().Slice(ChildName.IndexOf('_') + 1)); + result = string.Concat(WSManStringLiterals.containerSecurity, "_", ChildName.AsSpan(ChildName.IndexOf('_') + 1)); if (ChildName.StartsWith(WSManStringLiterals.containerClientCertificate, StringComparison.OrdinalIgnoreCase)) - result = string.Concat(WSManStringLiterals.containerClientCertificate, "_", ChildName.AsSpan().Slice(ChildName.IndexOf('_') + 1)); + result = string.Concat(WSManStringLiterals.containerClientCertificate, "_", ChildName.AsSpan(ChildName.IndexOf('_') + 1)); } } return result; } - private ArrayList RemoveItemfromResourceArray(ArrayList resourceArray, string ChildName, string type, string property) + private static ArrayList RemoveItemfromResourceArray(ArrayList resourceArray, string ChildName, string type, string property) { if (resourceArray != null) { @@ -4519,7 +4519,7 @@ private void GetChildItemsOrNames(string path, ProviderMethods methodname, bool /// /// /// - private int GetPluginNames(XmlDocument xmlPlugins, out PSObject PluginNames, out string CurrentPluginName, string path) + private static int GetPluginNames(XmlDocument xmlPlugins, out PSObject PluginNames, out string CurrentPluginName, string path) { PluginNames = new PSObject(); CurrentPluginName = string.Empty; @@ -4627,7 +4627,7 @@ private void StartWSManService(bool force) /// /// /// - private bool IsPathLocalMachine(string host) + private static bool IsPathLocalMachine(string host) { bool hostfound = false; // Check is Localhost @@ -4684,7 +4684,7 @@ private bool IsPathLocalMachine(string host) #region Plugin private functions - private void GenerateObjectNameAndKeys(Hashtable InputAttributes, string ResourceURI, string ContainerItem, out string ItemName, out string[] keys) + private static void GenerateObjectNameAndKeys(Hashtable InputAttributes, string ResourceURI, string ContainerItem, out string ItemName, out string[] keys) { StringBuilder sbHashKey = new StringBuilder(); string keysColumns = string.Empty; @@ -4717,7 +4717,7 @@ private void GenerateObjectNameAndKeys(Hashtable InputAttributes, string Resourc keys = keysColumns.Split('|'); } - private void ProcessCertMappingObjects(XmlDocument xmlCerts, out Hashtable Certcache, out Hashtable Keyscache) + private static void ProcessCertMappingObjects(XmlDocument xmlCerts, out Hashtable Certcache, out Hashtable Keyscache) { Hashtable lCache = new Hashtable(); Hashtable kCache = new Hashtable(); @@ -4775,7 +4775,7 @@ private void ProcessCertMappingObjects(XmlDocument xmlCerts, out Hashtable Certc Keyscache = kCache; } - private void ProcessListenerObjects(XmlDocument xmlListeners, out Hashtable listenercache, out Hashtable Keyscache) + private static void ProcessListenerObjects(XmlDocument xmlListeners, out Hashtable listenercache, out Hashtable Keyscache) { Hashtable lCache = new Hashtable(); Hashtable kCache = new Hashtable(); @@ -4836,7 +4836,7 @@ private void ProcessListenerObjects(XmlDocument xmlListeners, out Hashtable list Keyscache = kCache; } - private PSObject ProcessPluginConfigurationLevel(XmlDocument xmldoc, bool setRunasPasswordAsSecureString = false) + private static PSObject ProcessPluginConfigurationLevel(XmlDocument xmldoc, bool setRunasPasswordAsSecureString = false) { PSObject objConfiglvl = null; @@ -4877,7 +4877,7 @@ private PSObject ProcessPluginConfigurationLevel(XmlDocument xmldoc, bool setRun return objConfiglvl; } - private ArrayList ProcessPluginResourceLevel(XmlDocument xmldoc, out ArrayList arrSecurity) + private static ArrayList ProcessPluginResourceLevel(XmlDocument xmldoc, out ArrayList arrSecurity) { ArrayList Resources = null; ArrayList nSecurity = null; @@ -4963,7 +4963,7 @@ private ArrayList ProcessPluginResourceLevel(XmlDocument xmldoc, out ArrayList a return Resources; } - private ArrayList ProcessPluginInitParamLevel(XmlDocument xmldoc) + private static ArrayList ProcessPluginInitParamLevel(XmlDocument xmldoc) { ArrayList InitParamLvl = null; if (xmldoc != null) @@ -5001,7 +5001,7 @@ private ArrayList ProcessPluginInitParamLevel(XmlDocument xmldoc) return InitParamLvl; } - private ArrayList ProcessPluginSecurityLevel(ArrayList arrSecurity, XmlDocument xmlSecurity, string UniqueResourceID, string ParentResourceUri) + private static ArrayList ProcessPluginSecurityLevel(ArrayList arrSecurity, XmlDocument xmlSecurity, string UniqueResourceID, string ParentResourceUri) { // ArrayList SecurityLvl = null; if (xmlSecurity != null) @@ -5063,7 +5063,7 @@ private ArrayList ProcessPluginSecurityLevel(ArrayList arrSecurity, XmlDocument ///List of Securities ///List of initialization parameters. /// An Configuration XML, ready to send to server. - private string ConstructPluginXml(PSObject objinputparam, string ResourceURI, string host, string Operation, ArrayList resources, ArrayList securities, ArrayList initParams) + private static string ConstructPluginXml(PSObject objinputparam, string ResourceURI, string host, string Operation, ArrayList resources, ArrayList securities, ArrayList initParams) { StringBuilder sbvalues = new StringBuilder(); sbvalues.Append(" /// Value to append. - private string GetStringFromSecureString(object propertyValue) + private static string GetStringFromSecureString(object propertyValue) { SecureString value = propertyValue as SecureString; string passwordValueToAdd = string.Empty; @@ -5206,7 +5206,7 @@ private string GetStringFromSecureString(object propertyValue) return passwordValueToAdd; } - private string ConstructResourceXml(PSObject objinputparams, ArrayList resources, ArrayList securities) + private static string ConstructResourceXml(PSObject objinputparams, ArrayList resources, ArrayList securities) { StringBuilder sbvalues = new StringBuilder(string.Empty); if (objinputparams == null && resources == null) @@ -5293,7 +5293,7 @@ private string ConstructResourceXml(PSObject objinputparams, ArrayList resources return sbvalues.ToString(); } - private string ConstructSecurityXml(PSObject objinputparams, ArrayList securities, string strResourceIdentity) + private static string ConstructSecurityXml(PSObject objinputparams, ArrayList securities, string strResourceIdentity) { // StringBuilder sbvalues = new StringBuilder(string.Empty); @@ -5320,7 +5320,7 @@ private string ConstructSecurityXml(PSObject objinputparams, ArrayList securitie return sbvalues.ToString(); } - private void AddSecurityProperties( + private static void AddSecurityProperties( PSMemberInfoCollection properties, StringBuilder sbValues) { @@ -5345,7 +5345,7 @@ private void AddSecurityProperties( sbValues.Append(""); } - private string ConstructInitParamsXml(PSObject objinputparams, ArrayList initparams) + private static string ConstructInitParamsXml(PSObject objinputparams, ArrayList initparams) { // // @@ -5397,7 +5397,7 @@ private string ConstructInitParamsXml(PSObject objinputparams, ArrayList initpar return sbvalues.ToString(); } - private string ConstructCapabilityXml(object[] capabilities) + private static string ConstructCapabilityXml(object[] capabilities) { StringBuilder sbvalues = new StringBuilder(string.Empty); foreach (object cap in capabilities) @@ -5413,7 +5413,7 @@ private string ConstructCapabilityXml(object[] capabilities) return sbvalues.ToString(); } - private bool IsValueOfParamList(string name, string[] paramcontainer) + private static bool IsValueOfParamList(string name, string[] paramcontainer) { bool result = false; foreach (string value in paramcontainer) @@ -5434,14 +5434,14 @@ private enum ProviderMethods { GetChildItems, GetChildNames - }; + } private enum WsManElementObjectTypes { WSManConfigElement, WSManConfigContainerElement, WSManConfigLeafElement - }; + } #region def private static readonly string[] WinrmRootName = new string[] { "winrm/Config" }; diff --git a/src/Microsoft.WSMan.Management/CredSSP.cs b/src/Microsoft.WSMan.Management/CredSSP.cs index 60d8795ac54..cd5e6d3fc4d 100644 --- a/src/Microsoft.WSMan.Management/CredSSP.cs +++ b/src/Microsoft.WSMan.Management/CredSSP.cs @@ -227,7 +227,7 @@ private void DeleteUserDelegateSettings() GPO.OpenLocalMachineGPO(1); KeyHandle = GPO.GetRegistryKey(2); RegistryKey rootKey = Registry.CurrentUser; - string GPOpath = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Group Policy Objects"; + const string GPOpath = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Group Policy Objects"; RegistryKey GPOKey = rootKey.OpenSubKey(GPOpath, true); foreach (string keyname in GPOKey.GetSubKeyNames()) { @@ -508,7 +508,7 @@ private void EnableClientSideSettings() return; } - string newxmlcontent = @"true"; + const string newxmlcontent = @"true"; try { XmlDocument xmldoc = new XmlDocument(); @@ -626,7 +626,7 @@ private void UpdateCurrentUserRegistrySettings() GPO.OpenLocalMachineGPO(1); KeyHandle = GPO.GetRegistryKey(2); RegistryKey rootKey = Registry.CurrentUser; - string GPOpath = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Group Policy Objects"; + const string GPOpath = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Group Policy Objects"; RegistryKey GPOKey = rootKey.OpenSubKey(GPOpath, true); foreach (string keyname in GPOKey.GetSubKeyNames()) { @@ -827,7 +827,7 @@ protected override void BeginProcessing() } // The application name MUST be "wsman" as wsman got approval from security // folks who suggested to register the SPN with name "wsman". - string applicationname = "wsman"; + const string applicationname = "wsman"; string credsspResult = GetDelegateSettings(applicationname); if (string.IsNullOrEmpty(credsspResult)) { diff --git a/src/Microsoft.WSMan.Management/CurrentConfigurations.cs b/src/Microsoft.WSMan.Management/CurrentConfigurations.cs index 783bfe1ef0b..0129554c30b 100644 --- a/src/Microsoft.WSMan.Management/CurrentConfigurations.cs +++ b/src/Microsoft.WSMan.Management/CurrentConfigurations.cs @@ -131,7 +131,7 @@ public void RemoveOneConfiguration(string pathToNodeFromRoot) { if (nodeToRemove is XmlAttribute) { - this.RemoveAttribute(nodeToRemove as XmlAttribute); + RemoveAttribute(nodeToRemove as XmlAttribute); } } else @@ -217,7 +217,7 @@ public string GetOneConfiguration(string pathFromRoot) /// Removes the attribute from OwnerNode. /// /// Attribute to Remove. - private void RemoveAttribute(XmlAttribute attributeToRemove) + private static void RemoveAttribute(XmlAttribute attributeToRemove) { XmlElement ownerElement = attributeToRemove.OwnerElement; ownerElement.RemoveAttribute(attributeToRemove.Name); diff --git a/src/Microsoft.WSMan.Management/Interop.cs b/src/Microsoft.WSMan.Management/Interop.cs index 7084a111f2d..6685770b0ef 100644 --- a/src/Microsoft.WSMan.Management/Interop.cs +++ b/src/Microsoft.WSMan.Management/Interop.cs @@ -376,7 +376,7 @@ void SetProxy(int accessType, /// ProxyAuthenticationUseDigest method of IWSManConnectionOptionsEx2 interface. [DispId(11)] int ProxyAuthenticationUseDigest(); - }; + } #endregion IWSManConnectionOptions diff --git a/src/Microsoft.WSMan.Management/WSManInstance.cs b/src/Microsoft.WSMan.Management/WSManInstance.cs index a8eaad6ab9a..b4fb9ed955c 100644 --- a/src/Microsoft.WSMan.Management/WSManInstance.cs +++ b/src/Microsoft.WSMan.Management/WSManInstance.cs @@ -391,7 +391,7 @@ public SwitchParameter UseSSL #endregion parameter - # region private + #region private private WSManHelper helper; private string GetFilter() diff --git a/src/Microsoft.WSMan.Management/WsManHelper.cs b/src/Microsoft.WSMan.Management/WsManHelper.cs index ef29cb1a5c2..2c423fd2b13 100644 --- a/src/Microsoft.WSMan.Management/WsManHelper.cs +++ b/src/Microsoft.WSMan.Management/WsManHelper.cs @@ -467,7 +467,7 @@ internal string ProcessInput(IWSManEx wsman, string filepath, string operation, } else { - XmlNode tmpNode = node.ChildNodes[0];//.Item[0]; + XmlNode tmpNode = node.ChildNodes[0]; //.Item[0]; if (!tmpNode.NodeType.ToString().Equals("text", StringComparison.OrdinalIgnoreCase)) { throw new ArgumentException(_resourceMgr.GetString("NOAttributeMatch")); diff --git a/src/Microsoft.WSMan.Runtime/WSManSessionOption.cs b/src/Microsoft.WSMan.Runtime/WSManSessionOption.cs index d8681a54618..13dc8bbea2c 100644 --- a/src/Microsoft.WSMan.Runtime/WSManSessionOption.cs +++ b/src/Microsoft.WSMan.Runtime/WSManSessionOption.cs @@ -2,19 +2,8 @@ // Licensed under the MIT License. using System; -using System.ComponentModel; -using System.IO; -using System.Net; -using System.Reflection; -using System.Resources; -using System.Xml; - -using System.Collections; -using System.Collections.Generic; - -using System.Runtime.InteropServices; using System.Diagnostics.CodeAnalysis; -using System.Runtime.CompilerServices; +using System.Net; [assembly: CLSCompliant(true)] @@ -28,153 +17,53 @@ public sealed class SessionOption /// /// Property. /// - public bool SkipCACheck - { - get { return _SkipCACheck; } - - set - { - _SkipCACheck = value; - } - } - - private bool _SkipCACheck; + public bool SkipCACheck { get; set; } /// /// Property. /// - public bool SkipCNCheck - { - get { return _SkipCNCheck; } - - set - { - _SkipCNCheck = value; - } - } - - private bool _SkipCNCheck; + public bool SkipCNCheck { get; set; } /// /// Property. /// - public bool SkipRevocationCheck - { - get { return _SkipRevocationCheck; } - - set - { - _SkipRevocationCheck = value; - } - } - - private bool _SkipRevocationCheck; + public bool SkipRevocationCheck { get; set; } /// /// Property. /// - public bool UseEncryption - { - get { return _useencryption; } - - set - { - _useencryption = value; - } - } - - private bool _useencryption = true; + public bool UseEncryption { get; set; } = true; /// /// Property. /// - public bool UseUtf16 - { - get { return _UTF16; } - - set - { - _UTF16 = value; - } - } - - private bool _UTF16; + public bool UseUtf16 { get; set; } /// /// Property. /// - public ProxyAuthentication ProxyAuthentication - { - get { return _ProxyAuthentication; } - - set - { - _ProxyAuthentication = value; - } - } - - private ProxyAuthentication _ProxyAuthentication; + public ProxyAuthentication ProxyAuthentication { get; set; } /// /// Property. /// [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "SPN")] - public int SPNPort - { - get { return _SPNPort; } - - set - { - _SPNPort = value; - } - } - - private int _SPNPort; + public int SPNPort { get; set; } /// /// Property. /// - public int OperationTimeout - { - get { return _OperationTimeout; } - - set - { - _OperationTimeout = value; - } - } - - private int _OperationTimeout; + public int OperationTimeout { get; set; } /// /// Property. /// - public NetworkCredential ProxyCredential - { - get { return _ProxyCredential; } - - set - { - _ProxyCredential = value; - } - } - - private NetworkCredential _ProxyCredential; + public NetworkCredential ProxyCredential { get; set; } /// /// Property. /// - public ProxyAccessType ProxyAccessType - { - get { return _proxyaccesstype; } - - set - { - _proxyaccesstype = value; - } - } - - private ProxyAccessType _proxyaccesstype; + public ProxyAccessType ProxyAccessType { get; set; } } /// diff --git a/src/Modules/PSGalleryModules.csproj b/src/Modules/PSGalleryModules.csproj index 3f7b71a07a3..63807dc1e50 100644 --- a/src/Modules/PSGalleryModules.csproj +++ b/src/Modules/PSGalleryModules.csproj @@ -1,6 +1,14 @@ - + + PowerShell + Microsoft Corporation + (c) Microsoft Corporation. + + net5.0 + + true + diff --git a/src/Modules/Unix/Microsoft.PowerShell.Utility/Microsoft.PowerShell.Utility.psd1 b/src/Modules/Unix/Microsoft.PowerShell.Utility/Microsoft.PowerShell.Utility.psd1 index 1ef5f3328e0..b883acdd0d6 100644 --- a/src/Modules/Unix/Microsoft.PowerShell.Utility/Microsoft.PowerShell.Utility.psd1 +++ b/src/Modules/Unix/Microsoft.PowerShell.Utility/Microsoft.PowerShell.Utility.psd1 @@ -38,6 +38,10 @@ PrivateData = @{ Name = 'Microsoft.PowerShell.Utility.PSManageBreakpointsInRunspace' Description = 'Enables -BreakAll parameter on Debug-Runspace and Debug-Job cmdlets to allow users to decide if they want PowerShell to break immediately in the current location when they attach a debugger. Enables -Runspace parameter on *-PSBreakpoint cmdlets to support management of breakpoints in another runspace.' } + @{ + Name = 'Microsoft.PowerShell.Utility.PSImportPSDataFileSkipLimitCheck' + Description = 'Enable -SkipLimitCheck switch for Import-PowerShellDataFile to not enforce built-in hashtable limits' + } ) } } diff --git a/src/Modules/Windows/Microsoft.PowerShell.Utility/Microsoft.PowerShell.Utility.psd1 b/src/Modules/Windows/Microsoft.PowerShell.Utility/Microsoft.PowerShell.Utility.psd1 index 3b401f039e9..5ea504197fa 100644 --- a/src/Modules/Windows/Microsoft.PowerShell.Utility/Microsoft.PowerShell.Utility.psd1 +++ b/src/Modules/Windows/Microsoft.PowerShell.Utility/Microsoft.PowerShell.Utility.psd1 @@ -37,6 +37,10 @@ PrivateData = @{ Name = 'Microsoft.PowerShell.Utility.PSManageBreakpointsInRunspace' Description = 'Enables -BreakAll parameter on Debug-Runspace and Debug-Job cmdlets to allow users to decide if they want PowerShell to break immediately in the current location when they attach a debugger. Enables -Runspace parameter on *-PSBreakpoint cmdlets to support management of breakpoints in another runspace.' } + @{ + Name = 'Microsoft.PowerShell.Utility.PSImportPSDataFileSkipLimitCheck' + Description = 'Enable -NoLimit switch for Import-PowerShellDataFile to not enforce built-in hashtable limits' + } ) } } diff --git a/src/Modules/nuget.config b/src/Modules/nuget.config new file mode 100644 index 00000000000..f5a7f806a36 --- /dev/null +++ b/src/Modules/nuget.config @@ -0,0 +1,11 @@ + + + + + + + + + + + diff --git a/src/System.Management.Automation/CoreCLR/CorePsAssemblyLoadContext.cs b/src/System.Management.Automation/CoreCLR/CorePsAssemblyLoadContext.cs index 12f575b5175..5bd9be5c62b 100644 --- a/src/System.Management.Automation/CoreCLR/CorePsAssemblyLoadContext.cs +++ b/src/System.Management.Automation/CoreCLR/CorePsAssemblyLoadContext.cs @@ -105,7 +105,7 @@ private PowerShellAssemblyLoadContext(string basePaths) #region Fields - private static readonly object s_syncObj = new object(); + private static readonly object s_syncObj = new(); private readonly string[] _probingPaths; private readonly string[] _extensions = new string[] { ".ni.dll", ".dll" }; // CoreCLR type catalog dictionary @@ -114,9 +114,8 @@ private PowerShellAssemblyLoadContext(string basePaths) private readonly Dictionary _coreClrTypeCatalog; private readonly Lazy> _availableDotNetAssemblyNames; - private readonly HashSet _denyListedAssemblies = new HashSet(StringComparer.OrdinalIgnoreCase){ - "System.Windows.Forms" - }; + private readonly HashSet _denyListedAssemblies = + new(StringComparer.OrdinalIgnoreCase) { "System.Windows.Forms" }; #if !UNIX private string _winDir; @@ -140,7 +139,7 @@ private PowerShellAssemblyLoadContext(string basePaths) /// Therefore, there is no need to use the full assembly name as the key. Short assembly name is sufficient. /// private static readonly ConcurrentDictionary s_assemblyCache = - new ConcurrentDictionary(StringComparer.OrdinalIgnoreCase); + new(StringComparer.OrdinalIgnoreCase); #endregion Fields @@ -393,7 +392,7 @@ private bool TryFindInGAC(AssemblyName assemblyName, out string assemblyFilePath } // Find the assembly under 'gacRoot' and select the latest version. - private bool FindInGac(string gacRoot, AssemblyName assemblyName, out string assemblyPath) + private static bool FindInGac(string gacRoot, AssemblyName assemblyName, out string assemblyPath) { bool assemblyFound = false; assemblyPath = null; @@ -404,12 +403,12 @@ private bool FindInGac(string gacRoot, AssemblyName assemblyName, out string ass if (Directory.Exists(tempAssemblyDirPath)) { // Enumerate all directories, sort by name and select the last. This selects the latest version. - var chosenVersionDirectory = Directory.GetDirectories(tempAssemblyDirPath).OrderBy(d => d).LastOrDefault(); + var chosenVersionDirectory = Directory.EnumerateDirectories(tempAssemblyDirPath).OrderBy(d => d).LastOrDefault(); if (!string.IsNullOrEmpty(chosenVersionDirectory)) { // Select first or default as the directory will contain only one assembly. If nothing then default is null; - var foundAssemblyPath = Directory.GetFiles(chosenVersionDirectory, $"{assemblyName.Name}*").FirstOrDefault(); + var foundAssemblyPath = Directory.EnumerateFiles(chosenVersionDirectory, $"{assemblyName.Name}*").FirstOrDefault(); if (!string.IsNullOrEmpty(foundAssemblyPath)) { @@ -430,7 +429,7 @@ private bool FindInGac(string gacRoot, AssemblyName assemblyName, out string ass /// /// Try to get the specified assembly from cache. /// - private bool TryGetAssemblyFromCache(AssemblyName assemblyName, out Assembly asmLoaded) + private static bool TryGetAssemblyFromCache(AssemblyName assemblyName, out Assembly asmLoaded) { if (s_assemblyCache.TryGetValue(assemblyName.Name, out asmLoaded)) { @@ -454,7 +453,7 @@ private bool TryGetAssemblyFromCache(AssemblyName assemblyName, out Assembly asm /// AssemblyName of the requested assembly. /// AssemblyName of the loaded assembly. /// - private bool IsAssemblyMatching(AssemblyName requestedAssembly, AssemblyName loadedAssembly) + private static bool IsAssemblyMatching(AssemblyName requestedAssembly, AssemblyName loadedAssembly) { // // We use the same rules as CoreCLR loader to compare the requested assembly and loaded assembly: @@ -501,7 +500,7 @@ private bool IsAssemblyMatching(AssemblyName requestedAssembly, AssemblyName loa /// /// The assembly strong name of a CoreCLR Trusted_Platform_Assembly /// - private Assembly GetTrustedPlatformAssembly(string tpaStrongName) + private static Assembly GetTrustedPlatformAssembly(string tpaStrongName) { // We always depend on the default context to load the TPAs that are recorded in // the type catalog. @@ -509,7 +508,7 @@ private Assembly GetTrustedPlatformAssembly(string tpaStrongName) // it back from the cache of default context. // - If the requested TPA is not loaded yet, then 'Assembly.Load' will make the // default context to load it - AssemblyName assemblyName = new AssemblyName(tpaStrongName); + AssemblyName assemblyName = new(tpaStrongName); Assembly asmLoaded = Assembly.Load(assemblyName); return asmLoaded; } @@ -517,7 +516,7 @@ private Assembly GetTrustedPlatformAssembly(string tpaStrongName) /// /// Throw FileLoadException. /// - private void ThrowFileLoadException(string errorTemplate, params object[] args) + private static void ThrowFileLoadException(string errorTemplate, params object[] args) { string message = string.Format(CultureInfo.CurrentCulture, errorTemplate, args); throw new FileLoadException(message); @@ -526,7 +525,7 @@ private void ThrowFileLoadException(string errorTemplate, params object[] args) /// /// Throw FileNotFoundException. /// - private void ThrowFileNotFoundException(string errorTemplate, params object[] args) + private static void ThrowFileNotFoundException(string errorTemplate, params object[] args) { string message = string.Format(CultureInfo.CurrentCulture, errorTemplate, args); throw new FileNotFoundException(message); diff --git a/src/System.Management.Automation/CoreCLR/CorePsPlatform.cs b/src/System.Management.Automation/CoreCLR/CorePsPlatform.cs index 981d6bfb088..b5e657d497f 100644 --- a/src/System.Management.Automation/CoreCLR/CorePsPlatform.cs +++ b/src/System.Management.Automation/CoreCLR/CorePsPlatform.cs @@ -155,20 +155,20 @@ public static bool IsWindowsDesktop #endif // format files - internal static readonly List FormatFileNames = new List - { - "Certificate.format.ps1xml", - "Diagnostics.format.ps1xml", - "DotNetTypes.format.ps1xml", - "Event.format.ps1xml", - "FileSystem.format.ps1xml", - "Help.format.ps1xml", - "HelpV3.format.ps1xml", - "PowerShellCore.format.ps1xml", - "PowerShellTrace.format.ps1xml", - "Registry.format.ps1xml", - "WSMan.format.ps1xml" - }; + internal static readonly List FormatFileNames = new() + { + "Certificate.format.ps1xml", + "Diagnostics.format.ps1xml", + "DotNetTypes.format.ps1xml", + "Event.format.ps1xml", + "FileSystem.format.ps1xml", + "Help.format.ps1xml", + "HelpV3.format.ps1xml", + "PowerShellCore.format.ps1xml", + "PowerShellTrace.format.ps1xml", + "Registry.format.ps1xml", + "WSMan.format.ps1xml" + }; /// /// Some common environment variables used in PS have different @@ -566,8 +566,8 @@ internal static int NonWindowsGetProcessParentPid(int pid) /// Unix specific implementations of required functionality. internal static class Unix { - private static Dictionary usernameCache = new Dictionary(); - private static Dictionary groupnameCache = new Dictionary(); + private static Dictionary usernameCache = new(); + private static Dictionary groupnameCache = new(); /// The type of a Unix file system item. public enum ItemType @@ -699,7 +699,7 @@ public class CommonStat private const char CanExecute = 'x'; // helper for getting unix mode - private Dictionary modeMap = new Dictionary() + private Dictionary modeMap = new() { { StatMask.OwnerRead, CanRead }, { StatMask.OwnerWrite, CanWrite }, @@ -726,7 +726,7 @@ public class CommonStat }; // The item type and the character representation for the first element in the stat string - private Dictionary itemTypeTable = new Dictionary() + private Dictionary itemTypeTable = new() { { ItemType.BlockDevice, 'b' }, { ItemType.CharacterDevice, 'c' }, @@ -860,7 +860,7 @@ public static bool IsHardLink(FileSystemInfo fs) /// A managed common stat class instance. private static CommonStat CopyStatStruct(NativeMethods.CommonStatStruct css) { - CommonStat cs = new CommonStat(); + CommonStat cs = new(); cs.Inode = css.Inode; cs.Mode = css.Mode; cs.UserId = css.UserId; diff --git a/src/System.Management.Automation/DscSupport/CimDSCParser.cs b/src/System.Management.Automation/DscSupport/CimDSCParser.cs index 1d6ff12f270..78f778b944b 100644 --- a/src/System.Management.Automation/DscSupport/CimDSCParser.cs +++ b/src/System.Management.Automation/DscSupport/CimDSCParser.cs @@ -41,7 +41,7 @@ public static object ConvertCimInstanceToObject(Type targetType, CimInstance ins using (System.Management.Automation.PowerShell powerShell = System.Management.Automation.PowerShell.Create(RunspaceMode.CurrentRunspace)) { - string script = "param($targetType,$moduleName) & (Microsoft.PowerShell.Core\\Get-Module $moduleName) { New-Object $targetType } "; + const string script = "param($targetType,$moduleName) & (Microsoft.PowerShell.Core\\Get-Module $moduleName) { New-Object $targetType } "; powerShell.AddScript(script); powerShell.AddArgument(targetType); @@ -324,6 +324,7 @@ internal class CimDSCParser { private CimMofDeserializer _deserializer; private CimMofDeserializer.OnClassNeeded _onClassNeeded; + /// /// internal CimDSCParser(CimMofDeserializer.OnClassNeeded onClassNeeded) @@ -543,19 +544,19 @@ public static class DscClassCache // Create a list of classes which are not actual DSC resources similar to what we do inside PSDesiredStateConfiguration.psm1 private static readonly string[] s_hiddenResourceList = - { - "MSFT_BaseConfigurationProviderRegistration", - "MSFT_CimConfigurationProviderRegistration", - "MSFT_PSConfigurationProviderRegistration", - }; + { + "MSFT_BaseConfigurationProviderRegistration", + "MSFT_CimConfigurationProviderRegistration", + "MSFT_PSConfigurationProviderRegistration", + }; // Create a HashSet for fast lookup. According to MSDN, the time complexity of search for an element in a HashSet is O(1) - private static readonly HashSet s_hiddenResourceCache = new HashSet(s_hiddenResourceList, - StringComparer.OrdinalIgnoreCase); + private static readonly HashSet s_hiddenResourceCache = + new(s_hiddenResourceList, StringComparer.OrdinalIgnoreCase); // a collection to hold current importing script based resource file // this prevent circular importing case when the script resource existing in the same module with resources it import-dscresource - private static readonly HashSet s_currentImportingScriptFiles = new HashSet(StringComparer.OrdinalIgnoreCase); + private static readonly HashSet s_currentImportingScriptFiles = new(StringComparer.OrdinalIgnoreCase); /// /// DSC class cache for this runspace. @@ -637,18 +638,20 @@ private static HashSet ScriptKeywordFileCache /// /// Default ModuleName and ModuleVersion to use. /// - private static readonly Tuple s_defaultModuleInfoForResource = new Tuple("PSDesiredStateConfiguration", new Version("1.1")); + private static readonly Tuple s_defaultModuleInfoForResource = + new("PSDesiredStateConfiguration", new Version("1.1")); /// /// Default ModuleName and ModuleVersion to use for meta configuration resources. /// - internal static readonly Tuple DefaultModuleInfoForMetaConfigResource = new Tuple("PSDesiredStateConfigurationEngine", new Version("2.0")); + internal static readonly Tuple DefaultModuleInfoForMetaConfigResource = + new("PSDesiredStateConfigurationEngine", new Version("2.0")); /// /// A set of dynamic keywords that can be used in both configuration and meta configuration. /// internal static readonly HashSet SystemResourceNames = - new HashSet(StringComparer.OrdinalIgnoreCase) { "Node", "OMI_ConfigurationDocument" }; + new(StringComparer.OrdinalIgnoreCase) { "Node", "OMI_ConfigurationDocument" }; /// /// When this property is set to true, DSC Cache will cache multiple versions of a resource. @@ -783,7 +786,7 @@ public static void Initialize(Collection errors, List moduleP // Load Regular and DSC PS modules bool importInBoxResourcesImplicitly = false; - List modulePaths = new List(); + List modulePaths = new(); if (modulePathList == null || modulePathList.Count == 0) { modulePaths.Add(Path.Combine(configSystemPath, inboxModulePath)); @@ -1130,7 +1133,7 @@ private static List GetCachedClasses() /// List of cached cim classes. public static List GetCachedClassesForModule(PSModuleInfo module) { - List cachedClasses = new List(); + List cachedClasses = new(); var moduleQualifiedName = string.Format(CultureInfo.InvariantCulture, "{0}\\{1}", module.Name, module.Version.ToString()); foreach (var dscClassCacheEntry in ClassCache) { @@ -1150,7 +1153,7 @@ private static List GetCachedClasses() /// public static List GetFileDefiningClass(string className) { - List files = new List(); + List files = new(); foreach (var pair in ByFileClassCache) { var file = pair.Key; @@ -1297,7 +1300,7 @@ private static string GetFriendlyName(CimClass cimClass) /// public static Collection GetCachedKeywords() { - Collection keywords = new Collection(); + Collection keywords = new(); foreach (KeyValuePair cachedClass in ClassCache) { @@ -1908,7 +1911,7 @@ private static ParseError[] ImportResourceCheckSemantics(DynamicKeywordStatement // This function performs semantic checks for all DSC Resources keywords. private static ParseError[] CheckMandatoryPropertiesPresent(DynamicKeywordStatementAst kwAst) { - HashSet mandatoryPropertiesNames = new HashSet(StringComparer.OrdinalIgnoreCase); + HashSet mandatoryPropertiesNames = new(StringComparer.OrdinalIgnoreCase); foreach (var pair in kwAst.Keyword.Properties) { if (pair.Value.Mandatory) @@ -2360,7 +2363,7 @@ private static void GenerateMofForAst(TypeDefinitionAst typeAst, StringBuilder s ProcessMembers(sb, embeddedInstanceTypes, typeAst, className); - Queue bases = new Queue(); + Queue bases = new(); foreach (var b in typeAst.BaseTypes) { bases.Enqueue(b); @@ -2458,7 +2461,7 @@ public static bool GetResourceMethodsLinePosition(PSModuleInfo moduleInfo, strin } IEnumerable resourceDefinitions; - List moduleFiles = new List(); + List moduleFiles = new(); if (moduleInfo.RootModule != null) { moduleFiles.Add(moduleInfo.Path); @@ -2592,7 +2595,7 @@ private static bool GetResourceDefinitionsFromModule(string fileName, out IEnume { if (errorList != null && extent != null) { - List errorMessages = new List(); + List errorMessages = new(); foreach (var error in errors) { errorMessages.Add(error.ToString()); @@ -2697,7 +2700,7 @@ private static bool ImportKeywordsFromScriptFile(string fileName, PSModuleInfo m return result; } - private static readonly Dictionary s_mapPrimitiveDotNetTypeToMof = new Dictionary() + private static readonly Dictionary s_mapPrimitiveDotNetTypeToMof = new() { { typeof(sbyte), "sint8" }, { typeof(byte) , "uint8"}, @@ -2945,7 +2948,7 @@ private static string MapAttributesToMof(string[] enumNames, IEnumerable if (validateSet != null) { bool valueMapComma = false; - StringBuilder sbValues = new StringBuilder(", Values{"); + StringBuilder sbValues = new(", Values{"); sb.AppendFormat(CultureInfo.InvariantCulture, "{0}ValueMap{{", needComma ? ", " : string.Empty); needComma = true; @@ -3661,7 +3664,7 @@ public static string GetDSCResourceUsageString(DynamicKeyword keyword) private static StringBuilder FormatCimPropertyType(DynamicKeywordProperty prop, bool isOptionalProperty) { string cimTypeName = prop.TypeConstraint; - StringBuilder formattedTypeString = new StringBuilder(); + StringBuilder formattedTypeString = new(); if (string.Equals(cimTypeName, "MSFT_Credential", StringComparison.OrdinalIgnoreCase)) { @@ -3709,8 +3712,7 @@ private static ScriptBlock CimKeywordImplementationFunction get { // The scriptblock cache will handle mutual exclusion - return s_cimKeywordImplementationFunction ?? - (s_cimKeywordImplementationFunction = ScriptBlock.Create(CimKeywordImplementationFunctionText)); + return s_cimKeywordImplementationFunction ??= ScriptBlock.Create(CimKeywordImplementationFunctionText); } } diff --git a/src/System.Management.Automation/FormatAndOutput/DefaultFormatters/PowerShellCore_format_ps1xml.cs b/src/System.Management.Automation/FormatAndOutput/DefaultFormatters/PowerShellCore_format_ps1xml.cs index 0400d3488b5..dbb8d3a2085 100644 --- a/src/System.Management.Automation/FormatAndOutput/DefaultFormatters/PowerShellCore_format_ps1xml.cs +++ b/src/System.Management.Automation/FormatAndOutput/DefaultFormatters/PowerShellCore_format_ps1xml.cs @@ -263,6 +263,22 @@ internal static IEnumerable GetFormatData() yield return new ExtendedTypeDefinition( "Microsoft.PowerShell.Commands.ByteCollection", ViewsOf_Microsoft_PowerShell_Commands_ByteCollection()); + + yield return new ExtendedTypeDefinition( + "System.Management.Automation.PSStyle", + ViewsOf_System_Management_Automation_PSStyle()); + + yield return new ExtendedTypeDefinition( + "System.Management.Automation.PSStyle+FormattingData", + ViewsOf_System_Management_Automation_PSStyleFormattingData()); + + yield return new ExtendedTypeDefinition( + "System.Management.Automation.PSStyle+ForegroundColor", + ViewsOf_System_Management_Automation_PSStyleForegroundColor()); + + yield return new ExtendedTypeDefinition( + "System.Management.Automation.PSStyle+BackgroundColor", + ViewsOf_System_Management_Automation_PSStyleBackgroundColor()); } private static IEnumerable ViewsOf_System_RuntimeType() @@ -1317,7 +1333,7 @@ function Get-ConciseViewPositionMessage { $err.CategoryInfo.GetMessage() } elseif (! $err.ErrorDetails -or ! $err.ErrorDetails.Message) { - $err.Exception.Message + $posmsg + $newline + $err.Exception.Message + $posmsg } else { $err.ErrorDetails.Message + $posmsg } @@ -2004,5 +2020,131 @@ private static IEnumerable ViewsOf_Microsoft_PowerShell_Co .GroupByProperty("Label") .EndTable()); } + + private static IEnumerable ViewsOf_System_Management_Automation_PSStyle() + { + yield return new FormatViewDefinition("System.Management.Automation.PSStyle", + ListControl.Create() + .StartEntry() + .AddItemScriptBlock(@"""$($_.Reset)$($_.Reset.Replace(""""`e"""",'`e'))""", label: "Reset") + .AddItemScriptBlock(@"""$($_.BlinkOff)$($_.BlinkOff.Replace(""""`e"""",'`e'))$($_.Reset)""", label: "BlinkOff") + .AddItemScriptBlock(@"""$($_.Blink)$($_.Blink.Replace(""""`e"""",'`e'))$($_.Reset)""", label: "Blink") + .AddItemScriptBlock(@"""$($_.BoldOff)$($_.BoldOff.Replace(""""`e"""",'`e'))$($_.Reset)""", label: "BoldOff") + .AddItemScriptBlock(@"""$($_.Bold)$($_.Bold.Replace(""""`e"""",'`e'))$($_.Reset)""", label: "Bold") + .AddItemScriptBlock(@"""$($_.Hidden)$($_.Hidden.Replace(""""`e"""",'`e'))$($_.Reset)""", label: "Hidden") + .AddItemScriptBlock(@"""$($_.HiddenOff)$($_.HiddenOff.Replace(""""`e"""",'`e'))$($_.Reset)""", label: "HiddenOff") + .AddItemScriptBlock(@"""$($_.Reverse)$($_.Reverse.Replace(""""`e"""",'`e'))$($_.Reset)""", label: "Reverse") + .AddItemScriptBlock(@"""$($_.ReverseOff)$($_.ReverseOff.Replace(""""`e"""",'`e'))$($_.Reset)""", label: "ReverseOff") + .AddItemScriptBlock(@"""$($_.ItalicOff)$($_.ItalicOff.Replace(""""`e"""",'`e'))$($_.Reset)""", label: "ItalicOff") + .AddItemScriptBlock(@"""$($_.Italic)$($_.Italic.Replace(""""`e"""",'`e'))$($_.Reset)""", label: "Italic") + .AddItemScriptBlock(@"""$($_.UnderlineOff)$($_.UnderlineOff.Replace(""""`e"""",'`e'))$($_.Reset)""", label: "UnderlineOff") + .AddItemScriptBlock(@"""$($_.Underline)$($_.Underline.Replace(""""`e"""",'`e'))$($_.Reset)""", label: "Underline") + .AddItemProperty(@"OutputRendering") + .AddItemScriptBlock(@"""$($_.Formatting.FormatAccent)$($_.Formatting.FormatAccent.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Formatting.FormatAccent") + .AddItemScriptBlock(@"""$($_.Formatting.ErrorAccent)$($_.Formatting.ErrorAccent.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Formatting.ErrorAccent") + .AddItemScriptBlock(@"""$($_.Formatting.Error)$($_.Formatting.Error.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Formatting.Error") + .AddItemScriptBlock(@"""$($_.Formatting.Warning)$($_.Formatting.Warning.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Formatting.Warning") + .AddItemScriptBlock(@"""$($_.Formatting.Verbose)$($_.Formatting.Verbose.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Formatting.Verbose") + .AddItemScriptBlock(@"""$($_.Formatting.Debug)$($_.Formatting.Debug.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Formatting.Debug") + .AddItemScriptBlock(@"""$($_.Foreground.Black)$($_.Foreground.Black.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Foreground.Black") + .AddItemScriptBlock(@"""$($_.Foreground.White)$($_.Foreground.White.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Foreground.White") + .AddItemScriptBlock(@"""$($_.Foreground.DarkGray)$($_.Foreground.DarkGray.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Foreground.DarkGray") + .AddItemScriptBlock(@"""$($_.Foreground.LightGray)$($_.Foreground.LightGray.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Foreground.LightGray") + .AddItemScriptBlock(@"""$($_.Foreground.Red)$($_.Foreground.Red.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Foreground.Red") + .AddItemScriptBlock(@"""$($_.Foreground.LightRed)$($_.Foreground.LightRed.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Foreground.LightRed") + .AddItemScriptBlock(@"""$($_.Foreground.Magenta)$($_.Foreground.Magenta.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Foreground.Magenta") + .AddItemScriptBlock(@"""$($_.Foreground.LightMagenta)$($_.Foreground.LightMagenta.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Foreground.LightMagenta") + .AddItemScriptBlock(@"""$($_.Foreground.Blue)$($_.Foreground.Blue.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Foreground.Blue") + .AddItemScriptBlock(@"""$($_.Foreground.LightBlue)$($_.Foreground.LightBlue.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Foreground.LightBlue") + .AddItemScriptBlock(@"""$($_.Foreground.Cyan)$($_.Foreground.Cyan.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Foreground.Cyan") + .AddItemScriptBlock(@"""$($_.Foreground.LightCyan)$($_.Foreground.LightCyan.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Foreground.LightCyan") + .AddItemScriptBlock(@"""$($_.Foreground.Green)$($_.Foreground.Green.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Foreground.Green") + .AddItemScriptBlock(@"""$($_.Foreground.LightGreen)$($_.Foreground.LightGreen.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Foreground.LightGreen") + .AddItemScriptBlock(@"""$($_.Foreground.Yellow)$($_.Foreground.Yellow.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Foreground.Yellow") + .AddItemScriptBlock(@"""$($_.Foreground.LightYellow)$($_.Foreground.LightYellow.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Foreground.LightYellow") + .AddItemScriptBlock(@"""$($_.Background.Black)$($_.Background.Black.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Background.Black") + .AddItemScriptBlock(@"""$($_.Background.White)$($_.Background.White.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Background.White") + .AddItemScriptBlock(@"""$($_.Background.DarkGray)$($_.Background.DarkGray.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Background.DarkGray") + .AddItemScriptBlock(@"""$($_.Background.LightGray)$($_.Background.LightGray.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Background.LightGray") + .AddItemScriptBlock(@"""$($_.Background.Red)$($_.Background.Red.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Background.Red") + .AddItemScriptBlock(@"""$($_.Background.LightRed)$($_.Background.LightRed.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Background.LightRed") + .AddItemScriptBlock(@"""$($_.Background.Magenta)$($_.Background.Magenta.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Background.Magenta") + .AddItemScriptBlock(@"""$($_.Background.LightMagenta)$($_.Background.LightMagenta.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Background.LightMagenta") + .AddItemScriptBlock(@"""$($_.Background.Blue)$($_.Background.Blue.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Background.Blue") + .AddItemScriptBlock(@"""$($_.Background.LightBlue)$($_.Background.LightBlue.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Background.LightBlue") + .AddItemScriptBlock(@"""$($_.Background.Cyan)$($_.Background.Cyan.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Background.Cyan") + .AddItemScriptBlock(@"""$($_.Background.LightCyan)$($_.Background.LightCyan.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Background.LightCyan") + .AddItemScriptBlock(@"""$($_.Background.Green)$($_.Background.Green.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Background.Green") + .AddItemScriptBlock(@"""$($_.Background.LightGreen)$($_.Background.LightGreen.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Background.LightGreen") + .AddItemScriptBlock(@"""$($_.Background.Yellow)$($_.Background.Yellow.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Background.Yellow") + .AddItemScriptBlock(@"""$($_.Background.LightYellow)$($_.Background.LightYellow.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Background.LightYellow") + .EndEntry() + .EndList()); + } + + private static IEnumerable ViewsOf_System_Management_Automation_PSStyleFormattingData() + { + yield return new FormatViewDefinition("System.Management.Automation.PSStyle+FormattingData", + ListControl.Create() + .StartEntry() + .AddItemScriptBlock(@"""$($_.FormatAccent)$($_.FormatAccent.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "FormatAccent") + .AddItemScriptBlock(@"""$($_.ErrorAccent)$($_.ErrorAccent.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "ErrorAccent") + .AddItemScriptBlock(@"""$($_.Error)$($_.Error.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Error") + .AddItemScriptBlock(@"""$($_.Warning)$($_.Warning.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Warning") + .AddItemScriptBlock(@"""$($_.Verbose)$($_.Verbose.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Formatting.Verbose") + .AddItemScriptBlock(@"""$($_.Debug)$($_.Debug.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Debug") + .EndEntry() + .EndList()); + } + + private static IEnumerable ViewsOf_System_Management_Automation_PSStyleForegroundColor() + { + yield return new FormatViewDefinition("System.Management.Automation.PSStyle+ForegroundColor", + ListControl.Create() + .StartEntry() + .AddItemScriptBlock(@"""$($_.Black)$($_.Black.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Black") + .AddItemScriptBlock(@"""$($_.White)$($_.White.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "White") + .AddItemScriptBlock(@"""$($_.DarkGray)$($_.DarkGray.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "DarkGray") + .AddItemScriptBlock(@"""$($_.LightGray)$($_.LightGray.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "LightGray") + .AddItemScriptBlock(@"""$($_.Red)$($_.Red.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Red") + .AddItemScriptBlock(@"""$($_.LightRed)$($_.LightRed.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "LightRed") + .AddItemScriptBlock(@"""$($_.Magenta)$($_.Magenta.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Magenta") + .AddItemScriptBlock(@"""$($_.LightMagenta)$($_.LightMagenta.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "LightMagenta") + .AddItemScriptBlock(@"""$($_.Blue)$($_.Blue.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Blue") + .AddItemScriptBlock(@"""$($_.LightBlue)$($_.LightBlue.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "LightBlue") + .AddItemScriptBlock(@"""$($_.Cyan)$($_.Cyan.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Cyan") + .AddItemScriptBlock(@"""$($_.LightCyan)$($_.LightCyan.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "LightCyan") + .AddItemScriptBlock(@"""$($_.Green)$($_.Green.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Green") + .AddItemScriptBlock(@"""$($_.LightGreen)$($_.LightGreen.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "LightGreen") + .AddItemScriptBlock(@"""$($_.Yellow)$($_.Yellow.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Yellow") + .AddItemScriptBlock(@"""$($_.LightYellow)$($_.LightYellow.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "LightYellow") + .EndEntry() + .EndList()); + } + + private static IEnumerable ViewsOf_System_Management_Automation_PSStyleBackgroundColor() + { + yield return new FormatViewDefinition("System.Management.Automation.PSStyle+ForegroundColor", + ListControl.Create() + .StartEntry() + .AddItemScriptBlock(@"""$($_.Black)$($_.Black.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Black") + .AddItemScriptBlock(@"""$($_.White)$($_.White.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "White") + .AddItemScriptBlock(@"""$($_.DarkGray)$($_.DarkGray.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "DarkGray") + .AddItemScriptBlock(@"""$($_.LightGray)$($_.LightGray.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "LightGray") + .AddItemScriptBlock(@"""$($_.Red)$($_.Red.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Red") + .AddItemScriptBlock(@"""$($_.LightRed)$($_.LightRed.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "LightRed") + .AddItemScriptBlock(@"""$($_.Magenta)$($_.Magenta.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Magenta") + .AddItemScriptBlock(@"""$($_.LightMagenta)$($_.LightMagenta.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "LightMagenta") + .AddItemScriptBlock(@"""$($_.Blue)$($_.Blue.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Blue") + .AddItemScriptBlock(@"""$($_.LightBlue)$($_.LightBlue.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "LightBlue") + .AddItemScriptBlock(@"""$($_.Cyan)$($_.Cyan.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Cyan") + .AddItemScriptBlock(@"""$($_.LightCyan)$($_.LightCyan.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "LightCyan") + .AddItemScriptBlock(@"""$($_.Green)$($_.Green.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Green") + .AddItemScriptBlock(@"""$($_.LightGreen)$($_.LightGreen.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "LightGreen") + .AddItemScriptBlock(@"""$($_.Yellow)$($_.Yellow.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Yellow") + .AddItemScriptBlock(@"""$($_.LightYellow)$($_.LightYellow.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "LightYellow") + .EndEntry() + .EndList()); + } } } diff --git a/src/System.Management.Automation/FormatAndOutput/common/BaseOutputtingCommand.cs b/src/System.Management.Automation/FormatAndOutput/common/BaseOutputtingCommand.cs index e3ff3608b9d..48ab1307681 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/BaseOutputtingCommand.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/BaseOutputtingCommand.cs @@ -181,7 +181,7 @@ private FormatShape ActiveFormattingShape { // we assume that the format context // contains the information - FormatShape shape = FormatShape.Table; // default + const FormatShape shape = FormatShape.Table; // default FormatOutputContext foc = this.FormatContext; if (foc == null || foc.Data.shapeInfo == null) diff --git a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/XmlLoaderBase.cs b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/XmlLoaderBase.cs index 773eb9d3777..a7e7df0a5d7 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/XmlLoaderBase.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/XmlLoaderBase.cs @@ -44,7 +44,7 @@ internal class TooManyErrorsException : TypeInfoDataBaseLoaderException /// internal class XmlLoaderLoggerEntry { - internal enum EntryType { Error, Trace }; + internal enum EntryType { Error, Trace } /// /// Type of information being logged. @@ -100,7 +100,7 @@ internal void LogEntry(XmlLoaderLoggerEntry entry) WriteToTracer(entry); } - private void WriteToTracer(XmlLoaderLoggerEntry entry) + private static void WriteToTracer(XmlLoaderLoggerEntry entry) { if (entry.entryType == XmlLoaderLoggerEntry.EntryType.Error) { @@ -378,7 +378,7 @@ private bool MatchNodeNameHelper(XmlNode n, string s, bool allowAttributes) // we differ only in case: flag this as an ERROR for the time being // and accept the comparison - string fmtString = "XML tag differ in case only {0} {1}"; + const string fmtString = "XML tag differ in case only {0} {1}"; ReportTrace(string.Format(CultureInfo.InvariantCulture, fmtString, n.Name, s)); match = true; @@ -420,7 +420,7 @@ internal bool MatchAttributeName(XmlAttribute a, string s) // we differ only in case: flag this as an ERROR for the time being // and accept the comparison - string fmtString = "XML attribute differ in case only {0} {1}"; + const string fmtString = "XML attribute differ in case only {0} {1}"; ReportTrace(string.Format(CultureInfo.InvariantCulture, fmtString, a.Name, s)); return true; } diff --git a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/displayDescriptionData.cs b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/displayDescriptionData.cs index 717ea07bdcd..f126dddcadc 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/displayDescriptionData.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/displayDescriptionData.cs @@ -774,7 +774,7 @@ internal static PSControlGroupBy Get(GroupBy groupBy) return new PSControlGroupBy { Expression = new DisplayEntry(expressionToken), - Label = (groupBy.startGroup.labelTextToken != null) ? groupBy.startGroup.labelTextToken.text : null + Label = groupBy.startGroup.labelTextToken?.text }; } diff --git a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/displayResourceManagerCache.cs b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/displayResourceManagerCache.cs index aafd09cc255..fbdd1287a02 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/displayResourceManagerCache.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/displayResourceManagerCache.cs @@ -13,7 +13,7 @@ internal sealed class DisplayResourceManagerCache { internal enum LoadingResult { NoError, AssemblyNotFound, ResourceNotFound, StringNotFound } - internal enum AssemblyBindingStatus { NotFound, FoundInGac, FoundInPath }; + internal enum AssemblyBindingStatus { NotFound, FoundInGac, FoundInPath } internal string GetTextTokenString(TextToken tt) { @@ -176,7 +176,7 @@ internal Assembly ResolveAssemblyName(string assemblyName) return retVal; } - private Assembly ResolveAssemblyNameInLoadedAssemblies(string assemblyName, bool fullName) + private static Assembly ResolveAssemblyNameInLoadedAssemblies(string assemblyName, bool fullName) { Assembly result = null; diff --git a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataManager.cs b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataManager.cs index 51be05505e6..c42bd21adc7 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataManager.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataManager.cs @@ -57,7 +57,7 @@ internal TypeInfoDataBaseManager() /// /// Host passed to . Can be null if no interactive questions should be asked. /// - /// + /// /// /// 1. FormatFile is not rooted. /// diff --git a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataQuery.cs b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataQuery.cs index 9547ac1e072..60953d22c26 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataQuery.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataQuery.cs @@ -219,7 +219,7 @@ private int MatchTypeIndex(string typeName, PSObject currentObject, PSPropertyEx return BestMatchIndexUndefined; } - private bool MatchCondition(PSObject currentObject, PSPropertyExpression ex) + private static bool MatchCondition(PSObject currentObject, PSPropertyExpression ex) { if (ex == null) return true; diff --git a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataXmlLoader.cs b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataXmlLoader.cs index 90a44c848b2..b68288ff9ab 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataXmlLoader.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataXmlLoader.cs @@ -586,7 +586,7 @@ private ControlBase LoadTableControlFromObjectModel(TableControl table, int view /// /// /// - private void LoadHeadersSectionFromObjectModel(TableControlBody tableBody, List headers) + private static void LoadHeadersSectionFromObjectModel(TableControlBody tableBody, List headers) { foreach (TableControlColumnHeader header in headers) { @@ -746,7 +746,7 @@ private ExpressionToken LoadExpressionFromObjectModel(DisplayEntry displayEntry, /// Load EntrySelectedBy (TypeName) into AppliesTo. /// /// - private AppliesTo LoadAppliesToSectionFromObjectModel(List selectedBy, List condition) + private static AppliesTo LoadAppliesToSectionFromObjectModel(List selectedBy, List condition) { AppliesTo appliesTo = new AppliesTo(); diff --git a/src/System.Management.Automation/FormatAndOutput/common/FormatMsgCtxManager.cs b/src/System.Management.Automation/FormatAndOutput/common/FormatMsgCtxManager.cs index 5ccfada75fa..3eabcc975a0 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/FormatMsgCtxManager.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/FormatMsgCtxManager.cs @@ -19,10 +19,15 @@ internal class FormatMessagesContextManager { // callbacks declarations internal delegate OutputContext FormatContextCreationCallback(OutputContext parentContext, FormatInfoData formatData); + internal delegate void FormatStartCallback(OutputContext c); + internal delegate void FormatEndCallback(FormatEndData fe, OutputContext c); + internal delegate void GroupStartCallback(OutputContext c); + internal delegate void GroupEndCallback(GroupEndData fe, OutputContext c); + internal delegate void PayloadCallback(FormatEntryData formatEntryData, OutputContext c); // callback instances diff --git a/src/System.Management.Automation/FormatAndOutput/common/FormatViewGenerator_Table.cs b/src/System.Management.Automation/FormatAndOutput/common/FormatViewGenerator_Table.cs index 7394589bb95..bfd3291dd46 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/FormatViewGenerator_Table.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/FormatViewGenerator_Table.cs @@ -137,7 +137,7 @@ private void FilterActiveAssociationList() // make sure we do not have too many properties // NOTE: this is an arbitrary number, chosen to be a sensitive default - int nMax = 10; + const int nMax = 10; if (activeAssociationList.Count > nMax) { diff --git a/src/System.Management.Automation/FormatAndOutput/common/FormatViewManager.cs b/src/System.Management.Automation/FormatAndOutput/common/FormatViewManager.cs index c158583e25b..0737e43476e 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/FormatViewManager.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/FormatViewManager.cs @@ -234,7 +234,7 @@ private static void ProcessUnknownViewName(TerminatingErrorContext errorContext, string msg = null; bool foundValidViews = false; string formatTypeName = null; - string separator = ", "; + const string separator = ", "; StringBuilder validViewFormats = new StringBuilder(); if (so != null && so.BaseObject != null && diff --git a/src/System.Management.Automation/FormatAndOutput/common/FormattingObjectsDeserializer.cs b/src/System.Management.Automation/FormatAndOutput/common/FormattingObjectsDeserializer.cs index d1b9523138b..285e4d4c02b 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/FormattingObjectsDeserializer.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/FormattingObjectsDeserializer.cs @@ -290,7 +290,7 @@ internal int DeserializeIntMemberVariable(PSObject so, string property) internal bool DeserializeBoolMemberVariable(PSObject so, string property, bool cannotBeNull = true) { var val = DeserializeMemberVariable(so, property, typeof(bool), cannotBeNull); - return (val == null) ? false : (bool)val; + return val != null && (bool)val; } internal WriteStreamType DeserializeWriteStreamTypeMemberVariable(PSObject so) diff --git a/src/System.Management.Automation/FormatAndOutput/common/ILineOutput.cs b/src/System.Management.Automation/FormatAndOutput/common/ILineOutput.cs index 83e39c4dd5d..32d4565da5d 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/ILineOutput.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/ILineOutput.cs @@ -4,6 +4,7 @@ using System.Globalization; using System.IO; using System.Management.Automation; +using System.Management.Automation.Internal; using System.Text; // interfaces for host interaction @@ -411,6 +412,9 @@ internal override int RowNumber internal override void WriteLine(string s) { CheckStopProcessing(); + + s = Utils.GetOutputString(s, isHost: false); + if (_suppressNewline) { _writer.Write(s); diff --git a/src/System.Management.Automation/FormatAndOutput/common/PSStyle.cs b/src/System.Management.Automation/FormatAndOutput/common/PSStyle.cs new file mode 100644 index 00000000000..f27a5b89da9 --- /dev/null +++ b/src/System.Management.Automation/FormatAndOutput/common/PSStyle.cs @@ -0,0 +1,404 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +namespace System.Management.Automation +{ + #region OutputRendering + /// + /// Defines the options for output rendering. + /// + public enum OutputRendering + { + /// Automatic by PowerShell. + Automatic = 0, + + /// Render as plaintext. + PlainText = 1, + + /// Render as ANSI. + Ansi = 2, + + /// Render ANSI only to host. + Host = 3, + } + #endregion OutputRendering + + #region PSStyle + /// + /// Contains configuration for how PowerShell renders text. + /// + public class PSStyle + { + /// + /// Contains foreground colors. + /// + public class ForegroundColor + { + /// + /// Gets the color black. + /// + public string Black { get; } = "\x1b[30m"; + + /// + /// Gets the color blue. + /// + public string Blue { get; } = "\x1b[34m"; + + /// + /// Gets the color cyan. + /// + public string Cyan { get; } = "\x1b[36m"; + + /// + /// Gets the color dark gray. + /// + public string DarkGray { get; } = "\x1b[90m"; + + /// + /// Gets the color green. + /// + public string Green { get; } = "\x1b[32m"; + + /// + /// Gets the color light blue. + /// + public string LightBlue { get; } = "\x1b[94m"; + + /// + /// Gets the color light cyan. + /// + public string LightCyan { get; } = "\x1b[96m"; + + /// + /// Gets the color light gray. + /// + public string LightGray { get; } = "\x1b[97m"; + + /// + /// Gets the color light green. + /// + public string LightGreen { get; } = "\x1b[92m"; + + /// + /// Gets the color light magenta. + /// + public string LightMagenta { get; } = "\x1b[95m"; + + /// + /// Gets the color light red. + /// + public string LightRed { get; } = "\x1b[91m"; + + /// + /// Gets the color light yellow. + /// + public string LightYellow { get; } = "\x1b[93m"; + + /// + /// Gets the color magenta. + /// + public string Magenta { get; } = "\x1b[35m"; + + /// + /// Gets the color read. + /// + public string Red { get; } = "\x1b[31m"; + + /// + /// Gets the color white. + /// + public string White { get; } = "\x1b[37m"; + + /// + /// Gets the color yellow. + /// + public string Yellow { get; } = "\x1b[33m"; + + /// + /// Set as RGB (Red, Green, Blue). + /// + /// Byte value representing red. + /// Byte value representing green. + /// Byte value representing blue. + /// String representing ANSI code for RGB value. + public string FromRgb(byte red, byte green, byte blue) + { + return $"\x1b[38;2;{red};{green};{blue}m"; + } + + /// + /// The color set as RGB as a single number. + /// + /// RGB value specified as an integer. + /// String representing ANSI code for RGB value. + public string FromRgb(int rgb) + { + byte red, green, blue; + blue = (byte)(rgb & 0xFF); + rgb >>= 8; + green = (byte)(rgb & 0xFF); + rgb >>= 8; + red = (byte)(rgb & 0xFF); + + return FromRgb(red, green, blue); + } + } + + /// + /// Contains background colors. + /// + public class BackgroundColor + { + /// + /// Gets the color black. + /// + public string Black { get; } = "\x1b[40m"; + + /// + /// Gets the color blue. + /// + public string Blue { get; } = "\x1b[44m"; + + /// + /// Gets the color cyan. + /// + public string Cyan { get; } = "\x1b[46m"; + + /// + /// Gets the color dark gray. + /// + public string DarkGray { get; } = "\x1b[100m"; + + /// + /// Gets the color green. + /// + public string Green { get; } = "\x1b[42m"; + + /// + /// Gets the color light blue. + /// + public string LightBlue { get; } = "\x1b[104m"; + + /// + /// Gets the color light cyan. + /// + public string LightCyan { get; } = "\x1b[106m"; + + /// + /// Gets the color light gray. + /// + public string LightGray { get; } = "\x1b[107m"; + + /// + /// Gets the color light green. + /// + public string LightGreen { get; } = "\x1b[102m"; + + /// + /// Gets the color light magenta. + /// + public string LightMagenta { get; } = "\x1b[105m"; + + /// + /// Gets the color light red. + /// + public string LightRed { get; } = "\x1b[101m"; + + /// + /// Gets the color light yellow. + /// + public string LightYellow { get; } = "\x1b[103m"; + + /// + /// Gets the color magenta. + /// + public string Magenta { get; } = "\x1b[45m"; + + /// + /// Gets the color read. + /// + public string Red { get; } = "\x1b[41m"; + + /// + /// Gets the color white. + /// + public string White { get; } = "\x1b[47m"; + + /// + /// Gets the color yellow. + /// + public string Yellow { get; } = "\x1b[43m"; + + /// + /// The color set as RGB (Red, Green, Blue). + /// + /// Byte value representing red. + /// Byte value representing green. + /// Byte value representing blue. + /// String representing ANSI code for RGB value. + public string FromRgb(byte red, byte green, byte blue) + { + return $"\x1b[48;2;{red};{green};{blue}m"; + } + + /// + /// The color set as RGB as a single number. + /// + /// RGB value specified as an integer. + /// String representing ANSI code for RGB value. + public string FromRgb(int rgb) + { + byte red, green, blue; + blue = (byte)(rgb & 0xFF); + rgb >>= 8; + green = (byte)(rgb & 0xFF); + rgb >>= 8; + red = (byte)(rgb & 0xFF); + + return FromRgb(red, green, blue); + } + } + + /// + /// Contains formatting styles for steams and objects. + /// + public class FormattingData + { + /// + /// Gets or sets the accent style for formatting. + /// + public string FormatAccent { get; set; } = "\x1b[32;1m"; + + /// + /// Gets or sets the accent style for errors. + /// + public string ErrorAccent { get; set; } = "\x1b[36;1m"; + + /// + /// Gets or sets the style for error messages. + /// + public string Error { get; set; } = "\x1b[31;1m"; + + /// + /// Gets or sets the style for warning messages. + /// + public string Warning { get; set; } = "\x1b[33;1m"; + + /// + /// Gets or sets the style for verbose messages. + /// + public string Verbose { get; set; } = "\x1b[33;1m"; + + /// + /// Gets or sets the style for debug messages. + /// + public string Debug { get; set; } = "\x1b[33;1m"; + } + + /// + /// Gets or sets the rendering mode for output. + /// + public OutputRendering OutputRendering { get; set; } = OutputRendering.Automatic; + + /// + /// Gets value to turn off all attributes. + /// + public string Reset { get; } = "\x1b[0m"; + + /// + /// Gets value to turn off blink. + /// + public string BlinkOff { get; } = "\x1b[5m"; + + /// + /// Gets value to turn on blink. + /// + public string Blink { get; } = "\x1b[25m"; + + /// + /// Gets value to turn off bold. + /// + public string BoldOff { get; } = "\x1b[22m"; + + /// + /// Gets value to turn on blink. + /// + public string Bold { get; } = "\x1b[1m"; + + /// + /// Gets value to turn on hidden. + /// + public string Hidden { get; } = "\x1b[8m"; + + /// + /// Gets value to turn off hidden. + /// + public string HiddenOff { get; } = "\x1b[28m"; + + /// + /// Gets value to turn on reverse. + /// + public string Reverse { get; } = "\x1b[7m"; + + /// + /// Gets value to turn off reverse. + /// + public string ReverseOff { get; } = "\x1b[27m"; + + /// + /// Gets value to turn off standout. + /// + public string ItalicOff { get; } = "\x1b[23m"; + + /// + /// Gets value to turn on standout. + /// + public string Italic { get; } = "\x1b[3m"; + + /// + /// Gets value to turn off underlined. + /// + public string UnderlineOff { get; } = "\x1b[24m"; + + /// + /// Gets value to turn on underlined. + /// + public string Underline { get; } = "\x1b[4m"; + + /// + /// Gets the formatting rendering settings. + /// + public FormattingData Formatting { get; } + + /// + /// Gets foreground colors. + /// + public ForegroundColor Foreground { get; } + + /// + /// Gets background colors. + /// + public BackgroundColor Background { get; } + + private static readonly PSStyle s_psstyle = new PSStyle(); + + private PSStyle() + { + Formatting = new FormattingData(); + Foreground = new ForegroundColor(); + Background = new BackgroundColor(); + } + + /// + /// Gets singleton instance. + /// + public static PSStyle Instance + { + get + { + return s_psstyle; + } + } + } + #endregion PSStyle +} diff --git a/src/System.Management.Automation/FormatAndOutput/common/StringDecorated.cs b/src/System.Management.Automation/FormatAndOutput/common/StringDecorated.cs new file mode 100644 index 00000000000..3c1041f9c47 --- /dev/null +++ b/src/System.Management.Automation/FormatAndOutput/common/StringDecorated.cs @@ -0,0 +1,175 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#nullable enable + +using System.Text.RegularExpressions; + +namespace System.Management.Automation.Internal +{ + /// + /// Extensions to String type to calculate and render decorated content. + /// + public class StringDecorated + { + private readonly bool _isDecorated; + private readonly string _text; + private string? _plaintextcontent; + + private string PlainText + { + get + { + if (_plaintextcontent == null) + { + _plaintextcontent = ValueStringDecorated.AnsiRegex.Replace(_text, string.Empty); + } + + return _plaintextcontent; + } + } + + /// + /// Initializes a new instance of the class. + /// + /// The input string. + public StringDecorated(string text) + { + _text = text; + _isDecorated = text.Contains(ValueStringDecorated.ESC); + } + + /// + /// Gets a value indicating whether the string contains decoration. + /// + /// Boolean if the string contains decoration. + public bool IsDecorated => _isDecorated; + + /// + /// Gets the length of content sans escape sequences. + /// + /// Length of content sans escape sequences. + public int ContentLength => PlainText.Length; + + /// + /// Render the decorarted string using automatic output rendering. + /// + /// Rendered string based on automatic output rendering. + public override string ToString() => _isDecorated ? ToString(OutputRendering.Automatic) : _text; + + /// + /// Return string representation of content depending on output rendering mode. + /// + /// Specify how to render the text content. + /// Rendered string based on outputRendering. + public string ToString(OutputRendering outputRendering) + { + if (!_isDecorated) + { + return _text; + } + + if (outputRendering == OutputRendering.Automatic) + { + outputRendering = OutputRendering.Ansi; + if (PSStyle.Instance.OutputRendering == OutputRendering.PlainText) + { + outputRendering = OutputRendering.PlainText; + } + } + + if (outputRendering == OutputRendering.PlainText) + { + return PlainText; + } + else + { + return _text; + } + } + } + + internal struct ValueStringDecorated + { + internal const char ESC = '\x1b'; + private readonly bool _isDecorated; + private readonly string _text; + private string? _plaintextcontent; + + private string PlainText + { + get + { + if (_plaintextcontent == null) + { + _plaintextcontent = AnsiRegex.Replace(_text, string.Empty); + } + + return _plaintextcontent; + } + } + + // replace regex with .NET 6 API once available + internal static readonly Regex AnsiRegex = new Regex(@"\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])", RegexOptions.Compiled); + + /// + /// Initializes a new instance of the struct. + /// + /// The input string. + public ValueStringDecorated(string text) + { + _text = text; + _isDecorated = text.Contains(ESC); + _plaintextcontent = null; + } + + /// + /// Gets a value indicating whether the string contains decoration. + /// + /// Boolean if the string contains decoration. + public bool IsDecorated => _isDecorated; + + /// + /// Gets the length of content sans escape sequences. + /// + /// Length of content sans escape sequences. + public int ContentLength => PlainText.Length; + + /// + /// Render the decorarted string using automatic output rendering. + /// + /// Rendered string based on automatic output rendering. + public override string ToString() => _isDecorated ? ToString(OutputRendering.Automatic) : _text; + + /// + /// Return string representation of content depending on output rendering mode. + /// + /// Specify how to render the text content. + /// Rendered string based on outputRendering. + public string ToString(OutputRendering outputRendering) + { + if (!_isDecorated) + { + return _text; + } + + if (outputRendering == OutputRendering.Automatic) + { + outputRendering = OutputRendering.Ansi; + if (PSStyle.Instance.OutputRendering == OutputRendering.PlainText) + { + outputRendering = OutputRendering.PlainText; + } + } + + if (outputRendering == OutputRendering.PlainText) + { + return PlainText; + } + else + { + return _text; + } + } + } +} diff --git a/src/System.Management.Automation/FormatAndOutput/common/Utilities/Mshexpression.cs b/src/System.Management.Automation/FormatAndOutput/common/Utilities/Mshexpression.cs index b9419c1ec0e..68921ddb0e8 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/Utilities/Mshexpression.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/Utilities/Mshexpression.cs @@ -66,7 +66,7 @@ public PSPropertyExpression(string s) /// Create a property expression with a wildcard pattern. /// /// Property name pattern to match. - /// true if no further attempts should be made to resolve wildcards. + /// if no further attempts should be made to resolve wildcards. /// public PSPropertyExpression(string s, bool isResolved) { @@ -354,7 +354,7 @@ private PSPropertyExpressionResult GetValue(PSObject target, bool eatExceptions) } } - private PSObject IfHashtableWrapAsPSCustomObject(PSObject target, out bool wrapped) + private static PSObject IfHashtableWrapAsPSCustomObject(PSObject target, out bool wrapped) { wrapped = false; diff --git a/src/System.Management.Automation/FormatAndOutput/out-console/ConsoleLineOutput.cs b/src/System.Management.Automation/FormatAndOutput/out-console/ConsoleLineOutput.cs index decceac5108..4750b099b01 100644 --- a/src/System.Management.Automation/FormatAndOutput/out-console/ConsoleLineOutput.cs +++ b/src/System.Management.Automation/FormatAndOutput/out-console/ConsoleLineOutput.cs @@ -222,6 +222,7 @@ internal override int RowNumber internal override void WriteLine(string s) { CheckStopProcessing(); + // delegate the action to the helper, // that will properly break the string into // screen lines @@ -351,6 +352,7 @@ private void OnWrite(string s) #if TEST_MULTICELL_ON_SINGLE_CELL_LOCALE s = ((DisplayCellsTest)this._displayCellsPSHost).GenerateTestString(s); #endif + switch (this.WriteStream) { case WriteStreamType.Error: diff --git a/src/System.Management.Automation/System.Management.Automation.csproj b/src/System.Management.Automation/System.Management.Automation.csproj index e8d5ff5911d..562b98361ac 100644 --- a/src/System.Management.Automation/System.Management.Automation.csproj +++ b/src/System.Management.Automation/System.Management.Automation.csproj @@ -14,7 +14,7 @@ - + diff --git a/src/System.Management.Automation/cimSupport/cmdletization/EnumWriter.cs b/src/System.Management.Automation/cimSupport/cmdletization/EnumWriter.cs index 23c7a09c4f2..66649420101 100644 --- a/src/System.Management.Automation/cimSupport/cmdletization/EnumWriter.cs +++ b/src/System.Management.Automation/cimSupport/cmdletization/EnumWriter.cs @@ -17,14 +17,14 @@ internal static class EnumWriter private static ModuleBuilder CreateModuleBuilder() { - AssemblyName aName = new AssemblyName(namespacePrefix); + AssemblyName aName = new(namespacePrefix); AssemblyBuilder ab = AssemblyBuilder.DefineDynamicAssembly(aName, AssemblyBuilderAccess.Run); ModuleBuilder mb = ab.DefineDynamicModule(aName.Name); return mb; } - private static Lazy s_moduleBuilder = new Lazy(CreateModuleBuilder, isThreadSafe: true); - private static object s_moduleBuilderUsageLock = new object(); + private static Lazy s_moduleBuilder = new(CreateModuleBuilder, isThreadSafe: true); + private static object s_moduleBuilderUsageLock = new(); internal static string GetEnumFullName(EnumMetadataEnum enumMetadata) { diff --git a/src/System.Management.Automation/cimSupport/cmdletization/MethodInvocationInfo.cs b/src/System.Management.Automation/cimSupport/cmdletization/MethodInvocationInfo.cs index 81a4c33062f..1640dec33b9 100644 --- a/src/System.Management.Automation/cimSupport/cmdletization/MethodInvocationInfo.cs +++ b/src/System.Management.Automation/cimSupport/cmdletization/MethodInvocationInfo.cs @@ -18,7 +18,7 @@ public sealed class MethodInvocationInfo /// /// Name of the method to invoke. /// Method parameters. - /// Return value of the method (ok to pass null if the method doesn't return anything). + /// Return value of the method (ok to pass if the method doesn't return anything). public MethodInvocationInfo(string name, IEnumerable parameters, MethodParameter returnValue) { if (name == null) throw new ArgumentNullException(nameof(name)); @@ -48,16 +48,16 @@ public MethodInvocationInfo(string name, IEnumerable parameters public KeyedCollection Parameters { get; } /// - /// Return value of the method. Can be null if the method doesn't return anything. + /// Return value of the method. Can be if the method doesn't return anything. /// public MethodParameter ReturnValue { get; } internal IEnumerable GetArgumentsOfType() where T : class { - List result = new List(); + List result = new(); foreach (var methodParameter in this.Parameters) { - if (MethodParameterBindings.In != (methodParameter.Bindings & MethodParameterBindings.In)) + if ((methodParameter.Bindings & MethodParameterBindings.In) != MethodParameterBindings.In) { continue; } diff --git a/src/System.Management.Automation/cimSupport/cmdletization/MethodParameter.cs b/src/System.Management.Automation/cimSupport/cmdletization/MethodParameter.cs index d9b08b27179..f044d4d422f 100644 --- a/src/System.Management.Automation/cimSupport/cmdletization/MethodParameter.cs +++ b/src/System.Management.Automation/cimSupport/cmdletization/MethodParameter.cs @@ -43,7 +43,7 @@ public sealed class MethodParameter public Type ParameterType { get; set; } /// - /// Contents of the ETS type attribute in the CDXML file (or null if that attribute was not specified). + /// Contents of the ETS type attribute in the CDXML file (or if that attribute was not specified). /// The expectation is that the CmdletAdapter will stamp this value onto PSTypeNames of emitted objects. /// public string ParameterTypeName { get; set; } diff --git a/src/System.Management.Automation/cimSupport/cmdletization/ObjectModelWrapper.cs b/src/System.Management.Automation/cimSupport/cmdletization/ObjectModelWrapper.cs index 289ad0c3a76..a840ca527fd 100644 --- a/src/System.Management.Automation/cimSupport/cmdletization/ObjectModelWrapper.cs +++ b/src/System.Management.Automation/cimSupport/cmdletization/ObjectModelWrapper.cs @@ -127,7 +127,7 @@ public virtual void StopProcessing() /// /// The object on which to invoke the method. /// Method invocation details. - /// true if successful method invocations should emit downstream the being operated on. + /// if successful method invocations should emit downstream the being operated on. public virtual void ProcessRecord(TObjectInstance objectInstance, MethodInvocationInfo methodInvocationInfo, bool passThru) { throw new NotImplementedException(); @@ -138,7 +138,7 @@ public virtual void ProcessRecord(TObjectInstance objectInstance, MethodInvocati /// /// Query parameters. /// Method invocation details. - /// true if successful method invocations should emit downstream the object instance being operated on. + /// if successful method invocations should emit downstream the object instance being operated on. public virtual void ProcessRecord(QueryBuilder query, MethodInvocationInfo methodInvocationInfo, bool passThru) { throw new NotImplementedException(); @@ -182,7 +182,7 @@ public string ClassName /// /// Name of the class (from the object model handled by this ObjectModelWrapper) that is wrapped by the currently executing cmdlet. - /// This value can be null (i.e. when ClassVersion attribute is omitted in the ps1xml) + /// This value can be (i.e. when ClassVersion attribute is omitted in the ps1xml) /// public string ClassVersion { diff --git a/src/System.Management.Automation/cimSupport/cmdletization/QueryBuilder.cs b/src/System.Management.Automation/cimSupport/cmdletization/QueryBuilder.cs index a1ce1d726ec..36f781d98a0 100644 --- a/src/System.Management.Automation/cimSupport/cmdletization/QueryBuilder.cs +++ b/src/System.Management.Automation/cimSupport/cmdletization/QueryBuilder.cs @@ -52,8 +52,8 @@ public abstract class QueryBuilder /// Property name to query on. /// Property values to accept in the query. /// - /// true if should be treated as a containing a wildcard pattern; - /// false otherwise + /// if should be treated as a containing a wildcard pattern; + /// otherwise. /// /// /// Describes how to handle filters that didn't match any objects @@ -69,8 +69,8 @@ public virtual void FilterByProperty(string propertyName, IEnumerable allowedPro /// Property name to query on. /// Property values to reject in the query. /// - /// true if should be treated as a containing a wildcard pattern; - /// false otherwise + /// if should be treated as a containing a wildcard pattern; + /// otherwise. /// /// /// Describes how to handle filters that didn't match any objects diff --git a/src/System.Management.Automation/cimSupport/cmdletization/ScriptWriter.cs b/src/System.Management.Automation/cimSupport/cmdletization/ScriptWriter.cs index 3757319c9ab..3197361faea 100644 --- a/src/System.Management.Automation/cimSupport/cmdletization/ScriptWriter.cs +++ b/src/System.Management.Automation/cimSupport/cmdletization/ScriptWriter.cs @@ -234,10 +234,10 @@ private string GetCmdletName(CommonCmdletMetadata cmdletMetadata) return verb + "-" + noun; } - private string GetCmdletAttributes(CommonCmdletMetadata cmdletMetadata) + private static string GetCmdletAttributes(CommonCmdletMetadata cmdletMetadata) { // Generate the script for the Alias and Obsolete Attribute if any is declared in CDXML - StringBuilder attributes = new StringBuilder(150); + StringBuilder attributes = new(150); if (cmdletMetadata.Aliases != null) { attributes.Append("[Alias('" + string.Join("','", cmdletMetadata.Aliases.Select(alias => CodeGeneration.EscapeSingleQuotedStringContent(alias))) + "')]"); @@ -257,12 +257,12 @@ private string GetCmdletAttributes(CommonCmdletMetadata cmdletMetadata) private Dictionary GetCommonParameters() { - Dictionary commonParameters = new Dictionary(StringComparer.OrdinalIgnoreCase); + Dictionary commonParameters = new(StringComparer.OrdinalIgnoreCase); - InternalParameterMetadata internalParameterMetadata = new InternalParameterMetadata(_objectModelWrapper, false); + InternalParameterMetadata internalParameterMetadata = new(_objectModelWrapper, false); foreach (CompiledCommandParameter compiledCommandParameter in internalParameterMetadata.BindableParameters.Values) { - ParameterMetadata parameterMetadata = new ParameterMetadata(compiledCommandParameter); + ParameterMetadata parameterMetadata = new(compiledCommandParameter); foreach (ParameterSetMetadata psetMetadata in parameterMetadata.ParameterSets.Values) { if (psetMetadata.ValueFromPipeline) @@ -335,7 +335,7 @@ private Dictionary GetCommonParameters() private static List GetCommonParameterSets(Dictionary commonParameters) { - Dictionary parameterSetNames = new Dictionary(StringComparer.OrdinalIgnoreCase); + Dictionary parameterSetNames = new(StringComparer.OrdinalIgnoreCase); foreach (ParameterMetadata parameter in commonParameters.Values) { foreach (string parameterSetName in parameter.ParameterSets.Keys) @@ -352,7 +352,7 @@ private static List GetCommonParameterSets(Dictionary result = new List(parameterSetNames.Keys); + List result = new(parameterSetNames.Keys); result.Sort(StringComparer.Ordinal); // to have a deterministic order of parameter sets (also means that Ordinal instead of OrdinalIgnoreCase is ok) return result; } @@ -365,7 +365,7 @@ private string GetMethodParameterSet(StaticMethodMetadata staticMethod) private List GetMethodParameterSets(StaticCmdletMetadata staticCmdlet) { - Dictionary parameterSetNames = new Dictionary(StringComparer.OrdinalIgnoreCase); + Dictionary parameterSetNames = new(StringComparer.OrdinalIgnoreCase); foreach (StaticMethodMetadata method in staticCmdlet.Method) { @@ -386,7 +386,7 @@ private List GetMethodParameterSets(StaticCmdletMetadata staticCmdlet) return new List(parameterSetNames.Keys); } - private Dictionary _staticMethodMetadataToUniqueId = new Dictionary(); + private Dictionary _staticMethodMetadataToUniqueId = new(); private string GetMethodParameterSet(CommonMethodMetadata methodMetadata) { @@ -404,7 +404,7 @@ private string GetMethodParameterSet(CommonMethodMetadata methodMetadata) private List GetMethodParameterSets(InstanceCmdletMetadata instanceCmdlet) { - Dictionary parameterSetNames = new Dictionary(StringComparer.OrdinalIgnoreCase); + Dictionary parameterSetNames = new(StringComparer.OrdinalIgnoreCase); InstanceMethodMetadata method = instanceCmdlet.Method; string parameterSetName = GetMethodParameterSet(method); @@ -436,7 +436,7 @@ private GetCmdletParameters GetGetCmdletParameters(InstanceCmdletMetadata instan private List GetQueryParameterSets(InstanceCmdletMetadata instanceCmdlet) { - Dictionary parameterSetNames = new Dictionary(StringComparer.OrdinalIgnoreCase); + Dictionary parameterSetNames = new(StringComparer.OrdinalIgnoreCase); var parameters = new List(); bool anyQueryParameters = false; @@ -555,7 +555,7 @@ private ParameterMetadata GetParameter( parameterName = objectModelParameterName; } - ParameterMetadata parameterMetadata = new ParameterMetadata(parameterName); + ParameterMetadata parameterMetadata = new(parameterName); parameterMetadata.ParameterType = GetDotNetType(parameterTypeMetadata); if (typeof(PSCredential).Equals(parameterMetadata.ParameterType)) { @@ -645,7 +645,7 @@ private ParameterMetadata GetParameter( if (parameterCmdletization.ValidateSet != null) { - List allowedValues = new List(); + List allowedValues = new(); foreach (string allowedValue in parameterCmdletization.ValidateSet) { allowedValues.Add(allowedValue); @@ -803,9 +803,9 @@ private CommandMetadata GetCommandMetadata(CommonCmdletMetadata cmdletMetadata) confirmImpact = (System.Management.Automation.ConfirmImpact)(int)cmdletMetadata.ConfirmImpact; } - Dictionary parameters = new Dictionary(StringComparer.OrdinalIgnoreCase); + Dictionary parameters = new(StringComparer.OrdinalIgnoreCase); - CommandMetadata commandMetadata = new CommandMetadata( + CommandMetadata commandMetadata = new( name: this.GetCmdletName(cmdletMetadata), commandType: CommandTypes.Cmdlet, isProxyForCmdlet: true, @@ -829,7 +829,7 @@ private static string EscapeModuleNameForHelpComment(string name) { Dbg.Assert(name != null, "Caller should verify name != null"); - StringBuilder result = new StringBuilder(name.Length); + StringBuilder result = new(name.Length); foreach (char c in name) { if (("\"'`$#".IndexOf(c) == (-1)) && @@ -850,10 +850,10 @@ private static List> GetCombinations(params IEnumerable[] x if (x.Length == 1) { - List> result = new List>(); + List> result = new(); foreach (string s in x[0]) { - List subresult = new List(); + List subresult = new(); subresult.Add(s); result.Add(subresult); } @@ -866,12 +866,12 @@ private static List> GetCombinations(params IEnumerable[] x Array.Copy(x, 0, smallX, 0, smallX.Length); List> smallResult = GetCombinations(smallX); - List> result = new List>(); + List> result = new(); foreach (List smallSubresult in smallResult) { foreach (string s in x[x.Length - 1]) { - List newsubresult = new List(smallSubresult); + List newsubresult = new(smallSubresult); newsubresult.Add(s); result.Add(newsubresult); } @@ -941,7 +941,7 @@ private static void MultiplyParameterSets( foreach (ParameterMetadata parameter in parameters.Values) { - List> oldParameterSets = new List>(parameter.ParameterSets); + List> oldParameterSets = new(parameter.ParameterSets); parameter.ParameterSets.Clear(); foreach (KeyValuePair oldParameterSet in oldParameterSets) @@ -964,7 +964,7 @@ private static IEnumerable MultiplyParameterSets( string parameterSetNameTemplate, // {0} is the original parameter set, other ones are taken from the otherParameterSets array params IEnumerable[] otherParameterSets) { - List result = new List(); + List result = new(); List> combinations = GetCombinations(otherParameterSets); foreach (List combination in combinations) @@ -1086,7 +1086,7 @@ private static void GenerateSingleMethodParameterProcessing( prefix); } - if (MethodParameterBindings.In == (methodParameterBindings & MethodParameterBindings.In)) + if ((methodParameterBindings & MethodParameterBindings.In) == MethodParameterBindings.In) { Dbg.Assert(cmdletParameterName != null, "Called should verify cmdletParameterName!=null for 'in' parameters"); @@ -1114,7 +1114,7 @@ private static void GenerateSingleMethodParameterProcessing( CodeGeneration.EscapeSingleQuotedStringContent(cmdletParameterTypeName), CodeGeneration.EscapeSingleQuotedStringContent(methodParameterBindings.ToString())); - if (MethodParameterBindings.In == (methodParameterBindings & MethodParameterBindings.In)) + if ((methodParameterBindings & MethodParameterBindings.In) == MethodParameterBindings.In) { output.WriteLine("{0}}}", prefix); } @@ -1139,8 +1139,8 @@ private void GenerateMethodParametersProcessing( out string outputTypeAttributeDeclaration) { methodParameters = new Dictionary(StringComparer.OrdinalIgnoreCase); - StringBuilder outputTypeAttributeDeclarationBuilder = new StringBuilder(); - StringWriter output = new StringWriter(CultureInfo.InvariantCulture); + StringBuilder outputTypeAttributeDeclarationBuilder = new(); + StringWriter output = new(CultureInfo.InvariantCulture); output.WriteLine(" $__cmdletization_methodParameters = [System.Collections.Generic.List[Microsoft.PowerShell.Cmdletization.MethodParameter]]::new()"); output.WriteLine(); @@ -1170,8 +1170,8 @@ string parameterSetName in output.WriteLine(") -contains $_ } {"); } - List typesOfOutParameters = new List(); - List etsTypesOfOutParameters = new List(); + List typesOfOutParameters = new(); + List etsTypesOfOutParameters = new(); if (method.Parameters != null) { foreach (StaticMethodParameterMetadata methodParameter in method.Parameters) @@ -1222,7 +1222,7 @@ string parameterSetName in methodParameter.ParameterName, methodParameterBindings); - if (MethodParameterBindings.Out == (methodParameterBindings & MethodParameterBindings.Out)) + if ((methodParameterBindings & MethodParameterBindings.Out) == MethodParameterBindings.Out) { typesOfOutParameters.Add(dotNetTypeOfParameter); etsTypesOfOutParameters.Add(methodParameter.Type.ETSType); @@ -1246,7 +1246,7 @@ string parameterSetName in CodeGeneration.EscapeSingleQuotedStringContent(method.ReturnValue.Type.ETSType)); } - if (MethodParameterBindings.Out == (methodParameterBindings & MethodParameterBindings.Out)) + if ((methodParameterBindings & MethodParameterBindings.Out) == MethodParameterBindings.Out) { typesOfOutParameters.Add(dotNetTypeOfParameter); etsTypesOfOutParameters.Add(method.ReturnValue.Type.ETSType); @@ -1303,7 +1303,7 @@ private void GenerateMethodParametersProcessing( { methodParameters = new Dictionary(StringComparer.OrdinalIgnoreCase); outputTypeAttributeDeclaration = string.Empty; - StringWriter output = new StringWriter(CultureInfo.InvariantCulture); + StringWriter output = new(CultureInfo.InvariantCulture); output.WriteLine(" $__cmdletization_methodParameters = [System.Collections.Generic.List[Microsoft.PowerShell.Cmdletization.MethodParameter]]::new()"); output.WriteLine(" switch -exact ($PSCmdlet.ParameterSetName) { "); @@ -1320,8 +1320,8 @@ private void GenerateMethodParametersProcessing( output.WriteLine(") -contains $_ } {"); - List typesOfOutParameters = new List(); - List etsTypesOfOutParameters = new List(); + List typesOfOutParameters = new(); + List etsTypesOfOutParameters = new(); if (method.Parameters != null) { foreach (InstanceMethodParameterMetadata methodParameter in method.Parameters) @@ -1363,7 +1363,7 @@ private void GenerateMethodParametersProcessing( methodParameter.ParameterName, methodParameterBindings); - if (MethodParameterBindings.Out == (methodParameterBindings & MethodParameterBindings.Out)) + if ((methodParameterBindings & MethodParameterBindings.Out) == MethodParameterBindings.Out) { typesOfOutParameters.Add(dotNetTypeOfParameter); etsTypesOfOutParameters.Add(methodParameter.Type.ETSType); @@ -1387,7 +1387,7 @@ private void GenerateMethodParametersProcessing( CodeGeneration.EscapeSingleQuotedStringContent(method.ReturnValue.Type.ETSType)); } - if (MethodParameterBindings.Out == (methodParameterBindings & MethodParameterBindings.Out)) + if ((methodParameterBindings & MethodParameterBindings.Out) == MethodParameterBindings.Out) { typesOfOutParameters.Add(dotNetTypeOfParameter); etsTypesOfOutParameters.Add(method.ReturnValue.Type.ETSType); @@ -1444,7 +1444,7 @@ private void GenerateMethodParametersProcessing( } } - private void GenerateIfBoundParameter( + private static void GenerateIfBoundParameter( IEnumerable commonParameterSets, IEnumerable methodParameterSets, ParameterMetadata cmdletParameterMetadata, @@ -1615,7 +1615,7 @@ private void GenerateQueryParametersProcessing( out Dictionary queryParameters) { queryParameters = new Dictionary(StringComparer.OrdinalIgnoreCase); - StringWriter output = new StringWriter(CultureInfo.InvariantCulture); + StringWriter output = new(CultureInfo.InvariantCulture); output.WriteLine(" $__cmdletization_queryBuilder = $__cmdletization_objectModelWrapper.GetQueryBuilder()"); @@ -1725,7 +1725,7 @@ private void GenerateQueryParametersProcessing( if (instanceCmdlet != null) { - ParameterMetadata inputObjectParameter = new ParameterMetadata("InputObject", _objectInstanceType.MakeArrayType()); + ParameterMetadata inputObjectParameter = new("InputObject", _objectInstanceType.MakeArrayType()); ParameterSetMetadata.ParameterFlags inputObjectFlags = ParameterSetMetadata.ParameterFlags.ValueFromPipeline; if (queryParameters.Count > 0) @@ -1761,10 +1761,10 @@ private void GenerateQueryParametersProcessing( inputObjectParameter.Attributes.Add(new ValidateNotNullAttribute()); inputObjectParameter.ParameterSets.Clear(); - ParameterSetMetadata inputObjectPSet = new ParameterSetMetadata( + ParameterSetMetadata inputObjectPSet = new( int.MinValue, // non-positional inputObjectFlags, - null); // no help message + helpMessage: null); inputObjectParameter.ParameterSets.Add(ScriptWriter.InputObjectQueryParameterSetName, inputObjectPSet); queryParameters.Add(inputObjectParameter.Name, inputObjectParameter); } @@ -1859,9 +1859,9 @@ private void GenerateQueryParametersProcessing( private string GetHelpDirectiveForExternalHelp() { - StringBuilder output = new StringBuilder(); + StringBuilder output = new(); - if (GenerationOptions.HelpXml == (_generationOptions & GenerationOptions.HelpXml)) + if ((_generationOptions & GenerationOptions.HelpXml) == GenerationOptions.HelpXml) { output.AppendFormat( CultureInfo.InvariantCulture, @@ -1874,7 +1874,7 @@ private string GetHelpDirectiveForExternalHelp() private void WriteCmdlet(TextWriter output, StaticCmdletMetadata staticCmdlet) { - string attributeString = this.GetCmdletAttributes(staticCmdlet.CmdletMetadata); + string attributeString = GetCmdletAttributes(staticCmdlet.CmdletMetadata); Dictionary commonParameters = this.GetCommonParameters(); List commonParameterSets = GetCommonParameterSets(commonParameters); @@ -1948,9 +1948,9 @@ private static void AddPassThruParameter(IDictionary if (!outParametersArePresent) { - ParameterMetadata passThruParameter = new ParameterMetadata("PassThru", typeof(SwitchParameter)); + ParameterMetadata passThruParameter = new("PassThru", typeof(SwitchParameter)); passThruParameter.ParameterSets.Clear(); - ParameterSetMetadata passThruPSet = new ParameterSetMetadata(int.MinValue, 0, null); + ParameterSetMetadata passThruPSet = new(int.MinValue, 0, null); passThruParameter.ParameterSets.Add(ParameterAttribute.AllParameterSets, passThruPSet); commonParameters.Add(passThruParameter.Name, passThruParameter); @@ -1959,7 +1959,7 @@ private static void AddPassThruParameter(IDictionary private void WriteCmdlet(TextWriter output, InstanceCmdletMetadata instanceCmdlet) { - string attributeString = this.GetCmdletAttributes(instanceCmdlet.CmdletMetadata); + string attributeString = GetCmdletAttributes(instanceCmdlet.CmdletMetadata); Dictionary commonParameters = this.GetCommonParameters(); List commonParameterSets = GetCommonParameterSets(commonParameters); @@ -2017,7 +2017,7 @@ private void WriteCmdlet(TextWriter output, InstanceCmdletMetadata instanceCmdle private string GetOutputAttributeForGetCmdlet() { - StringBuilder result = new StringBuilder(); + StringBuilder result = new(); result.AppendFormat( CultureInfo.InvariantCulture, "[OutputType([{0}])]", @@ -2055,7 +2055,7 @@ private void WriteGetCmdlet(TextWriter output) { Dictionary commonParameters = this.GetCommonParameters(); List commonParameterSets = GetCommonParameterSets(commonParameters); - List methodParameterSets = new List(); + List methodParameterSets = new(); methodParameterSets.Add(string.Empty); List queryParameterSets = GetQueryParameterSets(null); @@ -2066,7 +2066,7 @@ private void WriteGetCmdlet(TextWriter output) CommonCmdletMetadata cmdletMetadata = this.GetGetCmdletMetadata(); Dbg.Assert(cmdletMetadata != null, "xsd should ensure that cmdlet metadata element is always present"); CommandMetadata commandMetadata = this.GetCommandMetadata(cmdletMetadata); - string attributeString = this.GetCmdletAttributes(cmdletMetadata); + string attributeString = GetCmdletAttributes(cmdletMetadata); GetCmdletParameters getCmdletParameters = this.GetGetCmdletParameters(null); if (!string.IsNullOrEmpty(getCmdletParameters.DefaultCmdletParameterSet)) @@ -2100,7 +2100,7 @@ private void WriteGetCmdlet(TextWriter output) /* 1 */ CodeGeneration.EscapeSingleQuotedStringContent(commandMetadata.Name)); } - private static object s_enumCompilationLock = new object(); + private static object s_enumCompilationLock = new(); private static void CompileEnum(EnumMetadataEnum enumMetadata) { @@ -2176,11 +2176,11 @@ internal void PopulatePSModuleInfo(PSModuleInfo moduleInfo) moduleInfo.SetModuleType(ModuleType.Cim); moduleInfo.SetVersion(new Version(_cmdletizationMetadata.Class.Version)); - Hashtable cmdletizationData = new Hashtable(StringComparer.OrdinalIgnoreCase); + Hashtable cmdletizationData = new(StringComparer.OrdinalIgnoreCase); cmdletizationData.Add(PrivateDataKey_ClassName, _cmdletizationMetadata.Class.ClassName); cmdletizationData.Add(PrivateDataKey_ObjectModelWrapper, _objectModelWrapper); - Hashtable privateData = new Hashtable(StringComparer.OrdinalIgnoreCase); + Hashtable privateData = new(StringComparer.OrdinalIgnoreCase); privateData.Add(PrivateDataKey_CmdletsOverObjects, cmdletizationData); moduleInfo.PrivateData = privateData; } diff --git a/src/System.Management.Automation/cimSupport/cmdletization/cim/WildcardPatternToCimQueryParser.cs b/src/System.Management.Automation/cimSupport/cmdletization/cim/WildcardPatternToCimQueryParser.cs index 4ce8a854487..48a47da7289 100644 --- a/src/System.Management.Automation/cimSupport/cmdletization/cim/WildcardPatternToCimQueryParser.cs +++ b/src/System.Management.Automation/cimSupport/cmdletization/cim/WildcardPatternToCimQueryParser.cs @@ -20,7 +20,7 @@ namespace Microsoft.PowerShell.Cmdletization.Cim /// internal class WildcardPatternToCimQueryParser : WildcardPatternParser { - private readonly StringBuilder _result = new StringBuilder(); + private readonly StringBuilder _result = new(); private bool _needClientSideFiltering; protected override void AppendLiteralCharacter(char c) @@ -79,13 +79,13 @@ protected override void AppendCharacterRangeToBracketExpression(char startOfChar // 93 = ] // 94 = ^ // 95 = _ - if ((91 <= startOfCharacterRange) && (startOfCharacterRange <= 94)) + if ((startOfCharacterRange >= 91) && (startOfCharacterRange <= 94)) { startOfCharacterRange = (char)90; _needClientSideFiltering = true; } - if ((91 <= endOfCharacterRange) && (endOfCharacterRange <= 94)) + if ((endOfCharacterRange >= 91) && (endOfCharacterRange <= 94)) { endOfCharacterRange = (char)95; _needClientSideFiltering = true; diff --git a/src/System.Management.Automation/cimSupport/other/ciminstancetypeadapter.cs b/src/System.Management.Automation/cimSupport/other/ciminstancetypeadapter.cs index 81ccb73133b..f9aa9f9b73c 100644 --- a/src/System.Management.Automation/cimSupport/other/ciminstancetypeadapter.cs +++ b/src/System.Management.Automation/cimSupport/other/ciminstancetypeadapter.cs @@ -28,7 +28,7 @@ public sealed class CimInstanceAdapter : PSPropertyAdapter { private static PSAdaptedProperty GetCimPropertyAdapter(CimProperty property, object baseObject, string propertyName) { - PSAdaptedProperty propertyToAdd = new PSAdaptedProperty(propertyName, property); + PSAdaptedProperty propertyToAdd = new(propertyName, property); propertyToAdd.baseObject = baseObject; // propertyToAdd.adapter = this; return propertyToAdd; @@ -50,7 +50,7 @@ private static PSAdaptedProperty GetCimPropertyAdapter(CimProperty property, obj private static PSAdaptedProperty GetPSComputerNameAdapter(CimInstance cimInstance) { - PSAdaptedProperty psComputerNameProperty = new PSAdaptedProperty(RemotingConstants.ComputerNameNoteProperty, cimInstance); + PSAdaptedProperty psComputerNameProperty = new(RemotingConstants.ComputerNameNoteProperty, cimInstance); psComputerNameProperty.baseObject = cimInstance; // psComputerNameProperty.adapter = this; return psComputerNameProperty; @@ -73,7 +73,7 @@ public override System.Collections.ObjectModel.Collection Get throw new PSInvalidOperationException(msg); } - Collection result = new Collection(); + Collection result = new(); if (cimInstance.CimInstanceProperties != null) { @@ -135,7 +135,7 @@ public override PSAdaptedProperty GetProperty(object baseObject, string property return null; } - /// + /// public override PSAdaptedProperty GetFirstPropertyOrDefault(object baseObject, MemberNamePredicate predicate) { if (predicate == null) @@ -242,7 +242,7 @@ public override object GetPropertyValue(PSAdaptedProperty adaptedProperty) throw new ArgumentNullException(nameof(adaptedProperty)); } - private void AddTypeNameHierarchy(IList typeNamesWithNamespace, IList typeNamesWithoutNamespace, string namespaceName, string className) + private static void AddTypeNameHierarchy(IList typeNamesWithNamespace, IList typeNamesWithoutNamespace, string namespaceName, string className) { if (!string.IsNullOrEmpty(namespaceName)) { @@ -258,9 +258,9 @@ private void AddTypeNameHierarchy(IList typeNamesWithNamespace, IList GetInheritanceChain(CimInstance cimInstance) + private static List GetInheritanceChain(CimInstance cimInstance) { - List inheritanceChain = new List(); + List inheritanceChain = new(); CimClass cimClass = cimInstance.CimClass; Dbg.Assert(cimClass != null, "CimInstance should always have ClassDecl"); while (cimClass != null) @@ -366,7 +366,7 @@ public override bool IsSettable(PSAdaptedProperty adaptedProperty) return false; } - bool isReadOnly = (CimFlags.ReadOnly == (cimProperty.Flags & CimFlags.ReadOnly)); + bool isReadOnly = ((cimProperty.Flags & CimFlags.ReadOnly) == CimFlags.ReadOnly); bool isSettable = !isReadOnly; return isSettable; } diff --git a/src/System.Management.Automation/engine/ArgumentTypeConverterAttribute.cs b/src/System.Management.Automation/engine/ArgumentTypeConverterAttribute.cs index e4337ab26dc..a2c2cd8321e 100644 --- a/src/System.Management.Automation/engine/ArgumentTypeConverterAttribute.cs +++ b/src/System.Management.Automation/engine/ArgumentTypeConverterAttribute.cs @@ -31,9 +31,7 @@ internal Type TargetType { get { - return _convertTypes == null - ? null - : _convertTypes.LastOrDefault(); + return _convertTypes?.LastOrDefault(); } } diff --git a/src/System.Management.Automation/engine/Attributes.cs b/src/System.Management.Automation/engine/Attributes.cs index 347eb4c7cd5..19a7aa881e7 100644 --- a/src/System.Management.Automation/engine/Attributes.cs +++ b/src/System.Management.Automation/engine/Attributes.cs @@ -507,7 +507,7 @@ public OutputTypeAttribute(params string[] type) [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] public string[] ParameterSetName { - get => _parameterSetName ?? (_parameterSetName = new[] { ParameterAttribute.AllParameterSets }); + get => _parameterSetName ??= new[] { ParameterAttribute.AllParameterSets }; set => _parameterSetName = value; } @@ -607,6 +607,7 @@ public ParameterAttribute(string experimentName, ExperimentAction experimentActi public ExperimentAction ExperimentAction { get; } internal bool ToHide => EffectiveAction == ExperimentAction.Hide; + internal bool ToShow => EffectiveAction == ExperimentAction.Show; /// @@ -1082,7 +1083,7 @@ public ValidateRangeAttribute(ValidateRangeKind kind) : base() _rangeKind = kind; } - private void ValidateRange(object element, ValidateRangeKind rangeKind) + private static void ValidateRange(object element, ValidateRangeKind rangeKind) { Type commonType = GetCommonType(typeof(int), element.GetType()); if (commonType == null) @@ -1092,7 +1093,7 @@ private void ValidateRange(object element, ValidateRangeKind rangeKind) innerException: null, Metadata.ValidateRangeElementType, element.GetType().Name, - typeof(int).Name); + nameof(Int32)); } object resultValue; @@ -1618,6 +1619,7 @@ public sealed class ValidateSetAttribute : ValidateEnumeratedArgumentsAttribute /// /// Gets the valid values in the set. /// + [SuppressMessage("Design", "CA1065:Do not raise exceptions in unexpected locations", Justification = "")] public IList ValidValues { get diff --git a/src/System.Management.Automation/engine/CmdletInfo.cs b/src/System.Management.Automation/engine/CmdletInfo.cs index 43e255b1549..05b7548f9fc 100644 --- a/src/System.Management.Automation/engine/CmdletInfo.cs +++ b/src/System.Management.Automation/engine/CmdletInfo.cs @@ -535,8 +535,7 @@ internal override CommandMetadata CommandMetadata { get { - return _cmdletMetadata ?? - (_cmdletMetadata = CommandMetadata.Get(this.Name, this.ImplementingType, Context)); + return _cmdletMetadata ??= CommandMetadata.Get(this.Name, this.ImplementingType, Context); } } @@ -548,7 +547,7 @@ internal override bool ImplementsDynamicParameters { if (ImplementingType != null) { - return (ImplementingType.GetInterface(typeof(IDynamicParameters).Name, true) != null); + return (ImplementingType.GetInterface(nameof(IDynamicParameters), true) != null); } else { diff --git a/src/System.Management.Automation/engine/CmdletParameterBinderController.cs b/src/System.Management.Automation/engine/CmdletParameterBinderController.cs index cbfa29504aa..440b9ead537 100644 --- a/src/System.Management.Automation/engine/CmdletParameterBinderController.cs +++ b/src/System.Management.Automation/engine/CmdletParameterBinderController.cs @@ -2450,7 +2450,7 @@ private void IgnoreOtherMandatoryParameterSets(uint otherMandatorySetsToBeIgnore } } - private uint NewParameterSetPromptingData( + private static uint NewParameterSetPromptingData( Dictionary promptingData, MergedCompiledCommandParameter parameter, ParameterSetSpecificMetadata parameterSetMetadata, @@ -3927,8 +3927,7 @@ private HashSet BoundObsoleteParameterNames { get { - return _boundObsoleteParameterNames ?? - (_boundObsoleteParameterNames = new HashSet(StringComparer.OrdinalIgnoreCase)); + return _boundObsoleteParameterNames ??= new HashSet(StringComparer.OrdinalIgnoreCase); } } @@ -4223,7 +4222,7 @@ private void RestoreDefaultParameterValues(IEnumerableThe invocation object for this command. internal InvocationInfo MyInvocation { - get { return _myInvocation ?? (_myInvocation = new InvocationInfo(this)); } + get { return _myInvocation ??= new InvocationInfo(this); } } /// @@ -470,7 +470,7 @@ public ProviderIntrinsics InvokeProvider { using (PSTransactionManager.GetEngineProtectionScope()) { - return _invokeProvider ?? (_invokeProvider = new ProviderIntrinsics(this)); + return _invokeProvider ??= new ProviderIntrinsics(this); } } } diff --git a/src/System.Management.Automation/engine/CommandCompletion/CommandCompletion.cs b/src/System.Management.Automation/engine/CommandCompletion/CommandCompletion.cs index 8b124194881..4d89d87e51c 100644 --- a/src/System.Management.Automation/engine/CommandCompletion/CommandCompletion.cs +++ b/src/System.Management.Automation/engine/CommandCompletion/CommandCompletion.cs @@ -157,7 +157,7 @@ public static CommandCompletion CompleteInput(string input, int cursorIndex, Has } // If we are in a debugger stop, let the debugger do the command completion. - var debugger = (powershell.Runspace != null) ? powershell.Runspace.Debugger : null; + var debugger = powershell.Runspace?.Debugger; if ((debugger != null) && debugger.InBreakpoint) { return CompleteInputInDebugger(input, cursorIndex, options, debugger); @@ -236,7 +236,7 @@ public static CommandCompletion CompleteInput(Ast ast, Token[] tokens, IScriptPo } // If we are in a debugger stop, let the debugger do the command completion. - var debugger = (powershell.Runspace != null) ? powershell.Runspace.Debugger : null; + var debugger = powershell.Runspace?.Debugger; if ((debugger != null) && debugger.InBreakpoint) { return CompleteInputInDebugger(ast, tokens, cursorPosition, options, debugger); @@ -740,7 +740,7 @@ private static bool PSv2IsCommandLikeCmdlet(string lastWord, out bool isSnapinSp return false; } - private struct CommandAndName + private readonly struct CommandAndName { internal readonly PSObject Command; internal readonly PSSnapinQualifiedName CommandName; @@ -1067,7 +1067,7 @@ private static bool PSv2ShouldFullyQualifyPathsPath(PowerShellExecutionHelper he return isAbsolute; } - private struct PathItemAndConvertedPath + private readonly struct PathItemAndConvertedPath { internal readonly string Path; internal readonly PSObject Item; diff --git a/src/System.Management.Automation/engine/CommandCompletion/CompletionAnalysis.cs b/src/System.Management.Automation/engine/CommandCompletion/CompletionAnalysis.cs index 9f4b3565115..95b26ff6907 100644 --- a/src/System.Management.Automation/engine/CommandCompletion/CompletionAnalysis.cs +++ b/src/System.Management.Automation/engine/CommandCompletion/CompletionAnalysis.cs @@ -20,18 +20,29 @@ internal class CompletionContext // This is how we can tell if we're trying to complete part of something (like a member) // or complete an argument, where TokenBeforeCursor could be a parameter name. internal Token TokenAtCursor { get; set; } + internal Token TokenBeforeCursor { get; set; } + internal IScriptPosition CursorPosition { get; set; } internal PowerShellExecutionHelper Helper { get; set; } + internal Hashtable Options { get; set; } + internal Dictionary CustomArgumentCompleters { get; set; } + internal Dictionary NativeArgumentCompleters { get; set; } + internal string WordToComplete { get; set; } + internal int ReplacementIndex { get; set; } + internal int ReplacementLength { get; set; } + internal ExecutionContext ExecutionContext { get; set; } + internal PseudoBindingInfo PseudoBindingInfo { get; set; } + internal TypeInferenceContext TypeInferenceContext { get; set; } internal bool GetOption(string option, bool @default) @@ -925,7 +936,7 @@ internal List GetResultHelper(CompletionContext completionCont } // Helper method to auto complete hashtable key - private List GetResultForHashtable(CompletionContext completionContext) + private static List GetResultForHashtable(CompletionContext completionContext) { var lastAst = completionContext.RelatedAsts.Last(); HashtableAst tempHashtableAst = null; @@ -986,7 +997,7 @@ private List GetResultForHashtable(CompletionContext completio } // Helper method to look for an incomplete assignment pair in hash table. - private bool CheckForPendingAssignment(HashtableAst hashTableAst) + private static bool CheckForPendingAssignment(HashtableAst hashTableAst) { foreach (var keyValue in hashTableAst.KeyValuePairs) { @@ -1054,7 +1065,7 @@ private static string GetFirstLineSubString(string stringToComplete, out bool ha return stringToComplete; } - private Tuple GetHashEntryContainsCursor( + private static Tuple GetHashEntryContainsCursor( IScriptPosition cursor, HashtableAst hashTableAst, bool isCursorInString) @@ -1345,7 +1356,7 @@ private static List GetResultForEnum( return GetMatchedResults(allNames, completionContext); } - private List GetResultForEnumPropertyValueOfDSCResource( + private static List GetResultForEnumPropertyValueOfDSCResource( CompletionContext completionContext, string stringToComplete, ref int replacementIndex, @@ -1632,7 +1643,7 @@ private List GetResultForString(CompletionContext completionCo /// /// /// - private ConfigurationDefinitionAst GetAncestorConfigurationAstAndKeywordAst( + private static ConfigurationDefinitionAst GetAncestorConfigurationAstAndKeywordAst( IScriptPosition cursorPosition, Ast ast, out DynamicKeywordStatementAst keywordAst) @@ -1668,7 +1679,7 @@ private ConfigurationDefinitionAst GetAncestorConfigurationAstAndKeywordAst( /// /// /// - private List GetResultForIdentifierInConfiguration( + private static List GetResultForIdentifierInConfiguration( CompletionContext completionContext, ConfigurationDefinitionAst configureAst, DynamicKeywordStatementAst keywordAst, @@ -2082,7 +2093,7 @@ private List GetResultForIdentifier(CompletionContext completi return result; } - private List GetResultForAttributeArgument(CompletionContext completionContext, ref int replacementIndex, ref int replacementLength) + private static List GetResultForAttributeArgument(CompletionContext completionContext, ref int replacementIndex, ref int replacementLength) { // Attribute member arguments Type attributeType = null; diff --git a/src/System.Management.Automation/engine/CommandCompletion/CompletionCompleters.cs b/src/System.Management.Automation/engine/CommandCompletion/CompletionCompleters.cs index e7c8ea0be9a..853b79e7843 100644 --- a/src/System.Management.Automation/engine/CommandCompletion/CompletionCompleters.cs +++ b/src/System.Management.Automation/engine/CommandCompletion/CompletionCompleters.cs @@ -511,7 +511,7 @@ internal static List CompleteCommandParameter(CompletionContex && !string.IsNullOrWhiteSpace(context.WordToComplete) && context.WordToComplete.StartsWith('-')) { var lastAst = context.RelatedAsts.Last(); - var wordToMatch = string.Concat(context.WordToComplete.AsSpan().Slice(1), "*"); + var wordToMatch = string.Concat(context.WordToComplete.AsSpan(1), "*"); var pattern = WildcardPattern.Get(wordToMatch, WildcardOptions.IgnoreCase); var parameterNames = keywordAst.CommandElements.Where(ast => ast is CommandParameterAst).Select(ast => (ast as CommandParameterAst).ParameterName); foreach (var parameterName in s_parameterNamesOfImportDSCResource) @@ -4086,7 +4086,9 @@ private static ArgumentLocation FindTargetArgumentLocation(Collection CompleteVariable(CompletionContext contex provider = wordToComplete.Substring(0, colon + 1); if (s_variableScopes.Contains(provider, StringComparer.OrdinalIgnoreCase)) { - pattern = string.Concat("variable:", wordToComplete.AsSpan().Slice(colon + 1), "*"); + pattern = string.Concat("variable:", wordToComplete.AsSpan(colon + 1), "*"); } else { @@ -4999,6 +5001,7 @@ internal static List CompleteComment(CompletionContext context new Tuple("Where", "Where({ expression } [, mode [, numberToReturn]])"), new Tuple("ForEach", "ForEach(expression [, arguments...])") }; + // List of DSC collection-value variables private static readonly HashSet s_dscCollectionVariables = new HashSet(StringComparer.OrdinalIgnoreCase) { "SelectedNodes", "AllNodes" }; @@ -5367,7 +5370,7 @@ private static string GetCimPropertyToString(CimPropertyDeclaration cimProperty) break; } - bool isReadOnly = (CimFlags.ReadOnly == (cimProperty.Flags & CimFlags.ReadOnly)); + bool isReadOnly = ((cimProperty.Flags & CimFlags.ReadOnly) == CimFlags.ReadOnly); return type + " " + cimProperty.Name + " { get; " + (isReadOnly ? "}" : "set; }"); } @@ -5440,6 +5443,7 @@ private static bool IsConstructor(object member) private abstract class TypeCompletionBase { internal abstract CompletionResult GetCompletionResult(string keyMatched, string prefix, string suffix); + internal abstract CompletionResult GetCompletionResult(string keyMatched, string prefix, string suffix, string namespaceToRemove); internal static string RemoveBackTick(string typeName) @@ -6092,7 +6096,7 @@ internal static List CompleteHelpTopics(CompletionContext cont foreach (var dir in searchPaths) { - foreach (var file in Directory.GetFiles(dir)) + foreach (var file in Directory.EnumerateFiles(dir)) { if (wildcardPattern.IsMatch(Path.GetFileName(file))) { @@ -6956,6 +6960,7 @@ internal static bool TrySafeEval(ExpressionAst ast, ExecutionContext executionCo public object VisitDoUntilStatement(DoUntilStatementAst doUntilStatementAst) { return false; } public object VisitAssignmentStatement(AssignmentStatementAst assignmentStatementAst) { return false; } + // REVIEW: we could relax this to allow specific commands public object VisitCommand(CommandAst commandAst) { return false; } diff --git a/src/System.Management.Automation/engine/CommandCompletion/ExtensibleCompletion.cs b/src/System.Management.Automation/engine/CommandCompletion/ExtensibleCompletion.cs index 6905e39b165..777fc6c16f4 100644 --- a/src/System.Management.Automation/engine/CommandCompletion/ExtensibleCompletion.cs +++ b/src/System.Management.Automation/engine/CommandCompletion/ExtensibleCompletion.cs @@ -58,6 +58,7 @@ public ArgumentCompleterAttribute(ScriptBlock scriptBlock) /// /// A type specified by the must implement this interface. /// +#nullable enable public interface IArgumentCompleter { /// @@ -82,6 +83,7 @@ IEnumerable CompleteArgument( CommandAst commandAst, IDictionary fakeBoundParameters); } +#nullable restore /// /// @@ -129,7 +131,7 @@ protected override void EndProcessing() if (CommandName == null || CommandName.Length == 0) { - CommandName = new[] { "" }; + CommandName = new[] { string.Empty }; } for (int i = 0; i < CommandName.Length; i++) diff --git a/src/System.Management.Automation/engine/CommandCompletion/PseudoParameterBinder.cs b/src/System.Management.Automation/engine/CommandCompletion/PseudoParameterBinder.cs index 2872066e74d..c86fc34cfaf 100644 --- a/src/System.Management.Automation/engine/CommandCompletion/PseudoParameterBinder.cs +++ b/src/System.Management.Automation/engine/CommandCompletion/PseudoParameterBinder.cs @@ -201,9 +201,9 @@ internal AstPair(CommandParameterAst parameterAst, ExpressionAst argumentAst) ParameterArgumentType = AstParameterArgumentType.AstPair; ParameterSpecified = parameterAst != null; ArgumentSpecified = argumentAst != null; - ParameterName = parameterAst != null ? parameterAst.ParameterName : null; - ParameterText = parameterAst != null ? parameterAst.ParameterName : null; - ArgumentType = argumentAst != null ? argumentAst.StaticType : null; + ParameterName = parameterAst?.ParameterName; + ParameterText = parameterAst?.ParameterName; + ArgumentType = argumentAst?.StaticType; ParameterContainsArgument = false; Argument = argumentAst; @@ -261,8 +261,7 @@ public static class StaticParameterBinder /// The StaticBindingResult that represents the binding. public static StaticBindingResult BindCommand(CommandAst commandAst) { - bool resolve = true; - return BindCommand(commandAst, resolve); + return BindCommand(commandAst, resolve: true); } /// diff --git a/src/System.Management.Automation/engine/CommandDiscovery.cs b/src/System.Management.Automation/engine/CommandDiscovery.cs index 8749d5468ce..2b328767f4c 100644 --- a/src/System.Management.Automation/engine/CommandDiscovery.cs +++ b/src/System.Management.Automation/engine/CommandDiscovery.cs @@ -149,7 +149,7 @@ internal CommandDiscovery(ExecutionContext context) /// /// True if the cmdlet is a special cmdlet that shouldn't be part of the discovery list. Or false otherwise. /// - private bool IsSpecialCmdlet(Type implementingType) + private static bool IsSpecialCmdlet(Type implementingType) { // These commands should never be put in the discovery list. They are an internal implementation // detail of the formatting and output component. That component uses these cmdlets by creating @@ -1348,7 +1348,7 @@ internal LookupPathCollection GetLookupDirectoryPaths() } // Cache the new lookup paths - return _cachedLookupPaths ?? (_cachedLookupPaths = result); + return _cachedLookupPaths ??= result; } /// diff --git a/src/System.Management.Automation/engine/CommandInfo.cs b/src/System.Management.Automation/engine/CommandInfo.cs index d1afb8b3b12..56e17ef0f5f 100644 --- a/src/System.Management.Automation/engine/CommandInfo.cs +++ b/src/System.Management.Automation/engine/CommandInfo.cs @@ -583,7 +583,7 @@ public virtual Dictionary Parameters internal CommandMetadata ExternalCommandMetadata { - get { return _externalCommandMetadata ?? (_externalCommandMetadata = new CommandMetadata(this, true)); } + get { return _externalCommandMetadata ??= new CommandMetadata(this, true); } set { _externalCommandMetadata = value; } } @@ -904,7 +904,7 @@ public override string ToString() } [DebuggerDisplay("{PSTypeName} {Name}")] - internal struct PSMemberNameAndType + internal readonly struct PSMemberNameAndType { public readonly string Name; @@ -960,7 +960,7 @@ private PSSyntheticTypeName(string typeName, Type type, IList member.Name.Equals(nameof(PSTypeName), StringComparison.OrdinalIgnoreCase); + private static bool IsPSTypeName(in PSMemberNameAndType member) => member.Name.Equals(nameof(PSTypeName), StringComparison.OrdinalIgnoreCase); private static string GetMemberTypeProjection(string typename, IList members) { diff --git a/src/System.Management.Automation/engine/CommandMetadata.cs b/src/System.Management.Automation/engine/CommandMetadata.cs index 5056f2afbb0..027373ec676 100644 --- a/src/System.Management.Automation/engine/CommandMetadata.cs +++ b/src/System.Management.Automation/engine/CommandMetadata.cs @@ -680,7 +680,7 @@ private void ConstructCmdletMetadataUsingReflection() // Determine if the cmdlet implements dynamic parameters by looking for the interface - Type dynamicParametersType = CommandType.GetInterface(typeof(IDynamicParameters).Name, true); + Type dynamicParametersType = CommandType.GetInterface(nameof(IDynamicParameters), true); if (dynamicParametersType != null) { @@ -1316,7 +1316,7 @@ public static Dictionary GetRestrictedCommands(SessionC List restrictedCommands = new List(); // all remoting cmdlets need to be included for workflow scenarios as wel - if (SessionCapabilities.RemoteServer == (sessionCapabilities & SessionCapabilities.RemoteServer)) + if ((sessionCapabilities & SessionCapabilities.RemoteServer) == SessionCapabilities.RemoteServer) { restrictedCommands.AddRange(GetRestrictedRemotingCommands()); } diff --git a/src/System.Management.Automation/engine/CommandParameter.cs b/src/System.Management.Automation/engine/CommandParameter.cs index b13cc94ad40..e6752ff023b 100644 --- a/src/System.Management.Automation/engine/CommandParameter.cs +++ b/src/System.Management.Automation/engine/CommandParameter.cs @@ -116,7 +116,7 @@ internal object ArgumentValue /// internal bool ArgumentToBeSplatted { - get { return _argument != null ? _argument.splatted : false; } + get { return _argument != null && _argument.splatted; } } /// diff --git a/src/System.Management.Automation/engine/CommandProcessor.cs b/src/System.Management.Automation/engine/CommandProcessor.cs index 4a1414362a5..fb1fe81fc54 100644 --- a/src/System.Management.Automation/engine/CommandProcessor.cs +++ b/src/System.Management.Automation/engine/CommandProcessor.cs @@ -607,7 +607,7 @@ private void WriteInputObjectError( string errorId, params object[] args) { - Type inputObjectType = (inputObject == null) ? null : inputObject.GetType(); + Type inputObjectType = inputObject?.GetType(); ParameterBindingException bindingException = new ParameterBindingException( ErrorCategory.InvalidArgument, @@ -824,7 +824,7 @@ private void InitCommon() /// /// Help target to request. /// Help category to request. - /// true if user requested help; false otherwise. + /// if user requested help; otherwise. internal override bool IsHelpRequested(out string helpTarget, out HelpCategory helpCategory) { if (this.arguments != null) diff --git a/src/System.Management.Automation/engine/CommandProcessorBase.cs b/src/System.Management.Automation/engine/CommandProcessorBase.cs index 33804b69ae3..6ab07114652 100644 --- a/src/System.Management.Automation/engine/CommandProcessorBase.cs +++ b/src/System.Management.Automation/engine/CommandProcessorBase.cs @@ -149,6 +149,7 @@ internal virtual ObsoleteAttribute ObsoleteAttribute { get { return null; } } + // Full Qualified ID for the obsolete command warning private const string FQIDCommandObsolete = "CommandObsolete"; @@ -256,7 +257,7 @@ internal ExecutionContext Context /// /// Help target to request. /// Help category to request. - /// true if user requested help; false otherwise. + /// if user requested help; otherwise. internal virtual bool IsHelpRequested(out string helpTarget, out HelpCategory helpCategory) { // by default we don't handle "-?" parameter at all @@ -956,14 +957,6 @@ private void Dispose(bool disposing) _disposed = true; } - /// - /// Finalizer for class CommandProcessorBase. - /// - ~CommandProcessorBase() - { - Dispose(false); - } - #endregion IDispose } } diff --git a/src/System.Management.Automation/engine/CommandSearcher.cs b/src/System.Management.Automation/engine/CommandSearcher.cs index d3a1033c932..b349255bab8 100644 --- a/src/System.Management.Automation/engine/CommandSearcher.cs +++ b/src/System.Management.Automation/engine/CommandSearcher.cs @@ -842,7 +842,7 @@ private static bool checkPath(string path, string commandName) // Don't return commands to the user if that might result in: // - Trusted commands calling untrusted functions that the user has overridden // - Debug prompts calling internal functions that are likely to have code injection - private bool ShouldSkipCommandResolutionForConstrainedLanguage(CommandInfo? result, ExecutionContext executionContext) + private static bool ShouldSkipCommandResolutionForConstrainedLanguage(CommandInfo? result, ExecutionContext executionContext) { if (result == null) { diff --git a/src/System.Management.Automation/engine/CompiledCommandParameter.cs b/src/System.Management.Automation/engine/CompiledCommandParameter.cs index 90011fbde74..dc74210bda5 100644 --- a/src/System.Management.Automation/engine/CompiledCommandParameter.cs +++ b/src/System.Management.Automation/engine/CompiledCommandParameter.cs @@ -625,7 +625,7 @@ internal ParameterCollectionTypeInformation(Type type) return; } - bool implementsIList = (type.GetInterface(typeof(IList).Name) != null); + bool implementsIList = (type.GetInterface(nameof(IList)) != null); // Look for class Collection. Collection implements IList, and also IList // is more efficient to bind than ICollection. This optimization diff --git a/src/System.Management.Automation/engine/CoreAdapter.cs b/src/System.Management.Automation/engine/CoreAdapter.cs index 673225b996b..48077bbafd4 100644 --- a/src/System.Management.Automation/engine/CoreAdapter.cs +++ b/src/System.Management.Automation/engine/CoreAdapter.cs @@ -2747,6 +2747,7 @@ internal ParameterizedPropertyCacheEntry(List properties) internal class PropertyCacheEntry : CacheEntry { internal delegate object GetterDelegate(object instance); + internal delegate void SetterDelegate(object instance, object setValue); internal PropertyCacheEntry(PropertyInfo property) @@ -5939,7 +5940,7 @@ private static MethodInfo Infer(MethodInfo genericMethod, ICollection type using (s_tracer.TraceScope("Inferring type parameters for the following method: {0}", genericMethod)) { - if (PSTraceSourceOptions.WriteLine == (s_tracer.Options & PSTraceSourceOptions.WriteLine)) + if ((s_tracer.Options & PSTraceSourceOptions.WriteLine) == PSTraceSourceOptions.WriteLine) { s_tracer.WriteLine( "Types of method arguments: {0}", diff --git a/src/System.Management.Automation/engine/EngineIntrinsics.cs b/src/System.Management.Automation/engine/EngineIntrinsics.cs index 9700a13f905..a492a5215fc 100644 --- a/src/System.Management.Automation/engine/EngineIntrinsics.cs +++ b/src/System.Management.Automation/engine/EngineIntrinsics.cs @@ -101,7 +101,7 @@ public SessionState SessionState /// public CommandInvocationIntrinsics InvokeCommand { - get { return _invokeCommand ?? (_invokeCommand = new CommandInvocationIntrinsics(_context)); } + get { return _invokeCommand ??= new CommandInvocationIntrinsics(_context); } } #endregion Public methods diff --git a/src/System.Management.Automation/engine/EnumExpressionEvaluator.cs b/src/System.Management.Automation/engine/EnumExpressionEvaluator.cs index 742a4a52fae..056372ac63e 100644 --- a/src/System.Management.Automation/engine/EnumExpressionEvaluator.cs +++ b/src/System.Management.Automation/engine/EnumExpressionEvaluator.cs @@ -157,6 +157,7 @@ internal abstract class Node public Node Operand1 { get; set; } internal abstract bool Eval(object val); + internal abstract bool ExistEnum(object enumVal); } @@ -308,7 +309,7 @@ internal override bool ExistEnum(object enumVal) return exist; } - private bool isUnsigned(Type type) + private static bool isUnsigned(Type type) { return (type == typeof(ulong) || type == typeof(uint) || type == typeof(ushort) || type == typeof(byte)); } @@ -385,7 +386,7 @@ internal bool ExistsInExpression(T flagName) /// /// A generic list of tokenized input. /// - private List TokenizeInput(string input) + private static List TokenizeInput(string input) { List tokenList = new List(); int _offset = 0; @@ -411,7 +412,7 @@ private List TokenizeInput(string input) /// /// Current offset position for the string parser. /// - private void FindNextToken(string input, ref int _offset) + private static void FindNextToken(string input, ref int _offset) { while (_offset < input.Length) { @@ -438,7 +439,7 @@ private void FindNextToken(string input, ref int _offset) /// /// The next token on the input string /// - private Token GetNextToken(string input, ref int _offset) + private static Token GetNextToken(string input, ref int _offset) { StringBuilder sb = new StringBuilder(); // bool singleQuoted = false; @@ -521,7 +522,7 @@ private Token GetNextToken(string input, ref int _offset) /// /// A list of tokenized input. /// - private void CheckSyntaxError(List tokenList) + private static void CheckSyntaxError(List tokenList) { // Initialize, assuming preceded by OR TokenKind previous = TokenKind.Or; @@ -576,7 +577,7 @@ private void CheckSyntaxError(List tokenList) /// /// Tokenized list of the input string. /// - private Node ConstructExpressionTree(List tokenList) + private static Node ConstructExpressionTree(List tokenList) { bool notFlag = false; Queue andQueue = new Queue(); diff --git a/src/System.Management.Automation/engine/EnumMinimumDisambiguation.cs b/src/System.Management.Automation/engine/EnumMinimumDisambiguation.cs index 18332cc37c6..5c166c69a63 100644 --- a/src/System.Management.Automation/engine/EnumMinimumDisambiguation.cs +++ b/src/System.Management.Automation/engine/EnumMinimumDisambiguation.cs @@ -85,7 +85,7 @@ internal static string EnumDisambiguate(string text, Type enumType) } // No special cases match, throw error for multiple matches. StringBuilder matchListSB = new StringBuilder(namesWithMatchingPrefix[0]); - string separator = ", "; + const string separator = ", "; for (int i = 1; i < namesWithMatchingPrefix.Count; i++) { matchListSB.Append(separator); @@ -106,7 +106,7 @@ internal static string EnumDisambiguate(string text, Type enumType) internal static string EnumAllValues(Type enumType) { string[] names = Enum.GetNames(enumType); - string separator = ", "; + const string separator = ", "; StringBuilder returnValue = new StringBuilder(); if (names.Length != 0) { diff --git a/src/System.Management.Automation/engine/ErrorPackage.cs b/src/System.Management.Automation/engine/ErrorPackage.cs index 4d1627dff93..6d7a6c8326a 100644 --- a/src/System.Management.Automation/engine/ErrorPackage.cs +++ b/src/System.Management.Automation/engine/ErrorPackage.cs @@ -495,7 +495,7 @@ public override string ToString() /// internal static string Ellipsize(CultureInfo uiCultureInfo, string original) { - if (40 >= original.Length) + if (original.Length <= 40) { return original; } @@ -1480,7 +1480,7 @@ internal void SetTargetObject(object target) /// for that ErrorCategory. /// /// never null - public ErrorCategoryInfo CategoryInfo { get => _categoryInfo ?? (_categoryInfo = new ErrorCategoryInfo(this)); } + public ErrorCategoryInfo CategoryInfo { get => _categoryInfo ??= new ErrorCategoryInfo(this); } private ErrorCategoryInfo _categoryInfo; diff --git a/src/System.Management.Automation/engine/EventManager.cs b/src/System.Management.Automation/engine/EventManager.cs index f820aec608b..4afde8a9913 100644 --- a/src/System.Management.Automation/engine/EventManager.cs +++ b/src/System.Management.Automation/engine/EventManager.cs @@ -680,7 +680,7 @@ private void ProcessNewSubscriber(PSEventSubscriber subscriber, object source, s } // Retrieve the event from the object - BindingFlags bindingFlags = BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.IgnoreCase; + const BindingFlags bindingFlags = BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.IgnoreCase; eventInfo = sourceType.GetEvent(eventName, bindingFlags); // If we can't find the event, throw an exception @@ -844,7 +844,7 @@ private void UnsubscribeEvent(PSEventSubscriber subscriber, bool skipDraining) Type sourceType = subscriber.SourceObject as Type ?? subscriber.SourceObject.GetType(); - BindingFlags bindingFlags = BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.IgnoreCase; + const BindingFlags bindingFlags = BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.IgnoreCase; eventInfo = sourceType.GetEvent(subscriber.EventName, bindingFlags); if ((eventInfo != null) && (existingSubscriber != null)) @@ -1510,14 +1510,6 @@ protected virtual void OnForwardEvent(PSEventArgs e) ForwardEvent?.Invoke(this, e); } - /// - /// Destructor for the EventManager class. - /// - ~PSLocalEventManager() - { - Dispose(false); - } - /// /// Disposes the EventManager class. /// @@ -1552,6 +1544,14 @@ public void Dispose(bool disposing) } } } + + /// + /// Finalizes an instance of the class. + /// + ~PSLocalEventManager() + { + Dispose(false); + } } /// @@ -2457,7 +2457,7 @@ public class PSEventJob : Job /// /// public PSEventJob(PSEventManager eventManager, PSEventSubscriber subscriber, ScriptBlock action, string name) : - base(action == null ? null : action.ToString(), name) + base(action?.ToString(), name) { if (eventManager == null) throw new ArgumentNullException(nameof(eventManager)); diff --git a/src/System.Management.Automation/engine/ExecutionContext.cs b/src/System.Management.Automation/engine/ExecutionContext.cs index 3a726be8f73..9c484a7c56f 100644 --- a/src/System.Management.Automation/engine/ExecutionContext.cs +++ b/src/System.Management.Automation/engine/ExecutionContext.cs @@ -113,9 +113,7 @@ internal static bool IsStrictVersion(ExecutionContext context, int majorVersion) context = LocalPipeline.GetExecutionContextFromTLS(); } - return (context != null) - ? context.IsStrictVersion(majorVersion) - : false; + return (context != null) && context.IsStrictVersion(majorVersion); } /// /// Check to see a specific version of strict mode is enabled. The check is always scoped, @@ -488,7 +486,7 @@ internal bool UseFullLanguageModeInDebugger { get { - return InitialSessionState != null ? InitialSessionState.UseFullLanguageModeInDebugger : false; + return InitialSessionState != null && InitialSessionState.UseFullLanguageModeInDebugger; } } @@ -666,7 +664,7 @@ internal bool GetBooleanPreference(VariablePath preferenceVariablePath, bool def /// internal HelpSystem HelpSystem { - get { return _helpSystem ?? (_helpSystem = new HelpSystem(this)); } + get { return _helpSystem ??= new HelpSystem(this); } } private HelpSystem _helpSystem; @@ -679,6 +677,7 @@ internal HelpSystem HelpSystem #endregion internal Dictionary CustomArgumentCompleters { get; set; } + internal Dictionary NativeArgumentCompleters { get; set; } /// @@ -744,7 +743,7 @@ internal InternalHost InternalHost /// internal EngineIntrinsics EngineIntrinsics { - get { return _engineIntrinsics ?? (_engineIntrinsics = new EngineIntrinsics(this)); } + get { return _engineIntrinsics ??= new EngineIntrinsics(this); } } private EngineIntrinsics _engineIntrinsics; @@ -906,7 +905,7 @@ internal void AppendDollarError(object obj) const int maxErrorCount = 256; int numToErase = arraylist.Count - (maxErrorCount - 1); - if (0 < numToErase) + if (numToErase > 0) { arraylist.RemoveRange( maxErrorCount - 1, @@ -1698,5 +1697,5 @@ internal enum EngineState /// Engine is stopped. /// Stopped = 4 - }; + } } diff --git a/src/System.Management.Automation/engine/ExperimentalFeature/ExperimentalFeature.cs b/src/System.Management.Automation/engine/ExperimentalFeature/ExperimentalFeature.cs index 4fd79fe7d7d..f1be0c5acc8 100644 --- a/src/System.Management.Automation/engine/ExperimentalFeature/ExperimentalFeature.cs +++ b/src/System.Management.Automation/engine/ExperimentalFeature/ExperimentalFeature.cs @@ -126,6 +126,9 @@ static ExperimentalFeature() new ExperimentalFeature( name: "PSSubsystemPluginModel", description: "A plugin model for registering and un-registering PowerShell subsystems"), + new ExperimentalFeature( + name: "PSAnsiRendering", + description: "Enable $PSStyle variable to control ANSI rendering of strings"), }; EngineExperimentalFeatures = new ReadOnlyCollection(engineFeatures); @@ -345,20 +348,21 @@ internal static void ValidateArguments(string experimentName, ExperimentAction e { if (string.IsNullOrEmpty(experimentName)) { - string paramName = nameof(experimentName); + const string paramName = nameof(experimentName); throw PSTraceSource.NewArgumentNullException(paramName, Metadata.ArgumentNullOrEmpty, paramName); } if (experimentAction == ExperimentAction.None) { - string paramName = nameof(experimentAction); - string invalidMember = nameof(ExperimentAction.None); + const string paramName = nameof(experimentAction); + const string invalidMember = nameof(ExperimentAction.None); string validMembers = StringUtil.Format("{0}, {1}", ExperimentAction.Hide, ExperimentAction.Show); throw PSTraceSource.NewArgumentException(paramName, Metadata.InvalidEnumArgument, invalidMember, paramName, validMembers); } } internal bool ToHide => EffectiveAction == ExperimentAction.Hide; + internal bool ToShow => EffectiveAction == ExperimentAction.Show; /// diff --git a/src/System.Management.Automation/engine/ExternalScriptInfo.cs b/src/System.Management.Automation/engine/ExternalScriptInfo.cs index c43177214ff..b97da3b9970 100644 --- a/src/System.Management.Automation/engine/ExternalScriptInfo.cs +++ b/src/System.Management.Automation/engine/ExternalScriptInfo.cs @@ -358,9 +358,8 @@ internal override CommandMetadata CommandMetadata { get { - return _commandMetadata ?? - (_commandMetadata = - new CommandMetadata(this.ScriptBlock, this.Name, LocalPipeline.GetExecutionContextFromTLS())); + return _commandMetadata ??= + new CommandMetadata(this.ScriptBlock, this.Name, LocalPipeline.GetExecutionContextFromTLS()); } } @@ -403,7 +402,7 @@ internal string RequiresApplicationID get { var data = GetRequiresData(); - return data == null ? null : data.RequiredApplicationId; + return data?.RequiredApplicationId; } } @@ -417,7 +416,7 @@ internal Version RequiresPSVersion get { var data = GetRequiresData(); - return data == null ? null : data.RequiredPSVersion; + return data?.RequiredPSVersion; } } @@ -426,7 +425,7 @@ internal IEnumerable RequiresPSEditions get { var data = GetRequiresData(); - return data == null ? null : data.RequiredPSEditions; + return data?.RequiredPSEditions; } } @@ -435,7 +434,7 @@ internal IEnumerable RequiresModules get { var data = GetRequiresData(); - return data == null ? null : data.RequiredModules; + return data?.RequiredModules; } } @@ -444,7 +443,7 @@ internal bool RequiresElevation get { var data = GetRequiresData(); - return data == null ? false : data.IsElevationRequired; + return data != null && data.IsElevationRequired; } } @@ -458,7 +457,7 @@ internal IEnumerable RequiresPSSnapIns get { var data = GetRequiresData(); - return data == null ? null : data.RequiresPSSnapIns; + return data?.RequiresPSSnapIns; } } diff --git a/src/System.Management.Automation/engine/FunctionInfo.cs b/src/System.Management.Automation/engine/FunctionInfo.cs index 8afe41ece15..70ab80e8ca4 100644 --- a/src/System.Management.Automation/engine/FunctionInfo.cs +++ b/src/System.Management.Automation/engine/FunctionInfo.cs @@ -265,7 +265,7 @@ internal void Update(ScriptBlock newFunction, bool force, ScopedItemOptions opti } /// - /// Returns true if this function uses cmdlet binding mode for its parameters; otherwise returns false. + /// Returns if this function uses cmdlet binding mode for its parameters; otherwise returns . /// public bool CmdletBinding { @@ -277,7 +277,7 @@ public bool CmdletBinding /// /// Gets the name of the default parameter set. - /// Returns null if this function doesn't use cmdlet parameter binding or if the default parameter set wasn't specified. + /// Returns if this function doesn't use cmdlet parameter binding or if the default parameter set wasn't specified. /// public string DefaultParameterSet { @@ -479,9 +479,8 @@ internal override CommandMetadata CommandMetadata { get { - return _commandMetadata ?? - (_commandMetadata = - new CommandMetadata(this.ScriptBlock, this.Name, LocalPipeline.GetExecutionContextFromTLS())); + return _commandMetadata ??= + new CommandMetadata(this.ScriptBlock, this.Name, LocalPipeline.GetExecutionContextFromTLS()); } } diff --git a/src/System.Management.Automation/engine/GetCommandCommand.cs b/src/System.Management.Automation/engine/GetCommandCommand.cs index 96be302f5e8..17efeb4ac73 100644 --- a/src/System.Management.Automation/engine/GetCommandCommand.cs +++ b/src/System.Management.Automation/engine/GetCommandCommand.cs @@ -1632,8 +1632,7 @@ private static PSObject GetParameterType(Type parameterType) new ArrayList(Enum.GetValues(parameterType)) : new ArrayList(); returnParameterType.Properties.Add(new PSNoteProperty("EnumValues", enumValues)); - bool hasFlagAttribute = (isArray) ? - ((parameterType.GetCustomAttributes(typeof(FlagsAttribute), true)).Length > 0) : false; + bool hasFlagAttribute = (isArray) && ((parameterType.GetCustomAttributes(typeof(FlagsAttribute), true)).Length > 0); returnParameterType.Properties.Add(new PSNoteProperty("HasFlagAttribute", hasFlagAttribute)); // Recurse into array elements. diff --git a/src/System.Management.Automation/engine/ICommandRuntime.cs b/src/System.Management.Automation/engine/ICommandRuntime.cs index cf5de2b20ab..6f0b3ce9d57 100644 --- a/src/System.Management.Automation/engine/ICommandRuntime.cs +++ b/src/System.Management.Automation/engine/ICommandRuntime.cs @@ -560,6 +560,7 @@ public interface ICommandRuntime /// execute an instance of a Cmdlet. ICommandRuntime2 extends the ICommandRuntime interface /// by adding support for the informational data stream. /// +#nullable enable public interface ICommandRuntime2 : ICommandRuntime { /// @@ -614,6 +615,6 @@ public interface ICommandRuntime2 : ICommandRuntime /// performed, and the Cmdlet should move on to the next target resource. /// [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1045:DoNotPassTypesByReference")] - bool ShouldContinue(string query, string caption, bool hasSecurityImpact, ref bool yesToAll, ref bool noToAll); + bool ShouldContinue(string? query, string? caption, bool hasSecurityImpact, ref bool yesToAll, ref bool noToAll); } } diff --git a/src/System.Management.Automation/engine/InformationRecord.cs b/src/System.Management.Automation/engine/InformationRecord.cs index 29d317e2c02..ad4aeeff5a9 100644 --- a/src/System.Management.Automation/engine/InformationRecord.cs +++ b/src/System.Management.Automation/engine/InformationRecord.cs @@ -81,7 +81,7 @@ internal InformationRecord(InformationRecord baseRecord) [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public List Tags { - get { return _tags ?? (_tags = new List()); } + get { return _tags ??= new List(); } internal set { _tags = value; } } @@ -120,7 +120,7 @@ public string User [DataMember] public string Computer { - get { return this._computerName ?? (this._computerName = PsUtils.GetHostName()); } + get { return this._computerName ??= PsUtils.GetHostName(); } set { this._computerName = value; } } diff --git a/src/System.Management.Automation/engine/InitialSessionState.cs b/src/System.Management.Automation/engine/InitialSessionState.cs index 8d9b01ad134..2495a4ac0fe 100644 --- a/src/System.Management.Automation/engine/InitialSessionState.cs +++ b/src/System.Management.Automation/engine/InitialSessionState.cs @@ -949,7 +949,7 @@ public override InitialSessionStateEntry Clone() /// public Collection Attributes { - get { return _attributes ?? (_attributes = new Collection()); } + get { return _attributes ??= new Collection(); } } private Collection _attributes; @@ -1346,7 +1346,7 @@ public static InitialSessionState CreateFromSessionConfigurationFile(string path public static InitialSessionState CreateRestricted(SessionCapabilities sessionCapabilities) { // only remote server has been requested - if (SessionCapabilities.RemoteServer == sessionCapabilities) + if (sessionCapabilities == SessionCapabilities.RemoteServer) { return CreateRestrictedForRemoteServer(); } @@ -2584,7 +2584,7 @@ HashSet GetPublicCommands() return null; } - private string[] GetModulesForUnResolvedCommands(IEnumerable unresolvedCommands, ExecutionContext context) + private static string[] GetModulesForUnResolvedCommands(IEnumerable unresolvedCommands, ExecutionContext context) { Collection modulesToImport = new Collection(); HashSet commandsToResolve = new HashSet(StringComparer.OrdinalIgnoreCase); @@ -3072,7 +3072,7 @@ private RunspaceOpenModuleLoadException ProcessModulesToImport( /// /// /// - private IEnumerable LookupCommands( + private static IEnumerable LookupCommands( string commandPattern, string moduleName, ExecutionContext context) @@ -4442,6 +4442,13 @@ .ForwardHelpCategory Cmdlet new SessionStateVariableEntry(SpecialVariables.FirstToken, null, string.Empty), new SessionStateVariableEntry(SpecialVariables.StackTrace, null, string.Empty), + // Variable which controls the output rendering + new SessionStateVariableEntry( + SpecialVariables.PSStyle, + PSStyle.Instance, + RunspaceInit.PSStyleDescription, + ScopedItemOptions.None), + // Variable which controls the encoding for piping data to a NativeCommand new SessionStateVariableEntry( SpecialVariables.OutputEncoding, diff --git a/src/System.Management.Automation/engine/InvocationInfo.cs b/src/System.Management.Automation/engine/InvocationInfo.cs index cae261aec7d..1ae22542c63 100644 --- a/src/System.Management.Automation/engine/InvocationInfo.cs +++ b/src/System.Management.Automation/engine/InvocationInfo.cs @@ -201,8 +201,7 @@ public Dictionary BoundParameters { get { - return _boundParameters ?? - (_boundParameters = new Dictionary(StringComparer.OrdinalIgnoreCase)); + return _boundParameters ??= new Dictionary(StringComparer.OrdinalIgnoreCase); } internal set { _boundParameters = value; } @@ -213,7 +212,7 @@ public Dictionary BoundParameters /// public List UnboundArguments { - get { return _unboundArguments ?? (_unboundArguments = new List()); } + get { return _unboundArguments ??= new List(); } internal set { _unboundArguments = value; } } diff --git a/src/System.Management.Automation/engine/LanguagePrimitives.cs b/src/System.Management.Automation/engine/LanguagePrimitives.cs index 703fbcd46e4..c397385e557 100644 --- a/src/System.Management.Automation/engine/LanguagePrimitives.cs +++ b/src/System.Management.Automation/engine/LanguagePrimitives.cs @@ -4349,19 +4349,21 @@ internal delegate T PSConverter(object valueToConvert, internal delegate object PSNullConverter(object nullOrAutomationNull); +#nullable enable internal interface IConversionData { object Converter { get; } ConversionRank Rank { get; } - object Invoke(object valueToConvert, + object? Invoke(object? valueToConvert, Type resultType, bool recurse, - PSObject originalValueToConvert, - IFormatProvider formatProvider, - TypeTable backupTable); + PSObject? originalValueToConvert, + IFormatProvider? formatProvider, + TypeTable? backupTable); } +#nullable restore [System.Diagnostics.DebuggerDisplay("{_converter.Method.Name}")] internal class ConversionData : IConversionData @@ -5104,7 +5106,7 @@ private static IConversionData FigureLanguageConversion(Type fromType, Type toTy return null; } - private struct SignatureComparator + private readonly struct SignatureComparator { private enum TypeMatchingContext { @@ -5779,7 +5781,7 @@ internal static IConversionData FigureConversion(Type fromType, Type toType) return CacheConversion(fromType, toType, converter, rank); } - internal class Null { }; + internal class Null { } private static IConversionData FigureConversionFromNull(Type toType) { diff --git a/src/System.Management.Automation/engine/ManagementObjectAdapter.cs b/src/System.Management.Automation/engine/ManagementObjectAdapter.cs index d1669bb4593..c591a6963ec 100644 --- a/src/System.Management.Automation/engine/ManagementObjectAdapter.cs +++ b/src/System.Management.Automation/engine/ManagementObjectAdapter.cs @@ -77,7 +77,7 @@ public WMIParameterInformation(string name, Type ty) : base(ty, true, null, fals /// /// /// - private IEnumerable GetTypeNameHierarchyFromDerivation(ManagementBaseObject managementObj, + private static IEnumerable GetTypeNameHierarchyFromDerivation(ManagementBaseObject managementObj, string dotnetBaseType, bool shouldIncludeNamespace) { StringBuilder type = new StringBuilder(200); diff --git a/src/System.Management.Automation/engine/MinishellParameterBinderController.cs b/src/System.Management.Automation/engine/MinishellParameterBinderController.cs index bd23408fcfa..e19defd57a7 100644 --- a/src/System.Management.Automation/engine/MinishellParameterBinderController.cs +++ b/src/System.Management.Automation/engine/MinishellParameterBinderController.cs @@ -254,7 +254,7 @@ private enum MinishellParameters Arguments = 0x02, InputFormat = 0x04, OutputFormat = 0x08 - }; + } /// /// Handles error handling if some parameter is specified more than once. diff --git a/src/System.Management.Automation/engine/Modules/GetModuleCommand.cs b/src/System.Management.Automation/engine/Modules/GetModuleCommand.cs index 4651f0c79de..663e1f4b0fe 100644 --- a/src/System.Management.Automation/engine/Modules/GetModuleCommand.cs +++ b/src/System.Management.Automation/engine/Modules/GetModuleCommand.cs @@ -174,7 +174,7 @@ PSObject outputObject in } } - private PSModuleInfo GetModuleInfoForRemoteModuleWithoutManifest(RemoteDiscoveryHelper.CimModule cimModule) + private static PSModuleInfo GetModuleInfoForRemoteModuleWithoutManifest(RemoteDiscoveryHelper.CimModule cimModule) { return new PSModuleInfo(cimModule.ModuleName, null, null); } diff --git a/src/System.Management.Automation/engine/Modules/ImportModuleCommand.cs b/src/System.Management.Automation/engine/Modules/ImportModuleCommand.cs index 2ddf17ff2b1..35e0b61ab20 100644 --- a/src/System.Management.Automation/engine/Modules/ImportModuleCommand.cs +++ b/src/System.Management.Automation/engine/Modules/ImportModuleCommand.cs @@ -573,11 +573,19 @@ private void ImportModule_ViaAssembly(ImportModuleOptions importModuleOptions, A if (!moduleLoaded) { - bool found; - PSModuleInfo module = LoadBinaryModule(false, null, null, suppliedAssembly, null, null, + PSModuleInfo module = LoadBinaryModule( + trySnapInName: false, + moduleName: null, + fileName: null, + suppliedAssembly, + moduleBase: null, + ss: null, importModuleOptions, ManifestProcessingFlags.LoadElements | ManifestProcessingFlags.WriteErrors | ManifestProcessingFlags.NullOnFirstError, - this.BasePrefix, false /* loadTypes */ , false /* loadFormats */, out found); + this.BasePrefix, + loadTypes: false, + loadFormats: false, + out bool found); if (found && module != null) { @@ -1393,7 +1401,7 @@ private static bool IsCmdletizationFile(RemoteDiscoveryHelper.CimModuleFile cimM return cimModuleFile.FileCode == RemoteDiscoveryHelper.CimFileCode.CmdletizationV1; } - private IEnumerable CreateCimModuleFiles( + private static IEnumerable CreateCimModuleFiles( RemoteDiscoveryHelper.CimModule remoteCimModule, RemoteDiscoveryHelper.CimFileCode fileCode, Func filesFilter, @@ -2068,7 +2076,7 @@ internal override IList ImportModulesUsingWinCompat(IEnumerable GetModuleForRootedPaths(List modulePat } } - private ErrorRecord CreateModuleNotFoundError(string modulePath) + private static ErrorRecord CreateModuleNotFoundError(string modulePath) { string errorMessage = StringUtil.Format(Modules.ModuleNotFoundForGetModule, modulePath); FileNotFoundException fnf = new FileNotFoundException(errorMessage); @@ -1140,7 +1141,7 @@ internal static Version GetMaximumVersion(string stringVersion) else { // If first conversion fails, try to convert * to maximum version - string maxRange = "999999999"; + const string maxRange = "999999999"; if (stringVersion[stringVersion.Length - 1] == '*') { stringVersion = stringVersion.Substring(0, stringVersion.Length - 1); @@ -1421,7 +1422,7 @@ private IEnumerable CreateFakeModuleObject(IEnumerable exportedTypeFiles; - if ( - !GetListOfFilesFromData(data, moduleManifestPath, "TypesToProcess", manifestProcessingFlags, moduleBase, - ".ps1xml", true, out exportedTypeFiles)) + if (!GetListOfFilesFromData( + data, + moduleManifestPath, + key: "TypesToProcess", + manifestProcessingFlags, + moduleBase, + extension: ".ps1xml", + verifyFilesExist: true, + out List exportedTypeFiles)) { containedErrors = true; if (bailOnFirstError) return null; @@ -2234,10 +2240,15 @@ internal PSModuleInfo LoadModuleManifest( } // Set up to load any format files that have been specified... - List exportedFormatFiles; - if ( - !GetListOfFilesFromData(data, moduleManifestPath, "FormatsToProcess", manifestProcessingFlags, - moduleBase, ".ps1xml", true, out exportedFormatFiles)) + if (!GetListOfFilesFromData( + data, + moduleManifestPath, + key: "FormatsToProcess", + manifestProcessingFlags, + moduleBase, + extension: ".ps1xml", + verifyFilesExist: true, + out List exportedFormatFiles)) { containedErrors = true; if (bailOnFirstError) return null; @@ -2276,10 +2287,15 @@ internal PSModuleInfo LoadModuleManifest( } // scripts to process - List scriptsToProcess; - if ( - !GetListOfFilesFromData(data, moduleManifestPath, "ScriptsToProcess", manifestProcessingFlags, - moduleBase, ".ps1", true, out scriptsToProcess)) + if (!GetListOfFilesFromData( + data, + moduleManifestPath, + key: "ScriptsToProcess", + manifestProcessingFlags, + moduleBase, + extension: ".ps1", + verifyFilesExist: true, + out List scriptsToProcess)) { containedErrors = true; if (bailOnFirstError) return null; @@ -2323,13 +2339,16 @@ internal PSModuleInfo LoadModuleManifest( } // Process "FileList" - List fileList; - if ( - !GetListOfFilesFromData(data, moduleManifestPath, "FileList", manifestProcessingFlags, moduleBase, "" - /*extension*/, - false - /* don't check file existence - don't want to change current behavior without feature team discussion */, - out fileList)) + if (!GetListOfFilesFromData( + data, + moduleManifestPath, + key: "FileList", + manifestProcessingFlags, + moduleBase, + extension: string.Empty, + // Don't check file existence - don't want to change current behavior without feature team discussion. + verifyFilesExist: false, + out List fileList)) { containedErrors = true; if (bailOnFirstError) return null; @@ -2927,8 +2946,8 @@ internal PSModuleInfo LoadModuleManifest( ss: null, options: nestedModuleOptions, manifestProcessingFlags: manifestProcessingFlags, - loadTypesFiles: true, - loadFormatFiles: true, + loadTypes: true, + loadFormats: true, privateData: privateData, found: out found, shortModuleName: null, @@ -3030,8 +3049,8 @@ internal PSModuleInfo LoadModuleManifest( ss: ss, options: options, manifestProcessingFlags: manifestProcessingFlags, - loadTypesFiles: (exportedTypeFiles == null || exportedTypeFiles.Count == 0), // If types files already loaded, don't load snapin files - loadFormatFiles: (exportedFormatFiles == null || exportedFormatFiles.Count == 0), // if format files already loaded, don't load snapin files + loadTypes: (exportedTypeFiles == null || exportedTypeFiles.Count == 0), // If types files already loaded, don't load snapin files + loadFormats: (exportedFormatFiles == null || exportedFormatFiles.Count == 0), // if format files already loaded, don't load snapin files privateData: privateData, found: out found, shortModuleName: null, @@ -3531,7 +3550,7 @@ private static void PropagateExportedTypesFromNestedModulesToRootModuleScope(Imp if (nestedModule != null) { var exportedTypes = nestedModule.GetExportedTypeDefinitions(); - if (exportedTypes != null && exportedTypes.Count != 0) + if (exportedTypes != null && exportedTypes.Count > 0) { foreach (var t in exportedTypes) { @@ -4203,7 +4222,7 @@ private static bool HasRequiredModulesCyclicReference(ModuleSpecification curren /// Search for a localized psd1 manifest file, using the same algorithm /// as Import-LocalizedData. /// - private ExternalScriptInfo FindLocalizedModuleManifest(string path) + private static ExternalScriptInfo FindLocalizedModuleManifest(string path) { string dir = Path.GetDirectoryName(path); string file = Path.GetFileName(path); @@ -4242,7 +4261,7 @@ private ExternalScriptInfo FindLocalizedModuleManifest(string path) /// /// Checks to see if the module manifest contains the specified key. /// If it does and it's valid, it returns true otherwise it returns false. - /// If the key wasn't there or wasn't valid, then is set to null + /// If the key wasn't there or wasn't valid, then is set to /// /// The hashtable to look for the key in. /// The manifest that generated the hashtable. @@ -4281,7 +4300,7 @@ internal bool GetListOfStringsFromData( /// /// Checks to see if the module manifest contains the specified key. /// If it does and it's valid, it returns true otherwise it returns false. - /// If the key wasn't there or wasn't valid, then is set to null. + /// If the key wasn't there or wasn't valid, then is set to . /// /// The hashtable to look for the key in. /// The manifest that generated the hashtable. @@ -4334,7 +4353,7 @@ private bool GetListOfWildcardsFromData( /// /// Checks to see if the module manifest contains the specified key. /// If it does and it's valid, it returns true otherwise it returns false. - /// If the key wasn't there or wasn't valid, then is set to null + /// If the key wasn't there or wasn't valid, then is set to /// /// The hashtable to look for the key in. /// The manifest that generated the hashtable. @@ -4342,7 +4361,7 @@ private bool GetListOfWildcardsFromData( /// Specifies how to treat errors and whether to load elements. /// Base directory of a module. /// Expected file extension (added to strings that didn't have an extension). - /// If true then we want to error out if the specified files don't exist. + /// If then we want to error out if the specified files don't exist. /// Returns the extracted version. /// private bool GetListOfFilesFromData( @@ -4435,7 +4454,7 @@ internal void SetModuleLoggingInformation(PSModuleInfo m) } } - private void SetModuleLoggingInformation(ModuleLoggingGroupPolicyStatus status, PSModuleInfo m, IEnumerable moduleNames) + private static void SetModuleLoggingInformation(ModuleLoggingGroupPolicyStatus status, PSModuleInfo m, IEnumerable moduleNames) { // TODO, insivara : What happens when Enabled but none of the other options (DefaultSystemModules, NonDefaultSystemModule, NonSystemModule, SpecificModules) are set? // After input from GP team for this behavior, need to revisit the commented out part @@ -4489,16 +4508,16 @@ internal static ModuleLoggingGroupPolicyStatus GetModuleLoggingInformation(out I /// /// Checks to see if the module manifest contains the specified key. - /// If it does and it can be converted to the expected type, then it returns true and sets to the value. - /// If the key is missing it returns true and sets to default(). - /// If the key is invalid then it returns false. + /// If it does and it can be converted to the expected type, then it returns and sets to the value. + /// If the key is missing it returns and sets to default(). + /// If the key is invalid then it returns . /// /// The hashtable to look for the key in. /// The manifest that generated the hashtable. /// The table key to use. /// Specifies how to treat errors and whether to load elements. /// Value from the manifest converted to the right type. - /// true if success; false if there were errors. + /// if success; if there were errors. internal bool GetScalarFromData( Hashtable data, string moduleManifestPath, @@ -5230,7 +5249,7 @@ internal bool DoesAlreadyLoadedModuleSatisfyConstraints(PSModuleInfo alreadyLoad /// /// /// Returns PSModuleInfo of an already loaded module if that module can be simply reimported and there is no need to proceed with a regular import. - /// Returns null if the caller should proceed with a regular import (either because there is no previously loaded module, or because the -Force flag was specified and the previously loaded module has been removed by this method). + /// Returns if the caller should proceed with a regular import (either because there is no previously loaded module, or because the -Force flag was specified and the previously loaded module has been removed by this method). /// internal PSModuleInfo IsModuleImportUnnecessaryBecauseModuleIsAlreadyLoaded(string modulePath, string prefix, ImportModuleOptions options) { @@ -5872,8 +5891,20 @@ internal PSModuleInfo LoadModule(PSModuleInfo parentModule, string fileName, str ext.Equals(StringLiterals.PowerShellNgenAssemblyExtension, StringComparison.OrdinalIgnoreCase) || ext.Equals(StringLiterals.PowerShellILExecutableExtension, StringComparison.OrdinalIgnoreCase)) { - module = LoadBinaryModule(false, ModuleIntrinsics.GetModuleName(fileName), fileName, null, - moduleBase, ss, options, manifestProcessingFlags, prefix, true, true, out found); + module = LoadBinaryModule( + trySnapInName: false, + ModuleIntrinsics.GetModuleName(fileName), + fileName, + assemblyToLoad: null, + moduleBase, + ss, + options, + manifestProcessingFlags, + prefix, + loadTypes: true, + loadFormats: true, + out found); + if (found && module != null) { // LanguageMode does not apply to binary modules @@ -6073,7 +6104,7 @@ private static bool ShouldProcessScriptModule(PSModuleInfo parentModule, ref boo private static readonly object s_lockObject = new object(); - private void ClearAnalysisCaches() + private static void ClearAnalysisCaches() { lock (s_lockObject) { @@ -6510,13 +6541,36 @@ private PSModuleInfo AnalyzeScriptFile(string filename, bool force, ExecutionCon /// Command name prefix. /// Sets this to true if an assembly was found. /// THe module info object that was created... - internal PSModuleInfo LoadBinaryModule(bool trySnapInName, string moduleName, string fileName, - Assembly assemblyToLoad, string moduleBase, SessionState ss, ImportModuleOptions options, - ManifestProcessingFlags manifestProcessingFlags, string prefix, - bool loadTypes, bool loadFormats, out bool found) + internal PSModuleInfo LoadBinaryModule( + bool trySnapInName, + string moduleName, + string fileName, + Assembly assemblyToLoad, + string moduleBase, + SessionState ss, + ImportModuleOptions options, + ManifestProcessingFlags manifestProcessingFlags, + string prefix, + bool loadTypes, + bool loadFormats, + out bool found) { - return LoadBinaryModule(null, trySnapInName, moduleName, fileName, assemblyToLoad, moduleBase, ss, options, - manifestProcessingFlags, prefix, loadTypes, loadFormats, out found, null, false); + return LoadBinaryModule( + parentModule: null, + trySnapInName, + moduleName, + fileName, + assemblyToLoad, + moduleBase, + ss, + options, + manifestProcessingFlags, + prefix, + loadTypes, + loadFormats, + out found, + shortModuleName: null, + disableFormatUpdates: false); } /// @@ -6542,7 +6596,22 @@ internal PSModuleInfo LoadBinaryModule(bool trySnapInName, string moduleName, st /// Short name for module. /// /// THe module info object that was created... - internal PSModuleInfo LoadBinaryModule(PSModuleInfo parentModule, bool trySnapInName, string moduleName, string fileName, Assembly assemblyToLoad, string moduleBase, SessionState ss, ImportModuleOptions options, ManifestProcessingFlags manifestProcessingFlags, string prefix, bool loadTypes, bool loadFormats, out bool found, string shortModuleName, bool disableFormatUpdates) + internal PSModuleInfo LoadBinaryModule( + PSModuleInfo parentModule, + bool trySnapInName, + string moduleName, + string fileName, + Assembly assemblyToLoad, + string moduleBase, + SessionState ss, + ImportModuleOptions options, + ManifestProcessingFlags manifestProcessingFlags, + string prefix, + bool loadTypes, + bool loadFormats, + out bool found, + string shortModuleName, + bool disableFormatUpdates) { PSModuleInfo module = null; diff --git a/src/System.Management.Automation/engine/Modules/ModuleIntrinsics.cs b/src/System.Management.Automation/engine/Modules/ModuleIntrinsics.cs index 71f86332861..94ce2664703 100644 --- a/src/System.Management.Automation/engine/Modules/ModuleIntrinsics.cs +++ b/src/System.Management.Automation/engine/Modules/ModuleIntrinsics.cs @@ -703,9 +703,9 @@ internal static bool MatchesModulePath(string modulePath, string requiredPath) } #if UNIX - StringComparison strcmp = StringComparison.Ordinal; + const StringComparison strcmp = StringComparison.Ordinal; #else - StringComparison strcmp = StringComparison.OrdinalIgnoreCase; + const StringComparison strcmp = StringComparison.OrdinalIgnoreCase; #endif // We must check modulePath (e.g. /path/to/module/module.psd1) against several possibilities: @@ -1719,6 +1719,7 @@ internal enum ModuleMatchFailure /// Used by Modules/Snapins to provide a hook to the engine for startup initialization /// w.r.t compiled assembly loading. /// +#nullable enable public interface IModuleAssemblyInitializer { /// diff --git a/src/System.Management.Automation/engine/Modules/NewModuleManifestCommand.cs b/src/System.Management.Automation/engine/Modules/NewModuleManifestCommand.cs index a1907a034ac..bf2e76501cc 100644 --- a/src/System.Management.Automation/engine/Modules/NewModuleManifestCommand.cs +++ b/src/System.Management.Automation/engine/Modules/NewModuleManifestCommand.cs @@ -534,7 +534,7 @@ public string DefaultCommandPrefix /// /// The string to quote. /// The quoted string. - private string QuoteName(string name) + private static string QuoteName(string name) { if (name == null) return "''"; @@ -546,7 +546,7 @@ private string QuoteName(string name) /// /// The Uri to quote. /// The quoted AbsoluteUri. - private string QuoteName(Uri name) + private static string QuoteName(Uri name) { if (name == null) return "''"; @@ -558,7 +558,7 @@ private string QuoteName(Uri name) /// /// The Version object to quote. /// The quoted Version string. - private string QuoteName(Version name) + private static string QuoteName(Version name) { if (name == null) return "''"; @@ -572,7 +572,7 @@ private string QuoteName(Version name) /// The list to quote. /// Streamwriter to get end of line character from. /// The quoted list. - private string QuoteNames(IEnumerable names, StreamWriter streamWriter) + private static string QuoteNames(IEnumerable names, StreamWriter streamWriter) { if (names == null) return "@()"; @@ -622,7 +622,7 @@ private string QuoteNames(IEnumerable names, StreamWriter streamWriter) /// /// /// - private IEnumerable PreProcessModuleSpec(IEnumerable moduleSpecs) + private static IEnumerable PreProcessModuleSpec(IEnumerable moduleSpecs) { if (moduleSpecs != null) { @@ -647,7 +647,7 @@ private IEnumerable PreProcessModuleSpec(IEnumerable moduleSpecs) /// The list to quote. /// Streamwriter to get end of line character from. /// The quoted list. - private string QuoteModules(IEnumerable moduleSpecs, StreamWriter streamWriter) + private static string QuoteModules(IEnumerable moduleSpecs, StreamWriter streamWriter) { StringBuilder result = new StringBuilder(); result.Append("@("); @@ -897,7 +897,7 @@ private string ManifestFragmentForNonSpecifiedManifestMember(string key, string _indent, resourceString, streamWriter.NewLine, key, value); } - private string ManifestComment(string insert, StreamWriter streamWriter) + private static string ManifestComment(string insert, StreamWriter streamWriter) { // Prefix a non-empty string with a space for formatting reasons... if (!string.IsNullOrEmpty(insert)) diff --git a/src/System.Management.Automation/engine/Modules/PSModuleInfo.cs b/src/System.Management.Automation/engine/Modules/PSModuleInfo.cs index caa4a5a666f..f2ab485aef0 100644 --- a/src/System.Management.Automation/engine/Modules/PSModuleInfo.cs +++ b/src/System.Management.Automation/engine/Modules/PSModuleInfo.cs @@ -299,8 +299,7 @@ public string ModuleBase { get { - return _moduleBase ?? - (_moduleBase = !string.IsNullOrEmpty(Path) ? IO.Path.GetDirectoryName(Path) : string.Empty); + return _moduleBase ??= !string.IsNullOrEmpty(Path) ? IO.Path.GetDirectoryName(Path) : string.Empty; } } @@ -582,7 +581,7 @@ public Dictionary ExportedFunctions } } - private bool IsScriptModuleFile(string path) + private static bool IsScriptModuleFile(string path) { var ext = System.IO.Path.GetExtension(path); return ext != null && s_scriptModuleExtensions.Contains(ext); @@ -922,8 +921,7 @@ public ReadOnlyCollection NestedModules { get { - return _readonlyNestedModules ?? - (_readonlyNestedModules = new ReadOnlyCollection(_nestedModules)); + return _readonlyNestedModules ??= new ReadOnlyCollection(_nestedModules); } } @@ -1014,8 +1012,7 @@ public ReadOnlyCollection RequiredModules { get { - return _readonlyRequiredModules ?? - (_readonlyRequiredModules = new ReadOnlyCollection(_requiredModules)); + return _readonlyRequiredModules ??= new ReadOnlyCollection(_requiredModules); } } @@ -1040,8 +1037,7 @@ internal ReadOnlyCollection RequiredModulesSpecification { get { - return _readonlyRequiredModulesSpecification ?? - (_readonlyRequiredModulesSpecification = new ReadOnlyCollection(_requiredModulesSpecification)); + return _readonlyRequiredModulesSpecification ??= new ReadOnlyCollection(_requiredModulesSpecification); } } diff --git a/src/System.Management.Automation/engine/Modules/RemoteDiscoveryHelper.cs b/src/System.Management.Automation/engine/Modules/RemoteDiscoveryHelper.cs index 65c2931db0f..9ece4af620f 100644 --- a/src/System.Management.Automation/engine/Modules/RemoteDiscoveryHelper.cs +++ b/src/System.Management.Automation/engine/Modules/RemoteDiscoveryHelper.cs @@ -31,7 +31,7 @@ internal class RemoteDiscoveryHelper private static Collection RehydrateHashtableKeys(PSObject pso, string propertyName) { - var rehydrationFlags = DeserializingTypeConverter.RehydrationFlags.NullValueOk | + const DeserializingTypeConverter.RehydrationFlags rehydrationFlags = DeserializingTypeConverter.RehydrationFlags.NullValueOk | DeserializingTypeConverter.RehydrationFlags.MissingPropertyOk; Hashtable hashtable = DeserializingTypeConverter.GetPropertyValue(pso, propertyName, rehydrationFlags); if (hashtable == null) @@ -53,7 +53,7 @@ private static Collection RehydrateHashtableKeys(PSObject pso, string pr internal static PSModuleInfo RehydratePSModuleInfo(PSObject deserializedModuleInfo) { - var rehydrationFlags = DeserializingTypeConverter.RehydrationFlags.NullValueOk | + const DeserializingTypeConverter.RehydrationFlags rehydrationFlags = DeserializingTypeConverter.RehydrationFlags.NullValueOk | DeserializingTypeConverter.RehydrationFlags.MissingPropertyOk; string name = DeserializingTypeConverter.GetPropertyValue(deserializedModuleInfo, "Name", rehydrationFlags); string path = DeserializingTypeConverter.GetPropertyValue(deserializedModuleInfo, "Path", rehydrationFlags); @@ -360,7 +360,7 @@ private static ErrorRecord GetErrorRecordForRemotePipelineInvocation(Exception i Exception outerException = new InvalidOperationException(errorMessage, innerException); RemoteException remoteException = innerException as RemoteException; - ErrorRecord remoteErrorRecord = remoteException != null ? remoteException.ErrorRecord : null; + ErrorRecord remoteErrorRecord = remoteException?.ErrorRecord; string errorId = remoteErrorRecord != null ? remoteErrorRecord.FullyQualifiedErrorId : innerException.GetType().Name; ErrorCategory errorCategory = remoteErrorRecord != null ? remoteErrorRecord.CategoryInfo.Category : ErrorCategory.NotSpecified; ErrorRecord errorRecord = new ErrorRecord(outerException, errorId, errorCategory, null); @@ -815,7 +815,7 @@ private static IEnumerable GetCimModules( ErrorRecord errorRecord = GetErrorRecordForRemoteDiscoveryProvider(exception); if (!cmdlet.MyInvocation.ExpectingInput) { - if (((-1) != errorRecord.FullyQualifiedErrorId.IndexOf(DiscoveryProviderNotFoundErrorId, StringComparison.OrdinalIgnoreCase)) || + if ((errorRecord.FullyQualifiedErrorId.IndexOf(DiscoveryProviderNotFoundErrorId, StringComparison.OrdinalIgnoreCase) != (-1)) || (cancellationToken.IsCancellationRequested || (exception is OperationCanceledException)) || (!cimSession.TestConnection())) { diff --git a/src/System.Management.Automation/engine/Modules/ScriptAnalysis.cs b/src/System.Management.Automation/engine/Modules/ScriptAnalysis.cs index 4db13309f6b..f2005400c9d 100644 --- a/src/System.Management.Automation/engine/Modules/ScriptAnalysis.cs +++ b/src/System.Management.Automation/engine/Modules/ScriptAnalysis.cs @@ -105,10 +105,15 @@ internal static string ReadScript(string path) } internal List DiscoveredExports { get; set; } + internal Dictionary DiscoveredAliases { get; set; } + internal List DiscoveredModules { get; set; } + internal List DiscoveredCommandFilters { get; set; } + internal bool AddsSelfToPath { get; set; } + internal List DiscoveredClasses { get; set; } } @@ -160,11 +165,17 @@ static ExportVisitor() private readonly bool _forCompletion; internal List DiscoveredExports { get; set; } + internal List DiscoveredModules { get; set; } + internal Dictionary DiscoveredFunctions { get; set; } + internal Dictionary DiscoveredAliases { get; set; } + internal List DiscoveredCommandFilters { get; set; } + internal bool AddsSelfToPath { get; set; } + internal List DiscoveredClasses { get; set; } public override AstVisitAction VisitTypeDefinition(TypeDefinitionAst typeDefinitionAst) @@ -451,7 +462,7 @@ private void ProcessCmdletArguments(object value, Action onEachArgument) // // It also only populates the bound parameters for a limited set of parameters needed // for module analysis. - private Hashtable DoPsuedoParameterBinding(CommandAst commandAst, string commandName) + private static Hashtable DoPsuedoParameterBinding(CommandAst commandAst, string commandName) { var result = new Hashtable(StringComparer.OrdinalIgnoreCase); @@ -564,6 +575,7 @@ private struct ParameterInfo internal class RequiredModuleInfo { internal string Name { get; set; } + internal List CommandsToPostFilter { get; set; } } } diff --git a/src/System.Management.Automation/engine/Modules/TestModuleManifestCommand.cs b/src/System.Management.Automation/engine/Modules/TestModuleManifestCommand.cs index 06a5789d629..265287a010f 100644 --- a/src/System.Management.Automation/engine/Modules/TestModuleManifestCommand.cs +++ b/src/System.Management.Automation/engine/Modules/TestModuleManifestCommand.cs @@ -404,7 +404,7 @@ private bool IsValidFilePath(string path, PSModuleInfo module, bool verifyPathSc /// /// /// - private bool IsValidGacAssembly(string assemblyName) + private static bool IsValidGacAssembly(string assemblyName) { #if UNIX return false; @@ -420,23 +420,13 @@ private bool IsValidGacAssembly(string assemblyName) try { - var allFiles = Directory.GetFiles(gacPath, assemblyFile, SearchOption.AllDirectories); - - if (allFiles.Length == 0) - { - var allNgenFiles = Directory.GetFiles(gacPath, ngenAssemblyFile, SearchOption.AllDirectories); - if (allNgenFiles.Length == 0) - { - return false; - } - } + return Directory.EnumerateFiles(gacPath, assemblyFile, SearchOption.AllDirectories).Any() + || Directory.EnumerateFiles(gacPath, ngenAssemblyFile, SearchOption.AllDirectories).Any(); } catch { return false; } - - return true; #endif } } diff --git a/src/System.Management.Automation/engine/MshCmdlet.cs b/src/System.Management.Automation/engine/MshCmdlet.cs index fe995d9096e..a2a7023b2d0 100644 --- a/src/System.Management.Automation/engine/MshCmdlet.cs +++ b/src/System.Management.Automation/engine/MshCmdlet.cs @@ -68,7 +68,7 @@ public interface IDynamicParameters /// Type used to define a parameter on a cmdlet script of function that /// can only be used as a switch. /// - public struct SwitchParameter + public readonly struct SwitchParameter { private readonly bool _isPresent; /// @@ -956,7 +956,7 @@ public string ParameterSetName /// /// If the cmdlet declares paging support (via ), /// then property contains arguments of the paging parameters. - /// Otherwise property is null. + /// Otherwise property is . /// public PagingParameters PagingParameters { @@ -999,7 +999,7 @@ public CommandInvocationIntrinsics InvokeCommand { using (PSTransactionManager.GetEngineProtectionScope()) { - return _invokeCommand ?? (_invokeCommand = new CommandInvocationIntrinsics(Context, this)); + return _invokeCommand ??= new CommandInvocationIntrinsics(Context, this); } } } diff --git a/src/System.Management.Automation/engine/MshCommandRuntime.cs b/src/System.Management.Automation/engine/MshCommandRuntime.cs index 2709ba1384e..a1cd276fa89 100644 --- a/src/System.Management.Automation/engine/MshCommandRuntime.cs +++ b/src/System.Management.Automation/engine/MshCommandRuntime.cs @@ -125,7 +125,7 @@ public override string ToString() /// The invocation object for this command. internal InvocationInfo MyInvocation { - get { return _myInvocation ?? (_myInvocation = _thisCommand.MyInvocation); } + get { return _myInvocation ??= _thisCommand.MyInvocation; } } /// @@ -1735,8 +1735,13 @@ public bool ShouldContinue(string query, string caption) { bool yesToAll = false; bool noToAll = false; - bool hasSecurityImpact = false; - return DoShouldContinue(query, caption, hasSecurityImpact, false, ref yesToAll, ref noToAll); + return DoShouldContinue( + query, + caption, + hasSecurityImpact: false, + supportsToAllOptions: false, + ref yesToAll, + ref noToAll); } /// @@ -2206,7 +2211,7 @@ internal void SetMergeFromRuntime(MshCommandRuntime fromRuntime) /// internal Pipe InputPipe { - get { return _inputPipe ?? (_inputPipe = new Pipe()); } + get { return _inputPipe ??= new Pipe(); } set { _inputPipe = value; } } @@ -2216,7 +2221,7 @@ internal Pipe InputPipe /// internal Pipe OutputPipe { - get { return _outputPipe ?? (_outputPipe = new Pipe()); } + get { return _outputPipe ??= new Pipe(); } set { _outputPipe = value; } } @@ -2239,7 +2244,7 @@ internal object[] GetResultsAsArray() /// internal Pipe ErrorOutputPipe { - get { return _errorOutputPipe ?? (_errorOutputPipe = new Pipe()); } + get { return _errorOutputPipe ??= new Pipe(); } set { _errorOutputPipe = value; } } @@ -2844,20 +2849,20 @@ internal void _WriteErrorSkipAllowCheck(ErrorRecord errorRecord, ActionPreferenc } // No trace of the error in the 'Ignore' case - if (ActionPreference.Ignore == preference) + if (preference == ActionPreference.Ignore) { return; // do not write or record to output pipe } // 2004/05/26-JonN // The object is not written in the SilentlyContinue case - if (ActionPreference.SilentlyContinue == preference) + if (preference == ActionPreference.SilentlyContinue) { AppendErrorToVariables(errorRecord); return; // do not write to output pipe } - if (ContinueStatus.YesToAll == lastErrorContinueStatus) + if (lastErrorContinueStatus == ContinueStatus.YesToAll) { preference = ActionPreference.Continue; } @@ -3384,7 +3389,7 @@ internal enum ContinueStatus No, YesToAll, NoToAll - }; + } internal ContinueStatus lastShouldProcessContinueStatus = ContinueStatus.Yes; internal ContinueStatus lastErrorContinueStatus = ContinueStatus.Yes; @@ -3684,7 +3689,7 @@ bool hasSecurityImpact CBhost.EnterNestedPrompt(_thisCommand); // continue loop } - else if (-1 == response) + else if (response == -1) { ActionPreferenceStopException e = new ActionPreferenceStopException( @@ -3746,6 +3751,17 @@ internal void SetVariableListsInPipe() if (this.PipelineVariable != null) { + // _state can be null if the current script block is dynamicparam, etc. + if (_state != null) + { + // Create the pipeline variable + _state.PSVariable.Set(_pipelineVarReference); + + // Get the reference again in case we re-used one from the + // same scope. + _pipelineVarReference = _state.PSVariable.Get(this.PipelineVariable); + } + this.OutputPipe.SetPipelineVariable(_pipelineVarReference); } } diff --git a/src/System.Management.Automation/engine/MshMemberInfo.cs b/src/System.Management.Automation/engine/MshMemberInfo.cs index 50d036a1bdd..9bbec9c4312 100644 --- a/src/System.Management.Automation/engine/MshMemberInfo.cs +++ b/src/System.Management.Automation/engine/MshMemberInfo.cs @@ -6,6 +6,7 @@ using System.Collections.ObjectModel; using System.Collections.Specialized; using System.ComponentModel; +using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Management.Automation.Internal; @@ -161,7 +162,7 @@ internal enum MshMemberMatchOptions IncludeHidden = 1, /// - /// Only include members with property set to true + /// Only include members with property set to /// OnlySerializable = 2 } @@ -875,6 +876,7 @@ public override PSMemberInfo Copy() /// /// When getting and there is no getter or when the getter throws an exception. /// When setting and there is no setter or when the setter throws an exception. + [SuppressMessage("Design", "CA1065:Do not raise exceptions in unexpected locations", Justification = "")] public override object Value { get @@ -964,6 +966,7 @@ public override object Value /// Gets the type of the value for this member. /// /// If there is no property getter. + [SuppressMessage("Design", "CA1065:Do not raise exceptions in unexpected locations", Justification = "")] public override string TypeNameOfValue { get @@ -1786,6 +1789,7 @@ public override PSMemberInfo Copy() /// /// When setting and there is no setter, /// when the setter throws an exception or when there is no Runspace to run the script. + [SuppressMessage("Design", "CA1065:Do not raise exceptions in unexpected locations", Justification = "")] public override object Value { get @@ -1911,12 +1915,12 @@ internal PSMethodInvocationConstraints( } /// - /// If null then there are no constraints + /// If then there are no constraints /// public Type MethodTargetType { get; } /// - /// If null then there are no constraints + /// If then there are no constraints /// public IEnumerable ParameterTypes => _parameterTypes; @@ -1971,7 +1975,7 @@ public bool Equals(PSMethodInvocationConstraints other) public override bool Equals(object obj) { - if (ReferenceEquals(null, obj)) + if (obj is null) { return false; } @@ -3728,7 +3732,7 @@ internal static PSMemberInfoInternalCollection Match(PSMemberInfoInternalC /// A Predicate that determine if a member name matches a criterion. /// /// - /// true if the matches the predicate, otherwise false. + /// if the matches the predicate, otherwise . public delegate bool MemberNamePredicate(string memberName); /// diff --git a/src/System.Management.Automation/engine/MshObject.cs b/src/System.Management.Automation/engine/MshObject.cs index 71d567c7d1b..2253c7c913e 100644 --- a/src/System.Management.Automation/engine/MshObject.cs +++ b/src/System.Management.Automation/engine/MshObject.cs @@ -651,6 +651,7 @@ internal static PSObject ConstructPSObjectFromSerializationInfo(SerializationInf new PSObject.AdapterSet(new ThirdPartyAdapter(typeof(Microsoft.Management.Infrastructure.CimInstance), new Microsoft.PowerShell.Cim.CimInstanceAdapter()), PSObject.DotNetInstanceAdapter); + #if !UNIX private static readonly AdapterSet s_managementObjectAdapter = new AdapterSet(new ManagementObjectAdapter(), DotNetInstanceAdapter); private static readonly AdapterSet s_managementClassAdapter = new AdapterSet(new ManagementClassApdapter(), DotNetInstanceAdapter); @@ -946,6 +947,7 @@ public static implicit operator PSObject(int valueToConvert) { return PSObject.AsPSObject(valueToConvert); } + /// /// /// @@ -954,6 +956,7 @@ public static implicit operator PSObject(string valueToConvert) { return PSObject.AsPSObject(valueToConvert); } + /// /// /// @@ -962,6 +965,7 @@ public static implicit operator PSObject(Hashtable valueToConvert) { return PSObject.AsPSObject(valueToConvert); } + /// /// /// @@ -970,6 +974,7 @@ public static implicit operator PSObject(double valueToConvert) { return PSObject.AsPSObject(valueToConvert); } + /// /// /// diff --git a/src/System.Management.Automation/engine/MshObjectTypeDescriptor.cs b/src/System.Management.Automation/engine/MshObjectTypeDescriptor.cs index 9a36e04140b..6e941b4c5f1 100644 --- a/src/System.Management.Automation/engine/MshObjectTypeDescriptor.cs +++ b/src/System.Management.Automation/engine/MshObjectTypeDescriptor.cs @@ -92,6 +92,7 @@ internal GettingValueExceptionEventArgs(Exception exception) public class PSObjectPropertyDescriptor : PropertyDescriptor { internal event EventHandler SettingValueException; + internal event EventHandler GettingValueException; internal PSObjectPropertyDescriptor(string propertyName, Type propertyType, bool isReadOnly, AttributeCollection propertyAttributes) @@ -222,8 +223,8 @@ private static PSObject GetComponentPSObject(object component) { throw PSTraceSource.NewArgumentException(nameof(component), ExtendedTypeSystem.InvalidComponent, "component", - typeof(PSObject).Name, - typeof(PSObjectTypeDescriptor).Name); + nameof(PSObject), + nameof(PSObjectTypeDescriptor)); } mshObj = descriptor.Instance; diff --git a/src/System.Management.Automation/engine/NativeCommandProcessor.cs b/src/System.Management.Automation/engine/NativeCommandProcessor.cs index bcd42658d22..96ad84a6c46 100644 --- a/src/System.Management.Automation/engine/NativeCommandProcessor.cs +++ b/src/System.Management.Automation/engine/NativeCommandProcessor.cs @@ -32,7 +32,7 @@ internal enum NativeCommandIOFormat { Text, Xml - }; + } /// /// Different streams produced by minishell output. @@ -824,7 +824,7 @@ public int ParentId get { // Construct parent id only once. - if (int.MinValue == _parentId) + if (_parentId == int.MinValue) { ConstructParentId(); } @@ -1169,7 +1169,7 @@ private ProcessStartInfo GetProcessStartInfo(bool redirectOutput, bool redirectE return startInfo; } - private bool IsDownstreamOutDefault(Pipe downstreamPipe) + private static bool IsDownstreamOutDefault(Pipe downstreamPipe) { Diagnostics.Assert(downstreamPipe != null, "Caller makes sure the passed-in parameter is not null."); @@ -1316,6 +1316,10 @@ private void CalculateIORedirection(bool isWindowsApplication, out bool redirect // On Windows, check the extension list and see if we should try to execute this directly. // Otherwise, use the platform library to check executability + [SuppressMessage( + "Performance", + "CA1822:Mark members as static", + Justification = "Accesses instance members in preprocessor branch.")] private bool IsExecutable(string path) { #if UNIX @@ -1419,7 +1423,7 @@ private struct SHFILEINFO [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 80)] public string szTypeName; - }; + } private const uint SHGFI_EXETYPE = 0x000002000; // flag used to ask to return exe type diff --git a/src/System.Management.Automation/engine/PSClassSearcher.cs b/src/System.Management.Automation/engine/PSClassSearcher.cs index 82c96c8a350..ce47ae93e16 100644 --- a/src/System.Management.Automation/engine/PSClassSearcher.cs +++ b/src/System.Management.Automation/engine/PSClassSearcher.cs @@ -288,7 +288,7 @@ private Collection GetPSModuleInfo(string modulePath) return modules; } - private PSClassInfo ConvertToClassInfo(PSModuleInfo module, ScriptBlockAst ast, TypeDefinitionAst statement) + private static PSClassInfo ConvertToClassInfo(PSModuleInfo module, ScriptBlockAst ast, TypeDefinitionAst statement) { PSClassInfo classInfo = new PSClassInfo(statement.Name); Dbg.Assert(statement.Name != null, "statement should have a name."); diff --git a/src/System.Management.Automation/engine/PSConfiguration.cs b/src/System.Management.Automation/engine/PSConfiguration.cs index ade427b2154..16273979a69 100644 --- a/src/System.Management.Automation/engine/PSConfiguration.cs +++ b/src/System.Management.Automation/engine/PSConfiguration.cs @@ -174,7 +174,7 @@ internal void SetExecutionPolicy(ConfigScope scope, string shellId, string execu WriteValueToFile(scope, key, executionPolicy); } - private string GetExecutionPolicySettingKey(string shellId) + private static string GetExecutionPolicySettingKey(string shellId) { return string.Equals(shellId, Utils.DefaultPowerShellShellID, StringComparison.Ordinal) ? ExecutionPolicyDefaultShellKey @@ -402,6 +402,10 @@ private T ReadValueFromFile(ConfigScope scope, string key, T defaultValue = d configData = serializer.Deserialize(jsonReader) ?? emptyConfig; } + catch (Exception exc) + { + throw PSTraceSource.NewInvalidOperationException(exc, PSConfigurationStrings.CanNotConfigurationFile, args: fileName); + } finally { fileLock.ExitReadLock(); @@ -562,7 +566,7 @@ private void UpdateValueInFile(ConfigScope scope, string key, T value, bool a /// The value to write. private void WriteValueToFile(ConfigScope scope, string key, T value) { - if (ConfigScope.CurrentUser == scope && !Directory.Exists(perUserConfigDirectory)) + if (scope == ConfigScope.CurrentUser && !Directory.Exists(perUserConfigDirectory)) { Directory.CreateDirectory(perUserConfigDirectory); } @@ -636,11 +640,17 @@ private void RemoveValueFromFile(ConfigScope scope, string key) internal sealed class PowerShellPolicies { public ScriptExecution ScriptExecution { get; set; } + public ScriptBlockLogging ScriptBlockLogging { get; set; } + public ModuleLogging ModuleLogging { get; set; } + public ProtectedEventLogging ProtectedEventLogging { get; set; } + public Transcription Transcription { get; set; } + public UpdatableHelp UpdatableHelp { get; set; } + public ConsoleSessionConfiguration ConsoleSessionConfiguration { get; set; } } @@ -652,6 +662,7 @@ internal abstract class PolicyBase { } internal sealed class ScriptExecution : PolicyBase { public string ExecutionPolicy { get; set; } + public bool? EnableScripts { get; set; } } @@ -661,6 +672,7 @@ internal sealed class ScriptExecution : PolicyBase internal sealed class ScriptBlockLogging : PolicyBase { public bool? EnableScriptBlockInvocationLogging { get; set; } + public bool? EnableScriptBlockLogging { get; set; } } @@ -670,6 +682,7 @@ internal sealed class ScriptBlockLogging : PolicyBase internal sealed class ModuleLogging : PolicyBase { public bool? EnableModuleLogging { get; set; } + public string[] ModuleNames { get; set; } } @@ -679,7 +692,9 @@ internal sealed class ModuleLogging : PolicyBase internal sealed class Transcription : PolicyBase { public bool? EnableTranscripting { get; set; } + public bool? EnableInvocationHeader { get; set; } + public string OutputDirectory { get; set; } } @@ -689,6 +704,7 @@ internal sealed class Transcription : PolicyBase internal sealed class UpdatableHelp : PolicyBase { public bool? EnableUpdateHelpDefaultSourcePath { get; set; } + public string DefaultSourcePath { get; set; } } @@ -698,6 +714,7 @@ internal sealed class UpdatableHelp : PolicyBase internal sealed class ConsoleSessionConfiguration : PolicyBase { public bool? EnableConsoleSessionConfiguration { get; set; } + public string ConsoleSessionConfigurationName { get; set; } } @@ -707,6 +724,7 @@ internal sealed class ConsoleSessionConfiguration : PolicyBase internal sealed class ProtectedEventLogging : PolicyBase { public bool? EnableProtectedEventLogging { get; set; } + public string[] EncryptionCertificate { get; set; } } diff --git a/src/System.Management.Automation/engine/PSVersionInfo.cs b/src/System.Management.Automation/engine/PSVersionInfo.cs index 529374a58db..289f105987e 100644 --- a/src/System.Management.Automation/engine/PSVersionInfo.cs +++ b/src/System.Management.Automation/engine/PSVersionInfo.cs @@ -859,7 +859,7 @@ public int CompareTo(object version) /// public int CompareTo(SemanticVersion value) { - if ((object)value == null) + if (value is null) return 1; if (Major != value.Major) diff --git a/src/System.Management.Automation/engine/ParameterBinderBase.cs b/src/System.Management.Automation/engine/ParameterBinderBase.cs index daa5b2f8759..ee7028c3865 100644 --- a/src/System.Management.Automation/engine/ParameterBinderBase.cs +++ b/src/System.Management.Automation/engine/ParameterBinderBase.cs @@ -172,7 +172,7 @@ internal object Target /// internal CommandLineParameters CommandLineParameters { - get { return _commandLineParameters ?? (_commandLineParameters = new CommandLineParameters()); } + get { return _commandLineParameters ??= new CommandLineParameters(); } // Setter is needed to pass into RuntimeParameterBinder instances set { _commandLineParameters = value; } @@ -439,7 +439,7 @@ internal virtual bool BindParameter( GetErrorExtent(parameter), parameterMetadata.Name, parameterMetadata.Type, - (parameterValue == null) ? null : parameterValue.GetType(), + parameterValue?.GetType(), ParameterBinderStrings.ParameterArgumentTransformationError, "ParameterArgumentTransformationError", e.Message); @@ -522,7 +522,7 @@ internal virtual bool BindParameter( GetErrorExtent(parameter), parameterMetadata.Name, parameterMetadata.Type, - (parameterValue == null) ? null : parameterValue.GetType(), + parameterValue?.GetType(), ParameterBinderStrings.ParameterArgumentValidationError, "ParameterArgumentValidationError", e.Message); @@ -586,7 +586,7 @@ internal virtual bool BindParameter( if (bindError != null) { - Type specifiedType = (parameterValue == null) ? null : parameterValue.GetType(); + Type specifiedType = parameterValue?.GetType(); ParameterBindingException bindingException = new ParameterBindingException( bindError, @@ -736,7 +736,7 @@ private void ValidateNullOrEmptyArgument( GetErrorExtent(parameter), parameterMetadata.Name, parameterMetadata.Type, - (parameterValue == null) ? null : parameterValue.GetType(), + parameterValue?.GetType(), ParameterBinderStrings.ParameterArgumentValidationErrorEmptyStringNotAllowed, "ParameterArgumentValidationErrorEmptyStringNotAllowed"); throw bindingException; @@ -813,7 +813,7 @@ private void ValidateNullOrEmptyArgument( GetErrorExtent(parameter), parameterMetadata.Name, parameterMetadata.Type, - (parameterValue == null) ? null : parameterValue.GetType(), + parameterValue?.GetType(), resourceString, errorId); throw bindingException; @@ -1781,7 +1781,7 @@ private object EncodeCollection( GetErrorExtent(argument), parameterName, toType, - (currentValueElement == null) ? null : currentValueElement.GetType(), + currentValueElement?.GetType(), ParameterBinderStrings.CannotConvertArgument, "CannotConvertArgument", currentValueElement ?? "null", @@ -1878,7 +1878,7 @@ private object EncodeCollection( GetErrorExtent(argument), parameterName, toType, - (currentValue == null) ? null : currentValue.GetType(), + currentValue?.GetType(), ParameterBinderStrings.CannotConvertArgument, "CannotConvertArgument", currentValue ?? "null", diff --git a/src/System.Management.Automation/engine/ParameterSetInfo.cs b/src/System.Management.Automation/engine/ParameterSetInfo.cs index 97f4d72ca4c..74745fca6da 100644 --- a/src/System.Management.Automation/engine/ParameterSetInfo.cs +++ b/src/System.Management.Automation/engine/ParameterSetInfo.cs @@ -105,7 +105,7 @@ public override string ToString() result.Append(']'); }); - return result.ToString(); + return result.ToString(); } /// diff --git a/src/System.Management.Automation/engine/PathInterfaces.cs b/src/System.Management.Automation/engine/PathInterfaces.cs index 2cf562d5f85..9a604829295 100644 --- a/src/System.Management.Automation/engine/PathInterfaces.cs +++ b/src/System.Management.Automation/engine/PathInterfaces.cs @@ -1402,7 +1402,7 @@ private LocationGlobber PathResolver _sessionState != null, "The only constructor for this class should always set the sessionState field"); - return _pathResolver ?? (_pathResolver = _sessionState.ExecutionContext.LocationGlobber); + return _pathResolver ??= _sessionState.ExecutionContext.LocationGlobber; } } diff --git a/src/System.Management.Automation/engine/Pipe.cs b/src/System.Management.Automation/engine/Pipe.cs index 98b55cf1105..c930a43ef99 100644 --- a/src/System.Management.Automation/engine/Pipe.cs +++ b/src/System.Management.Automation/engine/Pipe.cs @@ -16,7 +16,7 @@ internal enum VariableStreamKind Error, Warning, Information - }; + } /// /// Pipe provides a way to stitch two commands. @@ -299,7 +299,7 @@ internal void SetVariableListForTemporaryPipe(Pipe tempPipe) CopyVariableToTempPipe(VariableStreamKind.Information, _informationVariableList, tempPipe); } - private void CopyVariableToTempPipe(VariableStreamKind streamKind, List variableList, Pipe tempPipe) + private static void CopyVariableToTempPipe(VariableStreamKind streamKind, List variableList, Pipe tempPipe) { if (variableList != null && variableList.Count > 0) { diff --git a/src/System.Management.Automation/engine/PseudoParameterBinder.cs b/src/System.Management.Automation/engine/PseudoParameterBinder.cs index bddbe643f59..9bebe01b2e7 100644 --- a/src/System.Management.Automation/engine/PseudoParameterBinder.cs +++ b/src/System.Management.Automation/engine/PseudoParameterBinder.cs @@ -36,7 +36,7 @@ internal RuntimeDefinedParameterBinder( { string key = pair.Key; RuntimeDefinedParameter pp = pair.Value; - string ppName = (pp == null) ? null : pp.Name; + string ppName = pp?.Name; if (pp == null || key != ppName) { ParameterBindingException bindingException = diff --git a/src/System.Management.Automation/engine/ReflectionParameterBinder.cs b/src/System.Management.Automation/engine/ReflectionParameterBinder.cs index ee0562f5b89..6488dbcee90 100644 --- a/src/System.Management.Automation/engine/ReflectionParameterBinder.cs +++ b/src/System.Management.Automation/engine/ReflectionParameterBinder.cs @@ -124,7 +124,7 @@ internal override void BindParameter(string name, object value, CompiledCommandP try { var setter = parameterMetadata != null - ? (parameterMetadata.Setter ?? (parameterMetadata.Setter = GetSetter(Target.GetType(), name))) + ? (parameterMetadata.Setter ??= GetSetter(Target.GetType(), name)) : GetSetter(Target.GetType(), name); setter(Target, value); } diff --git a/src/System.Management.Automation/engine/ScriptCommandProcessor.cs b/src/System.Management.Automation/engine/ScriptCommandProcessor.cs index 89e898a5532..99b685e07d2 100644 --- a/src/System.Management.Automation/engine/ScriptCommandProcessor.cs +++ b/src/System.Management.Automation/engine/ScriptCommandProcessor.cs @@ -131,7 +131,7 @@ protected void CommonInitialization(ScriptBlock scriptBlock, ExecutionContext co /// /// Help target to request. /// Help category to request. - /// true if user requested help; false otherwise. + /// if user requested help; otherwise. internal override bool IsHelpRequested(out string helpTarget, out HelpCategory helpCategory) { if (arguments != null && CommandInfo != null && !string.IsNullOrEmpty(CommandInfo.Name) && _scriptBlock != null) @@ -274,7 +274,7 @@ private void Init() { _scriptBlock = base._scriptBlock; _obsoleteAttribute = _scriptBlock.ObsoleteAttribute; - _runOptimizedCode = _scriptBlock.Compile(optimized: _context._debuggingMode > 0 ? false : UseLocalScope); + _runOptimizedCode = _scriptBlock.Compile(optimized: _context._debuggingMode <= 0 && UseLocalScope); _localsTuple = _scriptBlock.MakeLocalsTuple(_runOptimizedCode); if (UseLocalScope) diff --git a/src/System.Management.Automation/engine/ScriptInfo.cs b/src/System.Management.Automation/engine/ScriptInfo.cs index 9c6b097fc05..af91867c452 100644 --- a/src/System.Management.Automation/engine/ScriptInfo.cs +++ b/src/System.Management.Automation/engine/ScriptInfo.cs @@ -116,9 +116,8 @@ internal override CommandMetadata CommandMetadata { get { - return _commandMetadata ?? - (_commandMetadata = - new CommandMetadata(this.ScriptBlock, this.Name, LocalPipeline.GetExecutionContextFromTLS())); + return _commandMetadata ??= + new CommandMetadata(this.ScriptBlock, this.Name, LocalPipeline.GetExecutionContextFromTLS()); } } diff --git a/src/System.Management.Automation/engine/SerializationStrings.cs b/src/System.Management.Automation/engine/SerializationStrings.cs index a06156086d7..81b0f9cb741 100644 --- a/src/System.Management.Automation/engine/SerializationStrings.cs +++ b/src/System.Management.Automation/engine/SerializationStrings.cs @@ -308,5 +308,5 @@ internal static class SerializationStrings internal const string MonadNamespacePrefix = "ps"; #endregion namespace values - }; + } } diff --git a/src/System.Management.Automation/engine/SessionState.cs b/src/System.Management.Automation/engine/SessionState.cs index 218fa6fd1c0..e0bdbd23ee0 100644 --- a/src/System.Management.Automation/engine/SessionState.cs +++ b/src/System.Management.Automation/engine/SessionState.cs @@ -143,7 +143,7 @@ internal void InitializeSessionStateInternalSpecialVariables(bool clearVariables /// internal LocationGlobber Globber { - get { return _globberPrivate ?? (_globberPrivate = ExecutionContext.LocationGlobber); } + get { return _globberPrivate ??= ExecutionContext.LocationGlobber; } } private LocationGlobber _globberPrivate; @@ -158,7 +158,7 @@ internal LocationGlobber Globber /// internal SessionState PublicSessionState { - get { return _publicSessionState ?? (_publicSessionState = new SessionState(this)); } + get { return _publicSessionState ??= new SessionState(this); } set { _publicSessionState = value; } } @@ -170,7 +170,7 @@ internal SessionState PublicSessionState /// internal ProviderIntrinsics InvokeProvider { - get { return _invokeProvider ?? (_invokeProvider = new ProviderIntrinsics(this)); } + get { return _invokeProvider ??= new ProviderIntrinsics(this); } } private ProviderIntrinsics _invokeProvider; @@ -389,7 +389,7 @@ internal SessionStateEntryVisibility CheckApplicationVisibility(string applicati return checkPathVisibility(Applications, applicationPath); } - private SessionStateEntryVisibility checkPathVisibility(List list, string path) + private static SessionStateEntryVisibility checkPathVisibility(List list, string path) { if (list == null || list.Count == 0) return SessionStateEntryVisibility.Private; if (string.IsNullOrEmpty(path)) return SessionStateEntryVisibility.Private; diff --git a/src/System.Management.Automation/engine/SessionStateContainer.cs b/src/System.Management.Automation/engine/SessionStateContainer.cs index a2b6f3baffa..ca7f03a42ca 100644 --- a/src/System.Management.Automation/engine/SessionStateContainer.cs +++ b/src/System.Management.Automation/engine/SessionStateContainer.cs @@ -2061,7 +2061,7 @@ internal object GetChildItemsDynamicParameters( } // Detect if the GetChildItemDynamicParameters has been overridden. - private bool HasGetChildItemDynamicParameters(ProviderInfo providerInfo) + private static bool HasGetChildItemDynamicParameters(ProviderInfo providerInfo) { Type providerType = providerInfo.ImplementingType; @@ -4038,7 +4038,7 @@ private bool HasChildItems( #region CopyItem /// - /// Copies an item at the specified path to an item at the . + /// Copies an item at the specified path to an item at the . /// /// /// The path(s) of the item(s) to copy. @@ -4106,7 +4106,7 @@ internal Collection CopyItem(string[] paths, } /// - /// Copies an item at the specified path to an item at the . + /// Copies an item at the specified path to an item at the . /// /// /// The path(s) of the item(s) to copy. @@ -4776,7 +4776,7 @@ private object CopyItemDynamicParameters( // This function validates a remote path, and if it exists, it returns the root path. // - private string ValidateRemotePathAndGetRoot(string path, Runspaces.PSSession session, CmdletProviderContext context, PSLanguageMode? languageMode, bool sourceIsRemote) + private static string ValidateRemotePathAndGetRoot(string path, Runspaces.PSSession session, CmdletProviderContext context, PSLanguageMode? languageMode, bool sourceIsRemote) { Hashtable op = null; @@ -4790,9 +4790,8 @@ private string ValidateRemotePathAndGetRoot(string path, Runspaces.PSSession ses if (languageMode.HasValue && (languageMode.Value == PSLanguageMode.ConstrainedLanguage || languageMode.Value == PSLanguageMode.NoLanguage)) { - var psRemoteUtilsName = CopyFileRemoteUtils.PSCopyRemoteUtilsName; ps.Runspace = session.Runspace; - ps.AddCommand("Get-Command").AddArgument(psRemoteUtilsName); + ps.AddCommand("Get-Command").AddArgument(CopyFileRemoteUtils.PSCopyRemoteUtilsName); var result = ps.Invoke(); if (result.Count == 0) @@ -4816,12 +4815,11 @@ private string ValidateRemotePathAndGetRoot(string path, Runspaces.PSSession ses ps.Commands.Clear(); ps.Streams.ClearStreams(); - ps.AddCommand(psRemoteUtilsName); + ps.AddCommand(CopyFileRemoteUtils.PSCopyRemoteUtilsName); } else { - string remoteScript = CopyFileRemoteUtils.PSValidatePathDefinition; - ps.AddScript(remoteScript); + ps.AddScript(CopyFileRemoteUtils.PSValidatePathDefinition); } ps.AddParameter("pathToValidate", path); @@ -4894,7 +4892,7 @@ private string ValidateRemotePathAndGetRoot(string path, Runspaces.PSSession ses return root; } - private bool isValidSession(PSSession session, CmdletProviderContext context, out PSLanguageMode? languageMode) + private static bool isValidSession(PSSession session, CmdletProviderContext context, out PSLanguageMode? languageMode) { // session == null is validated by the parameter binding if (session.Availability != RunspaceAvailability.Available) diff --git a/src/System.Management.Automation/engine/SessionStateFunctionAPIs.cs b/src/System.Management.Automation/engine/SessionStateFunctionAPIs.cs index 42d3607cadb..adf4c396473 100644 --- a/src/System.Management.Automation/engine/SessionStateFunctionAPIs.cs +++ b/src/System.Management.Automation/engine/SessionStateFunctionAPIs.cs @@ -220,7 +220,7 @@ internal FunctionInfo GetFunction(string name) return GetFunction(name, CommandOrigin.Internal); } - private IEnumerable GetFunctionAliases(IParameterMetadataProvider ipmp) + private static IEnumerable GetFunctionAliases(IParameterMetadataProvider ipmp) { if (ipmp == null || ipmp.Body.ParamBlock == null) yield break; diff --git a/src/System.Management.Automation/engine/SessionStateNavigation.cs b/src/System.Management.Automation/engine/SessionStateNavigation.cs index 4afb9218dd7..f6d1a28eb1c 100644 --- a/src/System.Management.Automation/engine/SessionStateNavigation.cs +++ b/src/System.Management.Automation/engine/SessionStateNavigation.cs @@ -190,7 +190,7 @@ internal string GetParentPath( } } - private string AddQualifier(string path, ProviderInfo provider, string qualifier, bool isProviderQualified, bool isDriveQualified) + private static string AddQualifier(string path, ProviderInfo provider, string qualifier, bool isProviderQualified, bool isDriveQualified) { string result = path; @@ -640,7 +640,7 @@ internal string NormalizeRelativePath( /// /// The character to test. /// True if the character is a path separator. - private bool IsPathSeparator(char c) + private static bool IsPathSeparator(char c) { return c == StringLiterals.DefaultPathSeparator || c == StringLiterals.AlternatePathSeparator; } diff --git a/src/System.Management.Automation/engine/SessionStatePublic.cs b/src/System.Management.Automation/engine/SessionStatePublic.cs index aa8932470ff..ce14d4948dc 100644 --- a/src/System.Management.Automation/engine/SessionStatePublic.cs +++ b/src/System.Management.Automation/engine/SessionStatePublic.cs @@ -88,7 +88,7 @@ public SessionState() /// public DriveManagementIntrinsics Drive { - get { return _drive ?? (_drive = new DriveManagementIntrinsics(_sessionState)); } + get { return _drive ??= new DriveManagementIntrinsics(_sessionState); } } /// @@ -96,7 +96,7 @@ public DriveManagementIntrinsics Drive /// public CmdletProviderManagementIntrinsics Provider { - get { return _provider ?? (_provider = new CmdletProviderManagementIntrinsics(_sessionState)); } + get { return _provider ??= new CmdletProviderManagementIntrinsics(_sessionState); } } /// @@ -104,7 +104,7 @@ public CmdletProviderManagementIntrinsics Provider /// public PathIntrinsics Path { - get { return _path ?? (_path = new PathIntrinsics(_sessionState)); } + get { return _path ??= new PathIntrinsics(_sessionState); } } /// @@ -112,7 +112,7 @@ public PathIntrinsics Path /// public PSVariableIntrinsics PSVariable { - get { return _variable ?? (_variable = new PSVariableIntrinsics(_sessionState)); } + get { return _variable ??= new PSVariableIntrinsics(_sessionState); } } /// @@ -336,6 +336,7 @@ public enum SessionStateEntryVisibility Private = 1 } +#nullable enable internal interface IHasSessionStateEntryVisibility { SessionStateEntryVisibility Visibility { get; set; } diff --git a/src/System.Management.Automation/engine/SessionStateScope.cs b/src/System.Management.Automation/engine/SessionStateScope.cs index db0bd76d55c..6f0c4fbbec3 100644 --- a/src/System.Management.Automation/engine/SessionStateScope.cs +++ b/src/System.Management.Automation/engine/SessionStateScope.cs @@ -111,7 +111,7 @@ internal SessionStateScope ScriptScope /// the provider has already been notified. /// /// - /// If is null. + /// If is null. /// /// /// If a drive of the same name already exists in this scope. @@ -165,7 +165,7 @@ internal void NewDrive(PSDriveInfo newDrive) /// by the provider. /// /// - /// If is null. + /// If is null. /// internal void RemoveDrive(PSDriveInfo drive) { @@ -216,7 +216,7 @@ internal void RemoveAllDrives() /// exists in this scope or null if one does not exist. /// /// - /// If is null. + /// If is null. /// internal PSDriveInfo GetDrive(string name) { @@ -489,7 +489,7 @@ internal PSVariable SetVariable(string name, object value, bool asValue, bool fo } else { - variable = (LocalsTuple != null ? LocalsTuple.TrySetVariable(name, value) : null) ?? new PSVariable(name, value); + variable = (LocalsTuple?.TrySetVariable(name, value)) ?? new PSVariable(name, value); } if (ExecutionContext.HasEverUsedConstrainedLanguage) @@ -1692,7 +1692,7 @@ private static FunctionInfo CreateFunction(string name, ScriptBlock function, Fu // performance degradation, so we use lazy initialization for all of them. private Dictionary GetDrives() { - return _drives ?? (_drives = new Dictionary(StringComparer.OrdinalIgnoreCase)); + return _drives ??= new Dictionary(StringComparer.OrdinalIgnoreCase); } private Dictionary _drives; @@ -1704,8 +1704,7 @@ private Dictionary GetDrives() // performance degradation, so we use lazy initialization for all of them. private Dictionary GetAutomountedDrives() { - return _automountedDrives ?? - (_automountedDrives = new Dictionary(StringComparer.OrdinalIgnoreCase)); + return _automountedDrives ??= new Dictionary(StringComparer.OrdinalIgnoreCase); } private Dictionary _automountedDrives; diff --git a/src/System.Management.Automation/engine/SessionStateVariableAPIs.cs b/src/System.Management.Automation/engine/SessionStateVariableAPIs.cs index f63a0a87c0f..8cc9e4bafa4 100644 --- a/src/System.Management.Automation/engine/SessionStateVariableAPIs.cs +++ b/src/System.Management.Automation/engine/SessionStateVariableAPIs.cs @@ -181,7 +181,7 @@ internal object GetVariableValue(string name, object defaultValue) /// The variable if it was found or null if it was not. /// /// - /// The is first parsed to see if it contains a drive + /// The is first parsed to see if it contains a drive /// specifier or special scope. If a special scope is found ("LOCAL" or "GLOBAL") /// then only that scope is searched for the variable. If any other drive specifier /// is found the lookup goes in the following order. @@ -252,7 +252,7 @@ internal object GetVariableValue( /// The variable if it was found or null if it was not. /// /// - /// The is first parsed to see if it contains a drive + /// The is first parsed to see if it contains a drive /// specifier or special scope. If a special scope is found ("LOCAL" or "GLOBAL") /// then only that scope is searched for the variable. If any other drive specifier /// is found the lookup goes in the following order. @@ -523,7 +523,7 @@ internal object GetVariableValueFromProvider( /// The variable if it was found or null if it was not. /// /// - /// The is first parsed to see if it contains a drive + /// The is first parsed to see if it contains a drive /// specifier or special scope. If a special scope is found ("LOCAL" or "GLOBAL") /// then only that scope is searched for the variable. /// - current scope @@ -575,7 +575,7 @@ internal PSVariable GetVariableItem( /// The variable if it was found or null if it was not. /// /// - /// The is first parsed to see if it contains a drive + /// The is first parsed to see if it contains a drive /// specifier or special scope. If a special scope is found ("LOCAL" or "GLOBAL") /// then only that scope is searched for the variable. /// - current scope @@ -1816,7 +1816,7 @@ internal IDictionary GetVariableTable() return result; } - private void GetScopeVariableTable(SessionStateScope scope, Dictionary result, bool includePrivate) + private static void GetScopeVariableTable(SessionStateScope scope, Dictionary result, bool includePrivate) { foreach (KeyValuePair entry in scope.Variables) { diff --git a/src/System.Management.Automation/engine/ShellVariable.cs b/src/System.Management.Automation/engine/ShellVariable.cs index 1a4bdb359a7..f8a32fca917 100644 --- a/src/System.Management.Automation/engine/ShellVariable.cs +++ b/src/System.Management.Automation/engine/ShellVariable.cs @@ -387,7 +387,7 @@ internal void SetOptions(ScopedItemOptions newOptions, bool force) /// public Collection Attributes { - get { return _attributes ?? (_attributes = new PSVariableAttributeCollection(this)); } + get { return _attributes ??= new PSVariableAttributeCollection(this); } } private PSVariableAttributeCollection _attributes; @@ -840,7 +840,7 @@ public override object Value /// public override string Description { - get { return _description ?? (_description = SessionStateStrings.DollarNullDescription); } + get { return _description ??= SessionStateStrings.DollarNullDescription; } set { /* Do nothing */ } } diff --git a/src/System.Management.Automation/engine/SpecialVariables.cs b/src/System.Management.Automation/engine/SpecialVariables.cs index aa241b6c942..ba757722e91 100644 --- a/src/System.Management.Automation/engine/SpecialVariables.cs +++ b/src/System.Management.Automation/engine/SpecialVariables.cs @@ -32,6 +32,10 @@ internal static class SpecialVariables internal static readonly VariablePath OFSVarPath = new VariablePath(OFS); + internal const string PSStyle = "PSStyle"; + + internal static readonly VariablePath PSStyleVarPath = new VariablePath(PSStyle); + internal const string OutputEncoding = "OutputEncoding"; internal static readonly VariablePath OutputEncodingVarPath = new VariablePath(OutputEncoding); diff --git a/src/System.Management.Automation/engine/Subsystem/SubsystemInfo.cs b/src/System.Management.Automation/engine/Subsystem/SubsystemInfo.cs index b0b31504da4..24adf990d9e 100644 --- a/src/System.Management.Automation/engine/Subsystem/SubsystemInfo.cs +++ b/src/System.Management.Automation/engine/Subsystem/SubsystemInfo.cs @@ -90,6 +90,7 @@ private protected SubsystemInfo(SubsystemKind kind, Type subsystemType) } private protected abstract void AddImplementation(ISubsystem rawImpl); + private protected abstract ISubsystem RemoveImplementation(Guid id); internal void RegisterImplementation(ISubsystem impl) diff --git a/src/System.Management.Automation/engine/Subsystem/SubsystemManager.cs b/src/System.Management.Automation/engine/Subsystem/SubsystemManager.cs index 1e32436e6da..81a27f61279 100644 --- a/src/System.Management.Automation/engine/Subsystem/SubsystemManager.cs +++ b/src/System.Management.Automation/engine/Subsystem/SubsystemManager.cs @@ -217,7 +217,7 @@ private static void RegisterSubsystem(SubsystemInfo subsystemInfo, ISubsystem pr nameof(proxy)); } - if (subsystemInfo.RequiredCmdlets.Any() || subsystemInfo.RequiredFunctions.Any()) + if (subsystemInfo.RequiredCmdlets.Count > 0 || subsystemInfo.RequiredFunctions.Count > 0) { // Process 'proxy.CmdletImplementationAssembly' and 'proxy.FunctionsToDefine' // Functions are added to global scope. @@ -265,7 +265,7 @@ public static void UnregisterSubsystem(SubsystemKind kind, Guid id) private static void UnregisterSubsystem(SubsystemInfo subsystemInfo, Guid id) { - if (subsystemInfo.RequiredCmdlets.Any() || subsystemInfo.RequiredFunctions.Any()) + if (subsystemInfo.RequiredCmdlets.Count > 0 || subsystemInfo.RequiredFunctions.Count > 0) { throw new NotSupportedException("NotSupported yet: unregister subsystem that introduced new cmdlets/functions."); } diff --git a/src/System.Management.Automation/engine/ThirdPartyAdapter.cs b/src/System.Management.Automation/engine/ThirdPartyAdapter.cs index 26a01b1d26d..bde0c0f3483 100644 --- a/src/System.Management.Automation/engine/ThirdPartyAdapter.cs +++ b/src/System.Management.Automation/engine/ThirdPartyAdapter.cs @@ -351,7 +351,7 @@ public virtual Collection GetTypeNameHierarchy(object baseObject) /// /// Returns a property if it's name matches the specified , otherwise null. /// - /// An adapted property if the predicate matches, or null. + /// An adapted property if the predicate matches, or . public virtual PSAdaptedProperty GetFirstPropertyOrDefault(object baseObject, MemberNamePredicate predicate) { foreach (var property in GetProperties(baseObject)) diff --git a/src/System.Management.Automation/engine/TypeMetadata.cs b/src/System.Management.Automation/engine/TypeMetadata.cs index 372497a0261..31a6adeab73 100644 --- a/src/System.Management.Automation/engine/TypeMetadata.cs +++ b/src/System.Management.Automation/engine/TypeMetadata.cs @@ -278,10 +278,10 @@ internal ParameterFlags Flags set { - this.IsMandatory = (ParameterFlags.Mandatory == (value & ParameterFlags.Mandatory)); - this.ValueFromPipeline = (ParameterFlags.ValueFromPipeline == (value & ParameterFlags.ValueFromPipeline)); - this.ValueFromPipelineByPropertyName = (ParameterFlags.ValueFromPipelineByPropertyName == (value & ParameterFlags.ValueFromPipelineByPropertyName)); - this.ValueFromRemainingArguments = (ParameterFlags.ValueFromRemainingArguments == (value & ParameterFlags.ValueFromRemainingArguments)); + this.IsMandatory = ((value & ParameterFlags.Mandatory) == ParameterFlags.Mandatory); + this.ValueFromPipeline = ((value & ParameterFlags.ValueFromPipeline) == ParameterFlags.ValueFromPipeline); + this.ValueFromPipelineByPropertyName = ((value & ParameterFlags.ValueFromPipelineByPropertyName) == ParameterFlags.ValueFromPipelineByPropertyName); + this.ValueFromRemainingArguments = ((value & ParameterFlags.ValueFromRemainingArguments) == ParameterFlags.ValueFromRemainingArguments); } } @@ -895,7 +895,7 @@ internal string GetProxyParameterData(string prefix, string paramNameOverride, b /// /// Attribute's proxy string. /// - private string GetProxyAttributeData(Attribute attrib, string prefix) + private static string GetProxyAttributeData(Attribute attrib, string prefix) { string result; @@ -978,7 +978,7 @@ private string GetProxyAttributeData(Attribute attrib, string prefix) string or = string.Empty; string[] regexOptionEnumValues = Enum.GetNames(typeof(System.Text.RegularExpressions.RegexOptions)); - foreach(string regexOption in regexOptionEnumValues) + foreach (string regexOption in regexOptionEnumValues) { System.Text.RegularExpressions.RegexOptions option = (System.Text.RegularExpressions.RegexOptions) Enum.Parse( typeof(System.Text.RegularExpressions.RegexOptions), @@ -1367,7 +1367,7 @@ private void ConstructCompiledParametersUsingReflection(bool processingDynamicPa } } - private void CheckForReservedParameter(string name) + private static void CheckForReservedParameter(string name) { if (name.Equals("SelectProperty", StringComparison.OrdinalIgnoreCase) || diff --git a/src/System.Management.Automation/engine/TypeTable.cs b/src/System.Management.Automation/engine/TypeTable.cs index 3d40a915f14..0e407d57ac4 100644 --- a/src/System.Management.Automation/engine/TypeTable.cs +++ b/src/System.Management.Automation/engine/TypeTable.cs @@ -277,7 +277,7 @@ private void CheckStandardNote(TypeMemberData member, TypeData typeData, Acti } } - private bool CheckStandardPropertySet(TypeMemberData member, TypeData typeData, Action setter) + private static bool CheckStandardPropertySet(TypeMemberData member, TypeData typeData, Action setter) { var propertySet = member as PropertySetData; if (propertySet != null) @@ -4567,7 +4567,7 @@ internal void Initialize( /// /// Helper method to load content for a module. /// - private string GetModuleContents( + private static string GetModuleContents( string moduleName, string fileToLoad, ConcurrentBag errors, diff --git a/src/System.Management.Automation/engine/TypeTable_Types_Ps1Xml.cs b/src/System.Management.Automation/engine/TypeTable_Types_Ps1Xml.cs index aad2f70246e..5a7133b7cd3 100644 --- a/src/System.Management.Automation/engine/TypeTable_Types_Ps1Xml.cs +++ b/src/System.Management.Automation/engine/TypeTable_Types_Ps1Xml.cs @@ -9227,7 +9227,6 @@ private void Process_Types_Ps1Xml(string filePath, ConcurrentBag errors) #if UNIX #region UnixStat - if (ExperimentalFeature.IsEnabled("PSUnixFileStat")) { typeName = @"System.IO.FileSystemInfo"; diff --git a/src/System.Management.Automation/engine/Utils.cs b/src/System.Management.Automation/engine/Utils.cs index 968e2c2aea6..6a4a863d23c 100644 --- a/src/System.Management.Automation/engine/Utils.cs +++ b/src/System.Management.Automation/engine/Utils.cs @@ -49,7 +49,7 @@ internal static class Utils internal static bool TryCast(BigInteger value, out byte b) { - if (value < byte.MinValue || byte.MaxValue < value) + if (value < byte.MinValue || value > byte.MaxValue) { b = 0; return false; @@ -61,7 +61,7 @@ internal static bool TryCast(BigInteger value, out byte b) internal static bool TryCast(BigInteger value, out sbyte sb) { - if (value < sbyte.MinValue || sbyte.MaxValue < value) + if (value < sbyte.MinValue || value > sbyte.MaxValue) { sb = 0; return false; @@ -73,7 +73,7 @@ internal static bool TryCast(BigInteger value, out sbyte sb) internal static bool TryCast(BigInteger value, out short s) { - if (value < short.MinValue || short.MaxValue < value) + if (value < short.MinValue || value > short.MaxValue) { s = 0; return false; @@ -85,7 +85,7 @@ internal static bool TryCast(BigInteger value, out short s) internal static bool TryCast(BigInteger value, out ushort us) { - if (value < ushort.MinValue || ushort.MaxValue < value) + if (value < ushort.MinValue || value > ushort.MaxValue) { us = 0; return false; @@ -97,7 +97,7 @@ internal static bool TryCast(BigInteger value, out ushort us) internal static bool TryCast(BigInteger value, out int i) { - if (value < int.MinValue || int.MaxValue < value) + if (value < int.MinValue || value > int.MaxValue) { i = 0; return false; @@ -109,7 +109,7 @@ internal static bool TryCast(BigInteger value, out int i) internal static bool TryCast(BigInteger value, out uint u) { - if (value < uint.MinValue || uint.MaxValue < value) + if (value < uint.MinValue || value > uint.MaxValue) { u = 0; return false; @@ -121,7 +121,7 @@ internal static bool TryCast(BigInteger value, out uint u) internal static bool TryCast(BigInteger value, out long l) { - if (value < long.MinValue || long.MaxValue < value) + if (value < long.MinValue || value > long.MaxValue) { l = 0; return false; @@ -133,7 +133,7 @@ internal static bool TryCast(BigInteger value, out long l) internal static bool TryCast(BigInteger value, out ulong ul) { - if (value < ulong.MinValue || ulong.MaxValue < value) + if (value < ulong.MinValue || value > ulong.MaxValue) { ul = 0; return false; @@ -1391,96 +1391,11 @@ internal static bool Succeeded(int hresult) return hresult >= 0; } - // Attempt to determine the existing encoding - internal static Encoding GetEncoding(string path) - { - if (!File.Exists(path)) - { - return ClrFacade.GetDefaultEncoding(); - } - - byte[] initialBytes = new byte[100]; - int bytesRead = 0; - - try - { - using (FileStream stream = System.IO.File.OpenRead(path)) - { - using (BinaryReader reader = new BinaryReader(stream)) - { - bytesRead = reader.Read(initialBytes, 0, 100); - } - } - } - catch (IOException) - { - return ClrFacade.GetDefaultEncoding(); - } - - // Test for four-byte preambles - string preamble = null; - Encoding foundEncoding = ClrFacade.GetDefaultEncoding(); - - if (bytesRead > 3) - { - preamble = string.Join("-", initialBytes[0], initialBytes[1], initialBytes[2], initialBytes[3]); - - if (encodingMap.TryGetValue(preamble, out foundEncoding)) - { - return foundEncoding; - } - } - - // Test for three-byte preambles - if (bytesRead > 2) - { - preamble = string.Join("-", initialBytes[0], initialBytes[1], initialBytes[2]); - if (encodingMap.TryGetValue(preamble, out foundEncoding)) - { - return foundEncoding; - } - } - - // Test for two-byte preambles - if (bytesRead > 1) - { - preamble = string.Join("-", initialBytes[0], initialBytes[1]); - if (encodingMap.TryGetValue(preamble, out foundEncoding)) - { - return foundEncoding; - } - } - - // Check for binary - string initialBytesAsAscii = System.Text.Encoding.ASCII.GetString(initialBytes, 0, bytesRead); - if (initialBytesAsAscii.IndexOfAny(nonPrintableCharacters) >= 0) - { - return Encoding.Unicode; - } - - return utf8NoBom; - } - // BigEndianUTF32 encoding is possible, but requires creation internal static readonly Encoding BigEndianUTF32Encoding = new UTF32Encoding(bigEndian: true, byteOrderMark: true); // [System.Text.Encoding]::GetEncodings() | Where-Object { $_.GetEncoding().GetPreamble() } | // Add-Member ScriptProperty Preamble { $this.GetEncoding().GetPreamble() -join "-" } -PassThru | // Format-Table -Auto - internal static readonly Dictionary encodingMap = - new Dictionary() - { - { "255-254", Encoding.Unicode }, - { "254-255", Encoding.BigEndianUnicode }, - { "255-254-0-0", Encoding.UTF32 }, - { "0-0-254-255", BigEndianUTF32Encoding }, - { "239-187-191", Encoding.UTF8 }, - }; - - internal static readonly char[] nonPrintableCharacters = { - (char) 0, (char) 1, (char) 2, (char) 3, (char) 4, (char) 5, (char) 6, (char) 7, (char) 8, - (char) 11, (char) 12, (char) 14, (char) 15, (char) 16, (char) 17, (char) 18, (char) 19, (char) 20, - (char) 21, (char) 22, (char) 23, (char) 24, (char) 25, (char) 26, (char) 28, (char) 29, (char) 30, - (char) 31, (char) 127, (char) 129, (char) 141, (char) 143, (char) 144, (char) 157 }; internal static readonly UTF8Encoding utf8NoBom = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false); @@ -1872,6 +1787,107 @@ private static bool TryGetCommandInfoList(PowerShell ps, HashSet command return true; } + internal static bool ShouldOutputPlainText(bool isHost, bool? supportsVirtualTerminal) + { + var outputRendering = OutputRendering.Ansi; + + if (ExperimentalFeature.IsEnabled("PSAnsiRendering")) + { + if (supportsVirtualTerminal != false) + { + switch (PSStyle.Instance.OutputRendering) + { + case OutputRendering.Automatic: + outputRendering = OutputRendering.Ansi; + break; + case OutputRendering.Host: + outputRendering = isHost ? OutputRendering.Ansi : OutputRendering.PlainText; + break; + default: + outputRendering = PSStyle.Instance.OutputRendering; + break; + } + } + } + + return outputRendering == OutputRendering.PlainText; + } + + internal static string GetOutputString(string s, bool isHost, bool? supportsVirtualTerminal = null, bool isOutputRedirected = false) + { + if (ExperimentalFeature.IsEnabled("PSAnsiRendering")) + { + var sd = new ValueStringDecorated(s); + + if (sd.IsDecorated) + { + var outputRendering = OutputRendering.Ansi; + if (InternalTestHooks.BypassOutputRedirectionCheck) + { + isOutputRedirected = false; + } + + if (isOutputRedirected || ShouldOutputPlainText(isHost, supportsVirtualTerminal)) + { + outputRendering = OutputRendering.PlainText; + } + + s = sd.ToString(outputRendering); + } + } + + return s; + } + + internal enum FormatStyle + { + Reset, + FormatAccent, + ErrorAccent, + Error, + Warning, + Verbose, + Debug, + } + + internal static string GetFormatStyleString(FormatStyle formatStyle) + { + // redirected console gets plaintext output to preserve existing behavior + if (!InternalTestHooks.BypassOutputRedirectionCheck && + ((PSStyle.Instance.OutputRendering == OutputRendering.PlainText) || + (formatStyle == FormatStyle.Error && Console.IsErrorRedirected) || + (formatStyle != FormatStyle.Error && Console.IsOutputRedirected))) + { + return string.Empty; + } + + if (ExperimentalFeature.IsEnabled("PSAnsiRendering")) + { + PSStyle psstyle = PSStyle.Instance; + switch (formatStyle) + { + case FormatStyle.Reset: + return psstyle.Reset; + case FormatStyle.FormatAccent: + return psstyle.Formatting.FormatAccent; + case FormatStyle.ErrorAccent: + return psstyle.Formatting.ErrorAccent; + case FormatStyle.Error: + return psstyle.Formatting.Error; + case FormatStyle.Warning: + return psstyle.Formatting.Warning; + case FormatStyle.Verbose: + return psstyle.Formatting.Verbose; + case FormatStyle.Debug: + return psstyle.Formatting.Debug; + default: + return string.Empty; + } + } + + return string.Empty; + } + #endregion } @@ -2055,6 +2071,7 @@ public static class InternalTestHooks internal static bool BypassAppLockerPolicyCaching; internal static bool BypassOnlineHelpRetrieval; internal static bool ForcePromptForChoiceDefaultOption; + internal static bool BypassOutputRedirectionCheck; // Stop/Restart/Rename Computer tests internal static bool TestStopComputer; diff --git a/src/System.Management.Automation/engine/debugger/Breakpoint.cs b/src/System.Management.Automation/engine/debugger/Breakpoint.cs index b506ee8a246..ca1c9818206 100644 --- a/src/System.Management.Automation/engine/debugger/Breakpoint.cs +++ b/src/System.Management.Automation/engine/debugger/Breakpoint.cs @@ -434,7 +434,9 @@ public override string ToString() } internal int SequencePointIndex { get; set; } + internal IScriptExtent[] SequencePoints { get; set; } + internal BitArray BreakpointBitArray { get; set; } private class CheckBreakpointInScript : AstVisitor diff --git a/src/System.Management.Automation/engine/debugger/debugger.cs b/src/System.Management.Automation/engine/debugger/debugger.cs index a32276bcc79..30e83c38f90 100644 --- a/src/System.Management.Automation/engine/debugger/debugger.cs +++ b/src/System.Management.Automation/engine/debugger/debugger.cs @@ -50,7 +50,7 @@ public enum DebuggerResumeAction /// Stop executing the script. /// Stop = 4, - }; + } /// /// Arguments for the DebuggerStop event. @@ -112,7 +112,7 @@ public DebuggerStopEventArgs( /// leave pending runspace debug sessions suspended until a debugger is attached. /// internal bool SuspendRemote { get; set; } - }; + } /// /// Kinds of breakpoint updates. @@ -135,7 +135,7 @@ public enum BreakpointUpdateType /// A breakpoint was disabled. /// Disabled = 3 - }; + } /// /// Arguments for the BreakpointUpdated event. @@ -166,7 +166,7 @@ internal BreakpointUpdatedEventArgs(Breakpoint breakpoint, BreakpointUpdateType /// Gets the current breakpoint count. /// public int BreakpointCount { get; } - }; + } #region PSJobStartEventArgs @@ -292,7 +292,7 @@ public enum DebugModes /// PowerShell remote script debugging. /// RemoteScript = 0x4 - }; + } /// /// Defines unhandled breakpoint processing behavior. @@ -1447,7 +1447,7 @@ private List GetVariableBreakpointsToTrigger(string variable return null; var callStackInfo = _callStack.Last(); - var currentScriptFile = (callStackInfo != null) ? callStackInfo.File : null; + var currentScriptFile = callStackInfo?.File; return breakpoints.Values.Where(bp => bp.Trigger(currentScriptFile, read: read)).ToList(); } finally @@ -1578,8 +1578,11 @@ internal void OnSequencePointHit(FunctionContext functionContext) private class CallStackInfo { internal InvocationInfo InvocationInfo { get; set; } + internal string File { get; set; } + internal bool DebuggerStepThrough { get; set; } + internal FunctionContext FunctionContext { get; set; } /// @@ -1589,7 +1592,7 @@ private class CallStackInfo internal bool IsFrameHidden { get; set; } internal bool TopFrameAtBreakpoint { get; set; } - }; + } private struct CallStackList { @@ -1633,7 +1636,7 @@ internal CallStackInfo Last() internal FunctionContext LastFunctionContext() { var last = Last(); - return last != null ? last.FunctionContext : null; + return last?.FunctionContext; } internal bool Any() @@ -2865,7 +2868,7 @@ public override Breakpoint DisableBreakpoint(Breakpoint breakpoint, int? runspac return null; } - private Debugger GetRunspaceDebugger(int runspaceId) + private static Debugger GetRunspaceDebugger(int runspaceId) { if (!Runspace.RunspaceDictionary.TryGetValue(runspaceId, out WeakReference wr)) { @@ -3677,7 +3680,7 @@ private void RemoveFromRunningRunspaceList(Runspace runspace) } // Clean up nested debugger. - NestedRunspaceDebugger nestedDebugger = (runspaceInfo != null) ? runspaceInfo.NestedDebugger : null; + NestedRunspaceDebugger nestedDebugger = runspaceInfo?.NestedDebugger; if (nestedDebugger != null) { nestedDebugger.DebuggerStop -= HandleMonitorRunningRSDebuggerStop; @@ -4138,7 +4141,7 @@ internal void TraceVariableSet(string varName, object value) // because 'ToStringParser' would iterate through the enumerator to get the individual elements, which will // make irreversible changes to the enumerator. bool isValueAnIEnumerator = PSObject.Base(value) is IEnumerator; - string valAsString = isValueAnIEnumerator ? typeof(IEnumerator).Name : PSObject.ToStringParser(_context, value); + string valAsString = isValueAnIEnumerator ? nameof(IEnumerator) : PSObject.ToStringParser(_context, value); int msgLength = 60 - varName.Length; if (valAsString.Length > msgLength) @@ -4195,7 +4198,7 @@ public Guid ParentDebuggerId /// Runspace. /// Runspace type. /// Debugger Id of parent. - public NestedRunspaceDebugger( + protected NestedRunspaceDebugger( Runspace runspace, PSMonitorRunspaceType runspaceType, Guid parentDebuggerId) @@ -4447,14 +4450,14 @@ protected virtual DebuggerCommandResults HandlePromptCommand(PSDataCollection]: [RunspaceName]: PS C:\> - string computerName = (_runspace.ConnectionInfo != null) ? _runspace.ConnectionInfo.ComputerName : null; - string processPartPattern = "{0}[{1}:{2}]:{3}"; + string computerName = _runspace.ConnectionInfo?.ComputerName; + const string processPartPattern = "{0}[{1}:{2}]:{3}"; string processPart = StringUtil.Format(processPartPattern, @"""", DebuggerStrings.NestedRunspaceDebuggerPromptProcessName, @"$($PID)", @""""); - string locationPart = @"""PS $($executionContext.SessionState.Path.CurrentLocation)> """; + const string locationPart = @"""PS $($executionContext.SessionState.Path.CurrentLocation)> """; string promptScript = "'[DBG]: '" + " + " + processPart + " + " + "' [" + CodeGeneration.EscapeSingleQuotedStringContent(_runspace.Name) + "]: '" + " + " + locationPart; // Get the command prompt from the wrapped debugger. @@ -4647,7 +4650,7 @@ private object DrainAndBlockRemoteOutput() return null; } - private void RestoreRemoteOutput(object runningCmd) + private static void RestoreRemoteOutput(object runningCmd) { if (runningCmd == null) { return; } @@ -4905,7 +4908,7 @@ private InvocationInfo CreateInvocationInfoFromParent( return null; } - private string FixUpStatementExtent(int startColNum, string stateExtentText) + private static string FixUpStatementExtent(int startColNum, string stateExtentText) { Text.StringBuilder sb = new Text.StringBuilder(); sb.Append(' ', startColNum); @@ -4944,7 +4947,7 @@ private object DrainAndBlockRemoteOutput() return null; } - private void RestoreRemoteOutput(object runningCmd) + private static void RestoreRemoteOutput(object runningCmd) { if (runningCmd == null) { return; } @@ -5204,7 +5207,7 @@ private DebuggerCommand DoProcessCommand(PSHost host, string command, Invocation /// /// Displays the help text for the debugger commands. /// - private void DisplayHelp(PSHost host, IList output) + private static void DisplayHelp(PSHost host, IList output) { WriteLine(string.Empty, host, output); WriteLine(StringUtil.Format(DebuggerStrings.StepHelp, StepShortcut, StepCommand), host, output); @@ -5332,7 +5335,7 @@ private void DisplayScript(PSHost host, IList output, InvocationInfo i WriteCR(host, output); } - private void WriteLine(string line, PSHost host, IList output) + private static void WriteLine(string line, PSHost host, IList output) { if (host != null) { @@ -5345,7 +5348,7 @@ private void WriteLine(string line, PSHost host, IList output) } } - private void WriteCR(PSHost host, IList output) + private static void WriteCR(PSHost host, IList output) { if (host != null) { @@ -5358,7 +5361,7 @@ private void WriteCR(PSHost host, IList output) } } - private void WriteErrorLine(string error, PSHost host, IList output) + private static void WriteErrorLine(string error, PSHost host, IList output) { if (host != null) { diff --git a/src/System.Management.Automation/engine/hostifaces/AsyncResult.cs b/src/System.Management.Automation/engine/hostifaces/AsyncResult.cs index fa965f4ab59..f1e57e6fe39 100644 --- a/src/System.Management.Automation/engine/hostifaces/AsyncResult.cs +++ b/src/System.Management.Automation/engine/hostifaces/AsyncResult.cs @@ -42,7 +42,7 @@ internal class AsyncResult : IAsyncResult /// internal AsyncResult(Guid ownerId, AsyncCallback callback, object state) { - Dbg.Assert(Guid.Empty != ownerId, "ownerId cannot be empty"); + Dbg.Assert(ownerId != Guid.Empty, "ownerId cannot be empty"); OwnerId = ownerId; Callback = callback; AsyncState = state; diff --git a/src/System.Management.Automation/engine/hostifaces/Command.cs b/src/System.Management.Automation/engine/hostifaces/Command.cs index 4af611980d3..6d8cd526486 100644 --- a/src/System.Management.Automation/engine/hostifaces/Command.cs +++ b/src/System.Management.Automation/engine/hostifaces/Command.cs @@ -422,7 +422,7 @@ public void MergeMyResults(PipelineResultTypes myResult, PipelineResultTypes toR } } - private Pipe GetRedirectionPipe( + private static Pipe GetRedirectionPipe( PipelineResultTypes toType, MshCommandRuntime mcr) { diff --git a/src/System.Management.Automation/engine/hostifaces/Connection.cs b/src/System.Management.Automation/engine/hostifaces/Connection.cs index 29e86c91b9b..5af011adb82 100644 --- a/src/System.Management.Automation/engine/hostifaces/Connection.cs +++ b/src/System.Management.Automation/engine/hostifaces/Connection.cs @@ -226,7 +226,7 @@ public enum PSThreadOptions /// This option is not valid for asynchronous calls /// UseCurrentThread = 3 - }; + } /// /// Defines type which has information about RunspaceState and @@ -952,7 +952,7 @@ internal void UpdateRunspaceAvailability(PipelineState pipelineState, bool raise { RemoteRunspace remoteRunspace = this as RemoteRunspace; RemoteDebugger remoteDebugger = (remoteRunspace != null) ? remoteRunspace.Debugger as RemoteDebugger : null; - Internal.ConnectCommandInfo remoteCommand = (remoteRunspace != null) ? remoteRunspace.RemoteCommand : null; + Internal.ConnectCommandInfo remoteCommand = remoteRunspace?.RemoteCommand; if (((pipelineState == PipelineState.Completed) || (pipelineState == PipelineState.Failed) || ((pipelineState == PipelineState.Stopped) && (this.RunspaceStateInfo.State == RunspaceState.Opened))) && (remoteCommand != null) && (cmdInstanceId != null) && (remoteCommand.CommandId == cmdInstanceId)) @@ -1590,7 +1590,7 @@ public virtual Debugger Debugger get { var context = GetExecutionContext; - return (context != null) ? context.Debugger : null; + return context?.Debugger; } } @@ -1651,6 +1651,7 @@ public virtual void ResetRunspaceState() // Used for pipeline id generation. private long _pipelineIdSeed; + // Generate pipeline id unique to this runspace internal long GeneratePipelineId() { diff --git a/src/System.Management.Automation/engine/hostifaces/ConnectionBase.cs b/src/System.Management.Automation/engine/hostifaces/ConnectionBase.cs index 48129196ad8..99151b7b0d4 100644 --- a/src/System.Management.Automation/engine/hostifaces/ConnectionBase.cs +++ b/src/System.Management.Automation/engine/hostifaces/ConnectionBase.cs @@ -1574,7 +1574,7 @@ internal ProviderIntrinsics InvokeProvider /// internal override SessionStateProxy GetSessionStateProxy() { - return _sessionStateProxy ?? (_sessionStateProxy = new SessionStateProxy(this)); + return _sessionStateProxy ??= new SessionStateProxy(this); } #endregion session state proxy diff --git a/src/System.Management.Automation/engine/hostifaces/FieldDescription.cs b/src/System.Management.Automation/engine/hostifaces/FieldDescription.cs index c9a2c9fe424..75987cc463a 100644 --- a/src/System.Management.Automation/engine/hostifaces/FieldDescription.cs +++ b/src/System.Management.Automation/engine/hostifaces/FieldDescription.cs @@ -291,7 +291,7 @@ public string Name Collection Attributes { - get { return metadata ?? (metadata = new Collection()); } + get { return metadata ??= new Collection(); } } /// diff --git a/src/System.Management.Automation/engine/hostifaces/History.cs b/src/System.Management.Automation/engine/hostifaces/History.cs index ddf533142a8..e1100b97487 100644 --- a/src/System.Management.Automation/engine/hostifaces/History.cs +++ b/src/System.Management.Automation/engine/hostifaces/History.cs @@ -416,7 +416,7 @@ internal HistoryInfo[] GetEntries(long id, long count, SwitchParameter newest) } else { - index = _countEntriesAdded;//SmallestIDinBuffer + index = _countEntriesAdded; //SmallestIDinBuffer for (long i = count - 1; i >= 0;) { @@ -755,11 +755,11 @@ private void IncrementCountOfEntriesInBuffer() /// Get the current history size. /// /// - private int GetHistorySize() + private static int GetHistorySize() { int historySize = 0; var executionContext = LocalPipeline.GetExecutionContextFromTLS(); - object obj = (executionContext != null) ? executionContext.GetVariableValue(SpecialVariables.HistorySizeVarPath) : null; + object obj = executionContext?.GetVariableValue(SpecialVariables.HistorySizeVarPath); if (obj != null) { try @@ -1315,7 +1315,7 @@ private void PopulateIdAndCommandLine() /// in the pipeline. If there are more than one element in pipeline /// (ex A | Invoke-History 2 | B) then we cannot do this replacement. /// - private void ReplaceHistoryString(HistoryInfo entry, LocalRunspace localRunspace) + private static void ReplaceHistoryString(HistoryInfo entry, LocalRunspace localRunspace) { var pipeline = (LocalPipeline)localRunspace.GetCurrentlyRunningPipeline(); if (pipeline.AddToHistory) @@ -1433,6 +1433,7 @@ void ProcessRecord() { break; } + // Read CommandLine property if (!(GetPropertyValue(mshObject, "CommandLine") is string commandLine)) { @@ -1441,109 +1442,32 @@ void ProcessRecord() // Read ExecutionStatus property object pipelineState = GetPropertyValue(mshObject, "ExecutionStatus"); - if (pipelineState == null) - { - break; - } - - PipelineState executionStatus; - if (pipelineState is PipelineState) - { - executionStatus = (PipelineState)pipelineState; - } - else if (pipelineState is PSObject) - { - PSObject serializedPipelineState = pipelineState as PSObject; - object baseObject = serializedPipelineState.BaseObject; - if (baseObject is not int) - { - break; - } - - executionStatus = (PipelineState)baseObject; - if (executionStatus < PipelineState.NotStarted || executionStatus > PipelineState.Failed) - { - break; - } - } - else if (pipelineState is string) - { - try - { - executionStatus = (PipelineState)Enum.Parse(typeof(PipelineState), (string)pipelineState); - } - catch (ArgumentException) - { - break; - } - } - else + if (pipelineState == null || !LanguagePrimitives.TryConvertTo(pipelineState, out PipelineState executionStatus)) { break; } // Read StartExecutionTime property - DateTime startExecutionTime; object temp = GetPropertyValue(mshObject, "StartExecutionTime"); - if (temp == null) - { - break; - } - else if (temp is DateTime) - { - startExecutionTime = (DateTime)temp; - } - else if (temp is string) - { - try - { - startExecutionTime = DateTime.Parse((string)temp, System.Globalization.CultureInfo.CurrentCulture); - } - catch (FormatException) - { - break; - } - } - else + if (temp == null || !LanguagePrimitives.TryConvertTo(temp, out DateTime startExecutionTime)) { break; } // Read EndExecutionTime property - DateTime endExecutionTime; temp = GetPropertyValue(mshObject, "EndExecutionTime"); - if (temp == null) - { - break; - } - else if (temp is DateTime) - { - endExecutionTime = (DateTime)temp; - } - else if (temp is string) - { - try - { - endExecutionTime = DateTime.Parse((string)temp, System.Globalization.CultureInfo.CurrentCulture); - } - catch (FormatException) - { - break; - } - } - else + if (temp == null || !LanguagePrimitives.TryConvertTo(temp, out DateTime endExecutionTime)) { break; } - return new HistoryInfo - ( - 0, - commandLine, - executionStatus, - startExecutionTime, - endExecutionTime - ); + return new HistoryInfo( + pipelineId: 0, + commandLine, + executionStatus, + startExecutionTime, + endExecutionTime + ); } while (false); // If we are here, an error has occured. @@ -1816,7 +1740,7 @@ private void ClearHistoryByID() // confirmation message if all the clearhistory cmdlet is used without any parameters if (!_countParameterSpecified) { - string message = StringUtil.Format(HistoryStrings.ClearHistoryWarning, "Warning");// "The command would clear all the entry(s) from the session history,Are you sure you want to continue ?"; + string message = StringUtil.Format(HistoryStrings.ClearHistoryWarning, "Warning"); // "The command would clear all the entry(s) from the session history,Are you sure you want to continue ?"; if (!ShouldProcess(message)) { return; @@ -1897,10 +1821,10 @@ private void ClearHistoryByCmdLine() /// /// Clears the session history based on the input parameter - /// Id of the entry to be cleared. - /// Count of entries to be cleared. - /// Cmdline string to be cleared. - /// Order of the entries. + /// Id of the entry to be cleared. + /// Count of entries to be cleared. + /// Cmdline string to be cleared. + /// Order of the entries. /// Nothing. /// private void ClearHistoryEntries(long id, int count, string cmdline, SwitchParameter newest) diff --git a/src/System.Management.Automation/engine/hostifaces/InternalHostUserInterface.cs b/src/System.Management.Automation/engine/hostifaces/InternalHostUserInterface.cs index 4dbc7acb855..b30d64d04db 100644 --- a/src/System.Management.Automation/engine/hostifaces/InternalHostUserInterface.cs +++ b/src/System.Management.Automation/engine/hostifaces/InternalHostUserInterface.cs @@ -49,8 +49,7 @@ class InternalHostUserInterface : PSHostUserInterface, IHostUISupportsMultipleCh _internalRawUI.ThrowNotInteractive(); } - private - void + private static void ThrowPromptNotInteractive(string promptMessage) { string message = StringUtil.Format(HostInterfaceExceptionsStrings.HostFunctionPromptNotImplemented, promptMessage); @@ -79,7 +78,7 @@ public override public override bool SupportsVirtualTerminal { - get { return (_externalUI != null) ? _externalUI.SupportsVirtualTerminal : false; } + get { return _externalUI != null && _externalUI.SupportsVirtualTerminal; } } /// @@ -680,12 +679,12 @@ internal static Type GetFieldType(FieldDescription field) internal static bool IsSecuritySensitiveType(string typeName) { - if (typeName.Equals(typeof(PSCredential).Name, StringComparison.OrdinalIgnoreCase)) + if (typeName.Equals(nameof(PSCredential), StringComparison.OrdinalIgnoreCase)) { return true; } - if (typeName.Equals(typeof(SecureString).Name, StringComparison.OrdinalIgnoreCase)) + if (typeName.Equals(nameof(SecureString), StringComparison.OrdinalIgnoreCase)) { return true; } @@ -912,7 +911,7 @@ private Collection EmulatePromptForMultipleChoice(string caption, // Construct the caption + message + list of choices + default choices Text.StringBuilder choicesMessage = new Text.StringBuilder(); - char newLine = '\n'; + const char newLine = '\n'; if (!string.IsNullOrEmpty(caption)) { choicesMessage.Append(caption); @@ -928,7 +927,7 @@ private Collection EmulatePromptForMultipleChoice(string caption, string[,] hotkeysAndPlainLabels = null; HostUIHelperMethods.BuildHotkeysAndPlainLabels(choices, out hotkeysAndPlainLabels); - string choiceTemplate = "[{0}] {1} "; + const string choiceTemplate = "[{0}] {1} "; for (int i = 0; i < hotkeysAndPlainLabels.GetLength(1); ++i) { string choice = diff --git a/src/System.Management.Automation/engine/hostifaces/LocalConnection.cs b/src/System.Management.Automation/engine/hostifaces/LocalConnection.cs index 22a0ab07d05..7f10b75525c 100644 --- a/src/System.Management.Automation/engine/hostifaces/LocalConnection.cs +++ b/src/System.Management.Automation/engine/hostifaces/LocalConnection.cs @@ -941,7 +941,7 @@ private void DoCloseHelper() /// function. If a remote runspace supports disconnect then it will be disconnected /// rather than closed. /// - private void CloseOrDisconnectAllRemoteRunspaces(Func> getRunspaces) + private static void CloseOrDisconnectAllRemoteRunspaces(Func> getRunspaces) { List runspaces = getRunspaces(); if (runspaces.Count == 0) { return; } diff --git a/src/System.Management.Automation/engine/hostifaces/LocalPipeline.cs b/src/System.Management.Automation/engine/hostifaces/LocalPipeline.cs index 61f391dd358..ab430decb50 100644 --- a/src/System.Management.Automation/engine/hostifaces/LocalPipeline.cs +++ b/src/System.Management.Automation/engine/hostifaces/LocalPipeline.cs @@ -249,7 +249,7 @@ protected override void StartPipelineExecution() } default: - Debug.Fail(""); + Debug.Fail(string.Empty); break; } } @@ -1251,7 +1251,7 @@ public void Dispose() } /// - /// Ensure we release the worker thread. + /// Finalizes an instance of the class. /// ~PipelineThread() { diff --git a/src/System.Management.Automation/engine/hostifaces/MshHost.cs b/src/System.Management.Automation/engine/hostifaces/MshHost.cs index 64d8f1170f2..7ee89d14b12 100644 --- a/src/System.Management.Automation/engine/hostifaces/MshHost.cs +++ b/src/System.Management.Automation/engine/hostifaces/MshHost.cs @@ -290,6 +290,7 @@ public virtual bool DebuggerEnabled /// This interface needs to be implemented by PSHost objects that want to support the PushRunspace /// and PopRunspace functionality. /// +#nullable enable public interface IHostSupportsInteractiveSession { /// @@ -317,6 +318,6 @@ public interface IHostSupportsInteractiveSession /// Returns the current runspace associated with this host. /// [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Runspace")] - Runspace Runspace { get; } + Runspace? Runspace { get; } } } diff --git a/src/System.Management.Automation/engine/hostifaces/MshHostUserInterface.cs b/src/System.Management.Automation/engine/hostifaces/MshHostUserInterface.cs index caaaa17a9ac..1e3da98da26 100644 --- a/src/System.Management.Automation/engine/hostifaces/MshHostUserInterface.cs +++ b/src/System.Management.Automation/engine/hostifaces/MshHostUserInterface.cs @@ -619,6 +619,16 @@ internal void TranscribeResult(Runspace sourceRunspace, string resultText) } resultText = resultText.TrimEnd(); + + if (ExperimentalFeature.IsEnabled("PSAnsiRendering")) + { + var text = new ValueStringDecorated(resultText); + if (text.IsDecorated) + { + resultText = text.ToString(OutputRendering.PlainText); + } + } + foreach (TranscriptionOption transcript in TranscriptionData.Transcripts.Prepend(TranscriptionData.SystemTranscript)) { if (transcript != null) @@ -1051,8 +1061,11 @@ internal TranscriptionData() internal List Transcripts { get; } internal TranscriptionOption SystemTranscript { get; set; } + internal string CommandBeingIgnored { get; set; } + internal bool IsHelperCommand { get; set; } + internal string PromptText { get; set; } } @@ -1068,22 +1081,7 @@ internal TranscriptionOption() /// /// The path that this transcript is being logged to. /// - internal string Path - { - get - { - return _path; - } - - set - { - _path = value; - // Get the encoding from the file, or default (UTF8-NoBom) - Encoding = Utils.GetEncoding(value); - } - } - - private string _path; + internal string Path { get; set; } /// /// Any output to log for this transcript. @@ -1101,12 +1099,6 @@ internal string Path /// internal bool IncludeInvocationHeader { get; set; } - /// - /// The encoding of this transcript, so that appending to it - /// can be done correctly. - /// - internal Encoding Encoding { get; private set; } - /// /// Logs buffered content to disk. We use this instead of File.AppendAllLines /// so that we don't need to pay seek penalties all the time, and so that we @@ -1114,6 +1106,13 @@ internal string Path /// internal void FlushContentToDisk() { + static Encoding GetPathEncoding(string path) + { + using StreamReader reader = new StreamReader(path, Utils.utf8NoBom, detectEncodingFromByteOrderMarks: true); + _ = reader.Read(); + return reader.CurrentEncoding; + } + lock (OutputBeingLogged) { if (!_disposed) @@ -1122,11 +1121,13 @@ internal void FlushContentToDisk() { try { + var currentEncoding = GetPathEncoding(this.Path); + // Try to first open the file with permissions that will allow us to read from it // later. _contentWriter = new StreamWriter( new FileStream(this.Path, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.Read), - this.Encoding); + currentEncoding); _contentWriter.BaseStream.Seek(0, SeekOrigin.End); } catch (IOException) @@ -1135,7 +1136,7 @@ internal void FlushContentToDisk() // file permissions. _contentWriter = new StreamWriter( new FileStream(this.Path, FileMode.Append, FileAccess.Write, FileShare.Read), - this.Encoding); + Utils.utf8NoBom); } _contentWriter.AutoFlush = true; diff --git a/src/System.Management.Automation/engine/hostifaces/PSDataCollection.cs b/src/System.Management.Automation/engine/hostifaces/PSDataCollection.cs index 6d690d1206e..1743e6d4678 100644 --- a/src/System.Management.Automation/engine/hostifaces/PSDataCollection.cs +++ b/src/System.Management.Automation/engine/hostifaces/PSDataCollection.cs @@ -1629,7 +1629,7 @@ private static void VerifyValueType(object value) } // Serializes an object, as long as it's not serialized. - private PSObject GetSerializedObject(object value) + private static PSObject GetSerializedObject(object value) { // This is a safe cast, as this method is only called with "SerializeInput" is set, // and that method throws if the collection type is not PSObject. @@ -1654,7 +1654,7 @@ private PSObject GetSerializedObject(object value) } } - private bool SerializationWouldHaveNoEffect(PSObject result) + private static bool SerializationWouldHaveNoEffect(PSObject result) { if (result == null) { diff --git a/src/System.Management.Automation/engine/hostifaces/PowerShell.cs b/src/System.Management.Automation/engine/hostifaces/PowerShell.cs index 11fc4592fb0..a76dbe1c0b1 100644 --- a/src/System.Management.Automation/engine/hostifaces/PowerShell.cs +++ b/src/System.Management.Automation/engine/hostifaces/PowerShell.cs @@ -4602,7 +4602,7 @@ private void CoreInvokeRemoteHelper(PSDataCollection in psAsyncResult.EndInvoke(); EndInvokeAsyncResult = null; - if ((PSInvocationState.Failed == InvocationStateInfo.State) && + if ((InvocationStateInfo.State == PSInvocationState.Failed) && (InvocationStateInfo.Reason != null)) { throw InvocationStateInfo.Reason; @@ -4931,7 +4931,7 @@ private IAsyncResult CoreInvokeAsync(PSDataCollection i /// /// Verifies the settings for ThreadOptions and ApartmentState. /// - private void VerifyThreadSettings(PSInvocationSettings settings, ApartmentState runspaceApartmentState, PSThreadOptions runspaceThreadOptions, bool isRemote) + private static void VerifyThreadSettings(PSInvocationSettings settings, ApartmentState runspaceApartmentState, PSThreadOptions runspaceThreadOptions, bool isRemote) { ApartmentState apartmentState; @@ -5546,7 +5546,7 @@ internal bool ConstructPipelineAndDoWork(Runspace rs, bool performSyncInvoke) LocalPipeline localPipeline = new LocalPipeline( lrs, _shell.Commands.Commands, - ((_settings != null) && (_settings.AddToHistory)) ? true : false, + (_settings != null && _settings.AddToHistory), _shell.IsNested, _inputStream, _outputStream, @@ -5827,7 +5827,7 @@ internal PSObject ToPSObjectForRemoting() return powerShellAsPSObject; } - private List CommandsAsListOfPSObjects(CommandCollection commands, Version psRPVersion) + private static List CommandsAsListOfPSObjects(CommandCollection commands, Version psRPVersion) { List commandsAsListOfPSObjects = new List(commands.Count); foreach (Command command in commands) diff --git a/src/System.Management.Automation/engine/hostifaces/PowerShellProcessInstance.cs b/src/System.Management.Automation/engine/hostifaces/PowerShellProcessInstance.cs index 35029df1e06..3f4dcf40744 100644 --- a/src/System.Management.Automation/engine/hostifaces/PowerShellProcessInstance.cs +++ b/src/System.Management.Automation/engine/hostifaces/PowerShellProcessInstance.cs @@ -185,6 +185,7 @@ public void Dispose() Dispose(true); GC.SuppressFinalize(this); } + /// /// /// diff --git a/src/System.Management.Automation/engine/hostifaces/RunspacePool.cs b/src/System.Management.Automation/engine/hostifaces/RunspacePool.cs index 2a53a8a93ab..5f814e0428b 100644 --- a/src/System.Management.Automation/engine/hostifaces/RunspacePool.cs +++ b/src/System.Management.Automation/engine/hostifaces/RunspacePool.cs @@ -508,7 +508,9 @@ public sealed class RunspacePool : IDisposable private readonly object _syncObject = new object(); private event EventHandler InternalStateChanged = null; + private event EventHandler InternalForwardEvent = null; + private event EventHandler InternalRunspaceCreated = null; #endregion diff --git a/src/System.Management.Automation/engine/interpreter/AddInstruction.cs b/src/System.Management.Automation/engine/interpreter/AddInstruction.cs index 9858167aa74..2f7ada9dcfd 100644 --- a/src/System.Management.Automation/engine/interpreter/AddInstruction.cs +++ b/src/System.Management.Automation/engine/interpreter/AddInstruction.cs @@ -130,14 +130,14 @@ public static Instruction Create(Type type) Debug.Assert(!type.IsEnum); switch (type.GetTypeCode()) { - case TypeCode.Int16: return s_int16 ?? (s_int16 = new AddInt16()); - case TypeCode.Int32: return s_int32 ?? (s_int32 = new AddInt32()); - case TypeCode.Int64: return s_int64 ?? (s_int64 = new AddInt64()); - case TypeCode.UInt16: return s_UInt16 ?? (s_UInt16 = new AddUInt16()); - case TypeCode.UInt32: return s_UInt32 ?? (s_UInt32 = new AddUInt32()); - case TypeCode.UInt64: return s_UInt64 ?? (s_UInt64 = new AddUInt64()); - case TypeCode.Single: return s_single ?? (s_single = new AddSingle()); - case TypeCode.Double: return s_double ?? (s_double = new AddDouble()); + case TypeCode.Int16: return s_int16 ??= new AddInt16(); + case TypeCode.Int32: return s_int32 ??= new AddInt32(); + case TypeCode.Int64: return s_int64 ??= new AddInt64(); + case TypeCode.UInt16: return s_UInt16 ??= new AddUInt16(); + case TypeCode.UInt32: return s_UInt32 ??= new AddUInt32(); + case TypeCode.UInt64: return s_UInt64 ??= new AddUInt64(); + case TypeCode.Single: return s_single ??= new AddSingle(); + case TypeCode.Double: return s_double ??= new AddDouble(); default: throw Assert.Unreachable; @@ -263,14 +263,14 @@ public static Instruction Create(Type type) Debug.Assert(!type.IsEnum); switch (type.GetTypeCode()) { - case TypeCode.Int16: return s_int16 ?? (s_int16 = new AddOvfInt16()); - case TypeCode.Int32: return s_int32 ?? (s_int32 = new AddOvfInt32()); - case TypeCode.Int64: return s_int64 ?? (s_int64 = new AddOvfInt64()); - case TypeCode.UInt16: return s_UInt16 ?? (s_UInt16 = new AddOvfUInt16()); - case TypeCode.UInt32: return s_UInt32 ?? (s_UInt32 = new AddOvfUInt32()); - case TypeCode.UInt64: return s_UInt64 ?? (s_UInt64 = new AddOvfUInt64()); - case TypeCode.Single: return s_single ?? (s_single = new AddOvfSingle()); - case TypeCode.Double: return s_double ?? (s_double = new AddOvfDouble()); + case TypeCode.Int16: return s_int16 ??= new AddOvfInt16(); + case TypeCode.Int32: return s_int32 ??= new AddOvfInt32(); + case TypeCode.Int64: return s_int64 ??= new AddOvfInt64(); + case TypeCode.UInt16: return s_UInt16 ??= new AddOvfUInt16(); + case TypeCode.UInt32: return s_UInt32 ??= new AddOvfUInt32(); + case TypeCode.UInt64: return s_UInt64 ??= new AddOvfUInt64(); + case TypeCode.Single: return s_single ??= new AddOvfSingle(); + case TypeCode.Double: return s_double ??= new AddOvfDouble(); default: throw Assert.Unreachable; diff --git a/src/System.Management.Automation/engine/interpreter/BranchLabel.cs b/src/System.Management.Automation/engine/interpreter/BranchLabel.cs index 919a7b06106..08af974416c 100644 --- a/src/System.Management.Automation/engine/interpreter/BranchLabel.cs +++ b/src/System.Management.Automation/engine/interpreter/BranchLabel.cs @@ -19,7 +19,7 @@ namespace System.Management.Automation.Interpreter { - internal struct RuntimeLabel + internal readonly struct RuntimeLabel { public readonly int Index; public readonly int StackDepth; diff --git a/src/System.Management.Automation/engine/interpreter/ControlFlowInstructions.cs b/src/System.Management.Automation/engine/interpreter/ControlFlowInstructions.cs index 6408a800b97..0fddd203346 100644 --- a/src/System.Management.Automation/engine/interpreter/ControlFlowInstructions.cs +++ b/src/System.Management.Automation/engine/interpreter/ControlFlowInstructions.cs @@ -69,7 +69,7 @@ internal sealed class BranchFalseInstruction : OffsetInstruction public override Instruction[] Cache { - get { return s_cache ?? (s_cache = new Instruction[CacheSize]); } + get { return s_cache ??= new Instruction[CacheSize]; } } internal BranchFalseInstruction() @@ -97,7 +97,7 @@ internal sealed class BranchTrueInstruction : OffsetInstruction public override Instruction[] Cache { - get { return s_cache ?? (s_cache = new Instruction[CacheSize]); } + get { return s_cache ??= new Instruction[CacheSize]; } } internal BranchTrueInstruction() @@ -125,7 +125,7 @@ internal sealed class CoalescingBranchInstruction : OffsetInstruction public override Instruction[] Cache { - get { return s_cache ?? (s_cache = new Instruction[CacheSize]); } + get { return s_cache ??= new Instruction[CacheSize]; } } internal CoalescingBranchInstruction() @@ -204,7 +204,7 @@ internal abstract class IndexedBranchInstruction : Instruction internal readonly int _labelIndex; - public IndexedBranchInstruction(int labelIndex) + protected IndexedBranchInstruction(int labelIndex) { _labelIndex = labelIndex; } diff --git a/src/System.Management.Automation/engine/interpreter/DivInstruction.cs b/src/System.Management.Automation/engine/interpreter/DivInstruction.cs index f6cfb5b265f..11edd140945 100644 --- a/src/System.Management.Automation/engine/interpreter/DivInstruction.cs +++ b/src/System.Management.Automation/engine/interpreter/DivInstruction.cs @@ -130,14 +130,14 @@ public static Instruction Create(Type type) Debug.Assert(!type.IsEnum); switch (type.GetTypeCode()) { - case TypeCode.Int16: return s_int16 ?? (s_int16 = new DivInt16()); - case TypeCode.Int32: return s_int32 ?? (s_int32 = new DivInt32()); - case TypeCode.Int64: return s_int64 ?? (s_int64 = new DivInt64()); - case TypeCode.UInt16: return s_UInt16 ?? (s_UInt16 = new DivUInt16()); - case TypeCode.UInt32: return s_UInt32 ?? (s_UInt32 = new DivUInt32()); - case TypeCode.UInt64: return s_UInt64 ?? (s_UInt64 = new DivUInt64()); - case TypeCode.Single: return s_single ?? (s_single = new DivSingle()); - case TypeCode.Double: return s_double ?? (s_double = new DivDouble()); + case TypeCode.Int16: return s_int16 ??= new DivInt16(); + case TypeCode.Int32: return s_int32 ??= new DivInt32(); + case TypeCode.Int64: return s_int64 ??= new DivInt64(); + case TypeCode.UInt16: return s_UInt16 ??= new DivUInt16(); + case TypeCode.UInt32: return s_UInt32 ??= new DivUInt32(); + case TypeCode.UInt64: return s_UInt64 ??= new DivUInt64(); + case TypeCode.Single: return s_single ??= new DivSingle(); + case TypeCode.Double: return s_double ??= new DivDouble(); default: throw Assert.Unreachable; diff --git a/src/System.Management.Automation/engine/interpreter/EqualInstruction.cs b/src/System.Management.Automation/engine/interpreter/EqualInstruction.cs index 639190e4d46..4db34761ce8 100644 --- a/src/System.Management.Automation/engine/interpreter/EqualInstruction.cs +++ b/src/System.Management.Automation/engine/interpreter/EqualInstruction.cs @@ -154,25 +154,25 @@ public static Instruction Create(Type type) var typeToUse = type.IsEnum ? Enum.GetUnderlyingType(type) : type; switch (typeToUse.GetTypeCode()) { - case TypeCode.Boolean: return s_boolean ?? (s_boolean = new EqualBoolean()); - case TypeCode.SByte: return s_SByte ?? (s_SByte = new EqualSByte()); - case TypeCode.Byte: return s_byte ?? (s_byte = new EqualByte()); - case TypeCode.Char: return s_char ?? (s_char = new EqualChar()); - case TypeCode.Int16: return s_int16 ?? (s_int16 = new EqualInt16()); - case TypeCode.Int32: return s_int32 ?? (s_int32 = new EqualInt32()); - case TypeCode.Int64: return s_int64 ?? (s_int64 = new EqualInt64()); + case TypeCode.Boolean: return s_boolean ??= new EqualBoolean(); + case TypeCode.SByte: return s_SByte ??= new EqualSByte(); + case TypeCode.Byte: return s_byte ??= new EqualByte(); + case TypeCode.Char: return s_char ??= new EqualChar(); + case TypeCode.Int16: return s_int16 ??= new EqualInt16(); + case TypeCode.Int32: return s_int32 ??= new EqualInt32(); + case TypeCode.Int64: return s_int64 ??= new EqualInt64(); - case TypeCode.UInt16: return s_UInt16 ?? (s_UInt16 = new EqualInt16()); - case TypeCode.UInt32: return s_UInt32 ?? (s_UInt32 = new EqualInt32()); - case TypeCode.UInt64: return s_UInt64 ?? (s_UInt64 = new EqualInt64()); + case TypeCode.UInt16: return s_UInt16 ??= new EqualInt16(); + case TypeCode.UInt32: return s_UInt32 ??= new EqualInt32(); + case TypeCode.UInt64: return s_UInt64 ??= new EqualInt64(); - case TypeCode.Single: return s_single ?? (s_single = new EqualSingle()); - case TypeCode.Double: return s_double ?? (s_double = new EqualDouble()); + case TypeCode.Single: return s_single ??= new EqualSingle(); + case TypeCode.Double: return s_double ??= new EqualDouble(); case TypeCode.Object: if (!type.IsValueType) { - return s_reference ?? (s_reference = new EqualReference()); + return s_reference ??= new EqualReference(); } // TODO: Nullable throw new NotImplementedException(); diff --git a/src/System.Management.Automation/engine/interpreter/GreaterThanInstruction.cs b/src/System.Management.Automation/engine/interpreter/GreaterThanInstruction.cs index 9f46323308f..ccd5c3780f7 100644 --- a/src/System.Management.Automation/engine/interpreter/GreaterThanInstruction.cs +++ b/src/System.Management.Automation/engine/interpreter/GreaterThanInstruction.cs @@ -144,17 +144,17 @@ public static Instruction Create(Type type) Debug.Assert(!type.IsEnum); switch (type.GetTypeCode()) { - case TypeCode.SByte: return s_SByte ?? (s_SByte = new GreaterThanSByte()); - case TypeCode.Byte: return s_byte ?? (s_byte = new GreaterThanByte()); - case TypeCode.Char: return s_char ?? (s_char = new GreaterThanChar()); - case TypeCode.Int16: return s_int16 ?? (s_int16 = new GreaterThanInt16()); - case TypeCode.Int32: return s_int32 ?? (s_int32 = new GreaterThanInt32()); - case TypeCode.Int64: return s_int64 ?? (s_int64 = new GreaterThanInt64()); - case TypeCode.UInt16: return s_UInt16 ?? (s_UInt16 = new GreaterThanUInt16()); - case TypeCode.UInt32: return s_UInt32 ?? (s_UInt32 = new GreaterThanUInt32()); - case TypeCode.UInt64: return s_UInt64 ?? (s_UInt64 = new GreaterThanUInt64()); - case TypeCode.Single: return s_single ?? (s_single = new GreaterThanSingle()); - case TypeCode.Double: return s_double ?? (s_double = new GreaterThanDouble()); + case TypeCode.SByte: return s_SByte ??= new GreaterThanSByte(); + case TypeCode.Byte: return s_byte ??= new GreaterThanByte(); + case TypeCode.Char: return s_char ??= new GreaterThanChar(); + case TypeCode.Int16: return s_int16 ??= new GreaterThanInt16(); + case TypeCode.Int32: return s_int32 ??= new GreaterThanInt32(); + case TypeCode.Int64: return s_int64 ??= new GreaterThanInt64(); + case TypeCode.UInt16: return s_UInt16 ??= new GreaterThanUInt16(); + case TypeCode.UInt32: return s_UInt32 ??= new GreaterThanUInt32(); + case TypeCode.UInt64: return s_UInt64 ??= new GreaterThanUInt64(); + case TypeCode.Single: return s_single ??= new GreaterThanSingle(); + case TypeCode.Double: return s_double ??= new GreaterThanDouble(); default: throw Assert.Unreachable; diff --git a/src/System.Management.Automation/engine/interpreter/Instruction.cs b/src/System.Management.Automation/engine/interpreter/Instruction.cs index 0a46fd88dfa..f1d8edaeb87 100644 --- a/src/System.Management.Automation/engine/interpreter/Instruction.cs +++ b/src/System.Management.Automation/engine/interpreter/Instruction.cs @@ -17,10 +17,12 @@ namespace System.Management.Automation.Interpreter { +#nullable enable internal interface IInstructionProvider { void AddInstructions(LightCompiler compiler); } +#nullable restore internal abstract class Instruction { diff --git a/src/System.Management.Automation/engine/interpreter/InstructionFactory.cs b/src/System.Management.Automation/engine/interpreter/InstructionFactory.cs index 286fce26f15..4a707201eb6 100644 --- a/src/System.Management.Automation/engine/interpreter/InstructionFactory.cs +++ b/src/System.Management.Automation/engine/interpreter/InstructionFactory.cs @@ -53,11 +53,17 @@ internal static InstructionFactory GetFactory(Type type) } protected internal abstract Instruction GetArrayItem(); + protected internal abstract Instruction SetArrayItem(); + protected internal abstract Instruction TypeIs(); + protected internal abstract Instruction TypeAs(); + protected internal abstract Instruction DefaultValue(); + protected internal abstract Instruction NewArray(); + protected internal abstract Instruction NewArrayInit(int elementCount); } @@ -81,32 +87,32 @@ private InstructionFactory() { } protected internal override Instruction GetArrayItem() { - return _getArrayItem ?? (_getArrayItem = new GetArrayItemInstruction()); + return _getArrayItem ??= new GetArrayItemInstruction(); } protected internal override Instruction SetArrayItem() { - return _setArrayItem ?? (_setArrayItem = new SetArrayItemInstruction()); + return _setArrayItem ??= new SetArrayItemInstruction(); } protected internal override Instruction TypeIs() { - return _typeIs ?? (_typeIs = new TypeIsInstruction()); + return _typeIs ??= new TypeIsInstruction(); } protected internal override Instruction TypeAs() { - return _typeAs ?? (_typeAs = new TypeAsInstruction()); + return _typeAs ??= new TypeAsInstruction(); } protected internal override Instruction DefaultValue() { - return _defaultValue ?? (_defaultValue = new DefaultValueInstruction()); + return _defaultValue ??= new DefaultValueInstruction(); } protected internal override Instruction NewArray() { - return _newArray ?? (_newArray = new NewArrayInstruction()); + return _newArray ??= new NewArrayInstruction(); } protected internal override Instruction NewArrayInit(int elementCount) diff --git a/src/System.Management.Automation/engine/interpreter/InstructionList.cs b/src/System.Management.Automation/engine/interpreter/InstructionList.cs index 79aca5b48ba..972c3f8635c 100644 --- a/src/System.Management.Automation/engine/interpreter/InstructionList.cs +++ b/src/System.Management.Automation/engine/interpreter/InstructionList.cs @@ -24,7 +24,7 @@ namespace System.Management.Automation.Interpreter { [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1815:OverrideEqualsAndOperatorEqualsOnValueTypes")] [DebuggerTypeProxy(typeof(InstructionArray.DebugView))] - internal struct InstructionArray + internal readonly struct InstructionArray { internal readonly int MaxStackDepth; internal readonly int MaxContinuationDepth; @@ -156,7 +156,7 @@ internal static InstructionView[] GetInstructionViews(IList instruc } [DebuggerDisplay("{GetValue(),nq}", Name = "{GetName(),nq}", Type = "{GetDisplayType(), nq}")] - internal struct InstructionView + internal readonly struct InstructionView { private readonly int _index; private readonly int _stackDepth; @@ -312,7 +312,7 @@ public InstructionArray ToArray() _maxStackDepth, _maxContinuationDepth, _instructions.ToArray(), - (_objects != null) ? _objects.ToArray() : null, + _objects?.ToArray(), BuildRuntimeLabels(), _debugCookies ); @@ -341,11 +341,11 @@ public void EmitLoad(bool value) { if ((bool)value) { - Emit(s_true ?? (s_true = new LoadObjectInstruction(value))); + Emit(s_true ??= new LoadObjectInstruction(value)); } else { - Emit(s_false ?? (s_false = new LoadObjectInstruction(value))); + Emit(s_false ??= new LoadObjectInstruction(value)); } } @@ -353,7 +353,7 @@ public void EmitLoad(object value, Type type) { if (value == null) { - Emit(s_null ?? (s_null = new LoadObjectInstruction(null))); + Emit(s_null ??= new LoadObjectInstruction(null)); return; } @@ -925,7 +925,7 @@ public void EmitLoadField(FieldInfo field) Emit(GetLoadField(field)); } - private Instruction GetLoadField(FieldInfo field) + private static Instruction GetLoadField(FieldInfo field) { lock (s_loadFields) { diff --git a/src/System.Management.Automation/engine/interpreter/InterpretedFrame.cs b/src/System.Management.Automation/engine/interpreter/InterpretedFrame.cs index 431471d0619..4b084ba72a8 100644 --- a/src/System.Management.Automation/engine/interpreter/InterpretedFrame.cs +++ b/src/System.Management.Automation/engine/interpreter/InterpretedFrame.cs @@ -295,12 +295,12 @@ internal void PopPendingContinuation() internal static MethodInfo GotoMethod { - get { return s_goto ?? (s_goto = typeof(InterpretedFrame).GetMethod("Goto")); } + get { return s_goto ??= typeof(InterpretedFrame).GetMethod("Goto"); } } internal static MethodInfo VoidGotoMethod { - get { return s_voidGoto ?? (s_voidGoto = typeof(InterpretedFrame).GetMethod("VoidGoto")); } + get { return s_voidGoto ??= typeof(InterpretedFrame).GetMethod("VoidGoto"); } } public int VoidGoto(int labelIndex) diff --git a/src/System.Management.Automation/engine/interpreter/LessThanInstruction.cs b/src/System.Management.Automation/engine/interpreter/LessThanInstruction.cs index aaf632d0c77..2d6754ff2fd 100644 --- a/src/System.Management.Automation/engine/interpreter/LessThanInstruction.cs +++ b/src/System.Management.Automation/engine/interpreter/LessThanInstruction.cs @@ -144,17 +144,17 @@ public static Instruction Create(Type type) Debug.Assert(!type.IsEnum); switch (type.GetTypeCode()) { - case TypeCode.SByte: return s_SByte ?? (s_SByte = new LessThanSByte()); - case TypeCode.Byte: return s_byte ?? (s_byte = new LessThanByte()); - case TypeCode.Char: return s_char ?? (s_char = new LessThanChar()); - case TypeCode.Int16: return s_int16 ?? (s_int16 = new LessThanInt16()); - case TypeCode.Int32: return s_int32 ?? (s_int32 = new LessThanInt32()); - case TypeCode.Int64: return s_int64 ?? (s_int64 = new LessThanInt64()); - case TypeCode.UInt16: return s_UInt16 ?? (s_UInt16 = new LessThanUInt16()); - case TypeCode.UInt32: return s_UInt32 ?? (s_UInt32 = new LessThanUInt32()); - case TypeCode.UInt64: return s_UInt64 ?? (s_UInt64 = new LessThanUInt64()); - case TypeCode.Single: return s_single ?? (s_single = new LessThanSingle()); - case TypeCode.Double: return s_double ?? (s_double = new LessThanDouble()); + case TypeCode.SByte: return s_SByte ??= new LessThanSByte(); + case TypeCode.Byte: return s_byte ??= new LessThanByte(); + case TypeCode.Char: return s_char ??= new LessThanChar(); + case TypeCode.Int16: return s_int16 ??= new LessThanInt16(); + case TypeCode.Int32: return s_int32 ??= new LessThanInt32(); + case TypeCode.Int64: return s_int64 ??= new LessThanInt64(); + case TypeCode.UInt16: return s_UInt16 ??= new LessThanUInt16(); + case TypeCode.UInt32: return s_UInt32 ??= new LessThanUInt32(); + case TypeCode.UInt64: return s_UInt64 ??= new LessThanUInt64(); + case TypeCode.Single: return s_single ??= new LessThanSingle(); + case TypeCode.Double: return s_double ??= new LessThanDouble(); default: throw Assert.Unreachable; diff --git a/src/System.Management.Automation/engine/interpreter/LightCompiler.cs b/src/System.Management.Automation/engine/interpreter/LightCompiler.cs index 00bdc0d5dd6..85f97ee7d40 100644 --- a/src/System.Management.Automation/engine/interpreter/LightCompiler.cs +++ b/src/System.Management.Automation/engine/interpreter/LightCompiler.cs @@ -243,7 +243,7 @@ public override string ToString() // TODO: [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1815:OverrideEqualsAndOperatorEqualsOnValueTypes")] [Serializable] - internal struct InterpretedFrameInfo + internal readonly struct InterpretedFrameInfo { public readonly string MethodName; @@ -1025,7 +1025,7 @@ private void CompileConditionalExpression(Expression expr, bool asVoid) #region Loops - private void CompileLoopExpression(Expression expr) + private static void CompileLoopExpression(Expression expr) { // var node = (LoopExpression)expr; // var enterLoop = new EnterLoopInstruction(node, _locals, _compilationThreshold, _instructions.Count); @@ -1531,7 +1531,7 @@ private void CompileTryExpression(Expression expr) enterTryInstr.SetTryHandler( new TryCatchFinallyHandler(tryStart, tryEnd, gotoEnd.TargetIndex, startOfFinally.TargetIndex, _instructions.Count, - exHandlers != null ? exHandlers.ToArray() : null)); + exHandlers?.ToArray())); PopLabelBlock(LabelScopeKind.Finally); } else @@ -2004,7 +2004,8 @@ private void CompileNoLabelPush(Expression expr) case ExpressionType.Index: CompileIndexExpression(expr); break; case ExpressionType.Label: CompileLabelExpression(expr); break; case ExpressionType.RuntimeVariables: CompileRuntimeVariablesExpression(expr); break; - case ExpressionType.Loop: CompileLoopExpression(expr); break; + case ExpressionType.Loop: + CompileLoopExpression(expr); break; case ExpressionType.Switch: CompileSwitchExpression(expr); break; case ExpressionType.Throw: CompileThrowUnaryExpression(expr, expr.Type == typeof(void)); break; case ExpressionType.Try: CompileTryExpression(expr); break; diff --git a/src/System.Management.Automation/engine/interpreter/LightDelegateCreator.cs b/src/System.Management.Automation/engine/interpreter/LightDelegateCreator.cs index 5c96d2f6870..0df528b94bb 100644 --- a/src/System.Management.Automation/engine/interpreter/LightDelegateCreator.cs +++ b/src/System.Management.Automation/engine/interpreter/LightDelegateCreator.cs @@ -169,7 +169,7 @@ internal void Compile(object state) // So change the lambda's delegate type to Func<...> or // Action<...> so it can be called from the LightLambda.Run // methods. - LambdaExpression lambda = (_lambda as LambdaExpression);// ?? (LambdaExpression)((LightLambdaExpression)_lambda).Reduce(); + LambdaExpression lambda = (_lambda as LambdaExpression); // ?? (LambdaExpression)((LightLambdaExpression)_lambda).Reduce(); if (_interpreter != null) { _compiledDelegateType = GetFuncOrAction(lambda); diff --git a/src/System.Management.Automation/engine/interpreter/LocalAccess.cs b/src/System.Management.Automation/engine/interpreter/LocalAccess.cs index 7b0711b1930..30596866c0c 100644 --- a/src/System.Management.Automation/engine/interpreter/LocalAccess.cs +++ b/src/System.Management.Automation/engine/interpreter/LocalAccess.cs @@ -23,10 +23,13 @@ namespace System.Management.Automation.Interpreter { + +#nullable enable internal interface IBoxableInstruction { - Instruction BoxIfIndexMatches(int index); + Instruction? BoxIfIndexMatches(int index); } +#nullable restore internal abstract class LocalAccessInstruction : Instruction { diff --git a/src/System.Management.Automation/engine/interpreter/LocalVariables.cs b/src/System.Management.Automation/engine/interpreter/LocalVariables.cs index e093877ce34..aaee75d0234 100644 --- a/src/System.Management.Automation/engine/interpreter/LocalVariables.cs +++ b/src/System.Management.Automation/engine/interpreter/LocalVariables.cs @@ -78,7 +78,7 @@ public override string ToString() } } - internal struct LocalDefinition + internal readonly struct LocalDefinition { private readonly int _index; private readonly ParameterExpression _parameter; diff --git a/src/System.Management.Automation/engine/interpreter/MulInstruction.cs b/src/System.Management.Automation/engine/interpreter/MulInstruction.cs index 486d2ebc751..3b150a7abbd 100644 --- a/src/System.Management.Automation/engine/interpreter/MulInstruction.cs +++ b/src/System.Management.Automation/engine/interpreter/MulInstruction.cs @@ -130,14 +130,14 @@ public static Instruction Create(Type type) Debug.Assert(!type.IsEnum); switch (type.GetTypeCode()) { - case TypeCode.Int16: return s_int16 ?? (s_int16 = new MulInt16()); - case TypeCode.Int32: return s_int32 ?? (s_int32 = new MulInt32()); - case TypeCode.Int64: return s_int64 ?? (s_int64 = new MulInt64()); - case TypeCode.UInt16: return s_UInt16 ?? (s_UInt16 = new MulUInt16()); - case TypeCode.UInt32: return s_UInt32 ?? (s_UInt32 = new MulUInt32()); - case TypeCode.UInt64: return s_UInt64 ?? (s_UInt64 = new MulUInt64()); - case TypeCode.Single: return s_single ?? (s_single = new MulSingle()); - case TypeCode.Double: return s_double ?? (s_double = new MulDouble()); + case TypeCode.Int16: return s_int16 ??= new MulInt16(); + case TypeCode.Int32: return s_int32 ??= new MulInt32(); + case TypeCode.Int64: return s_int64 ??= new MulInt64(); + case TypeCode.UInt16: return s_UInt16 ??= new MulUInt16(); + case TypeCode.UInt32: return s_UInt32 ??= new MulUInt32(); + case TypeCode.UInt64: return s_UInt64 ??= new MulUInt64(); + case TypeCode.Single: return s_single ??= new MulSingle(); + case TypeCode.Double: return s_double ??= new MulDouble(); default: throw Assert.Unreachable; @@ -263,14 +263,14 @@ public static Instruction Create(Type type) Debug.Assert(!type.IsEnum); switch (type.GetTypeCode()) { - case TypeCode.Int16: return s_int16 ?? (s_int16 = new MulOvfInt16()); - case TypeCode.Int32: return s_int32 ?? (s_int32 = new MulOvfInt32()); - case TypeCode.Int64: return s_int64 ?? (s_int64 = new MulOvfInt64()); - case TypeCode.UInt16: return s_UInt16 ?? (s_UInt16 = new MulOvfUInt16()); - case TypeCode.UInt32: return s_UInt32 ?? (s_UInt32 = new MulOvfUInt32()); - case TypeCode.UInt64: return s_UInt64 ?? (s_UInt64 = new MulOvfUInt64()); - case TypeCode.Single: return s_single ?? (s_single = new MulOvfSingle()); - case TypeCode.Double: return s_double ?? (s_double = new MulOvfDouble()); + case TypeCode.Int16: return s_int16 ??= new MulOvfInt16(); + case TypeCode.Int32: return s_int32 ??= new MulOvfInt32(); + case TypeCode.Int64: return s_int64 ??= new MulOvfInt64(); + case TypeCode.UInt16: return s_UInt16 ??= new MulOvfUInt16(); + case TypeCode.UInt32: return s_UInt32 ??= new MulOvfUInt32(); + case TypeCode.UInt64: return s_UInt64 ??= new MulOvfUInt64(); + case TypeCode.Single: return s_single ??= new MulOvfSingle(); + case TypeCode.Double: return s_double ??= new MulOvfDouble(); default: throw Assert.Unreachable; diff --git a/src/System.Management.Automation/engine/interpreter/NotEqualInstruction.cs b/src/System.Management.Automation/engine/interpreter/NotEqualInstruction.cs index 440b5f8d6fa..79df1b9a84b 100644 --- a/src/System.Management.Automation/engine/interpreter/NotEqualInstruction.cs +++ b/src/System.Management.Automation/engine/interpreter/NotEqualInstruction.cs @@ -154,25 +154,25 @@ public static Instruction Create(Type type) var typeToUse = type.IsEnum ? Enum.GetUnderlyingType(type) : type; switch (typeToUse.GetTypeCode()) { - case TypeCode.Boolean: return s_boolean ?? (s_boolean = new NotEqualBoolean()); - case TypeCode.SByte: return s_SByte ?? (s_SByte = new NotEqualSByte()); - case TypeCode.Byte: return s_byte ?? (s_byte = new NotEqualByte()); - case TypeCode.Char: return s_char ?? (s_char = new NotEqualChar()); - case TypeCode.Int16: return s_int16 ?? (s_int16 = new NotEqualInt16()); - case TypeCode.Int32: return s_int32 ?? (s_int32 = new NotEqualInt32()); - case TypeCode.Int64: return s_int64 ?? (s_int64 = new NotEqualInt64()); + case TypeCode.Boolean: return s_boolean ??= new NotEqualBoolean(); + case TypeCode.SByte: return s_SByte ??= new NotEqualSByte(); + case TypeCode.Byte: return s_byte ??= new NotEqualByte(); + case TypeCode.Char: return s_char ??= new NotEqualChar(); + case TypeCode.Int16: return s_int16 ??= new NotEqualInt16(); + case TypeCode.Int32: return s_int32 ??= new NotEqualInt32(); + case TypeCode.Int64: return s_int64 ??= new NotEqualInt64(); - case TypeCode.UInt16: return s_UInt16 ?? (s_UInt16 = new NotEqualInt16()); - case TypeCode.UInt32: return s_UInt32 ?? (s_UInt32 = new NotEqualInt32()); - case TypeCode.UInt64: return s_UInt64 ?? (s_UInt64 = new NotEqualInt64()); + case TypeCode.UInt16: return s_UInt16 ??= new NotEqualInt16(); + case TypeCode.UInt32: return s_UInt32 ??= new NotEqualInt32(); + case TypeCode.UInt64: return s_UInt64 ??= new NotEqualInt64(); - case TypeCode.Single: return s_single ?? (s_single = new NotEqualSingle()); - case TypeCode.Double: return s_double ?? (s_double = new NotEqualDouble()); + case TypeCode.Single: return s_single ??= new NotEqualSingle(); + case TypeCode.Double: return s_double ??= new NotEqualDouble(); case TypeCode.Object: if (!type.IsValueType) { - return s_reference ?? (s_reference = new NotEqualReference()); + return s_reference ??= new NotEqualReference(); } // TODO: Nullable throw new NotImplementedException(); diff --git a/src/System.Management.Automation/engine/interpreter/SubInstruction.cs b/src/System.Management.Automation/engine/interpreter/SubInstruction.cs index c0874d47d89..486cd7f8933 100644 --- a/src/System.Management.Automation/engine/interpreter/SubInstruction.cs +++ b/src/System.Management.Automation/engine/interpreter/SubInstruction.cs @@ -130,14 +130,14 @@ public static Instruction Create(Type type) Debug.Assert(!type.IsEnum); switch (type.GetTypeCode()) { - case TypeCode.Int16: return s_int16 ?? (s_int16 = new SubInt16()); - case TypeCode.Int32: return s_int32 ?? (s_int32 = new SubInt32()); - case TypeCode.Int64: return s_int64 ?? (s_int64 = new SubInt64()); - case TypeCode.UInt16: return s_UInt16 ?? (s_UInt16 = new SubUInt16()); - case TypeCode.UInt32: return s_UInt32 ?? (s_UInt32 = new SubUInt32()); - case TypeCode.UInt64: return s_UInt64 ?? (s_UInt64 = new SubUInt64()); - case TypeCode.Single: return s_single ?? (s_single = new SubSingle()); - case TypeCode.Double: return s_double ?? (s_double = new SubDouble()); + case TypeCode.Int16: return s_int16 ??= new SubInt16(); + case TypeCode.Int32: return s_int32 ??= new SubInt32(); + case TypeCode.Int64: return s_int64 ??= new SubInt64(); + case TypeCode.UInt16: return s_UInt16 ??= new SubUInt16(); + case TypeCode.UInt32: return s_UInt32 ??= new SubUInt32(); + case TypeCode.UInt64: return s_UInt64 ??= new SubUInt64(); + case TypeCode.Single: return s_single ??= new SubSingle(); + case TypeCode.Double: return s_double ??= new SubDouble(); default: throw Assert.Unreachable; @@ -263,14 +263,14 @@ public static Instruction Create(Type type) Debug.Assert(!type.IsEnum); switch (type.GetTypeCode()) { - case TypeCode.Int16: return s_int16 ?? (s_int16 = new SubOvfInt16()); - case TypeCode.Int32: return s_int32 ?? (s_int32 = new SubOvfInt32()); - case TypeCode.Int64: return s_int64 ?? (s_int64 = new SubOvfInt64()); - case TypeCode.UInt16: return s_UInt16 ?? (s_UInt16 = new SubOvfUInt16()); - case TypeCode.UInt32: return s_UInt32 ?? (s_UInt32 = new SubOvfUInt32()); - case TypeCode.UInt64: return s_UInt64 ?? (s_UInt64 = new SubOvfUInt64()); - case TypeCode.Single: return s_single ?? (s_single = new SubOvfSingle()); - case TypeCode.Double: return s_double ?? (s_double = new SubOvfDouble()); + case TypeCode.Int16: return s_int16 ??= new SubOvfInt16(); + case TypeCode.Int32: return s_int32 ??= new SubOvfInt32(); + case TypeCode.Int64: return s_int64 ??= new SubOvfInt64(); + case TypeCode.UInt16: return s_UInt16 ??= new SubOvfUInt16(); + case TypeCode.UInt32: return s_UInt32 ??= new SubOvfUInt32(); + case TypeCode.UInt64: return s_UInt64 ??= new SubOvfUInt64(); + case TypeCode.Single: return s_single ??= new SubOvfSingle(); + case TypeCode.Double: return s_double ??= new SubOvfDouble(); default: throw Assert.Unreachable; diff --git a/src/System.Management.Automation/engine/interpreter/Utilities.cs b/src/System.Management.Automation/engine/interpreter/Utilities.cs index 35c7756ee66..3d4307f1d3a 100644 --- a/src/System.Management.Automation/engine/interpreter/Utilities.cs +++ b/src/System.Management.Automation/engine/interpreter/Utilities.cs @@ -668,7 +668,7 @@ public TValue this[TKey key] } } - private struct KeyInfo + private readonly struct KeyInfo { internal readonly TValue Value; internal readonly LinkedListNode List; diff --git a/src/System.Management.Automation/engine/lang/parserutils.cs b/src/System.Management.Automation/engine/lang/parserutils.cs index f1133733448..52c64400ccd 100644 --- a/src/System.Management.Automation/engine/lang/parserutils.cs +++ b/src/System.Management.Automation/engine/lang/parserutils.cs @@ -378,8 +378,8 @@ internal static object ImplicitOp(object lval, object rval, string op, IScriptEx lval = PSObject.Base(lval); rval = PSObject.Base(rval); - Type lvalType = lval != null ? lval.GetType() : null; - Type rvalType = rval != null ? rval.GetType() : null; + Type lvalType = lval?.GetType(); + Type rvalType = rval?.GetType(); Type opType; if (lvalType == null || (lvalType.IsPrimitive)) { @@ -965,6 +965,7 @@ internal static object ReplaceOperator(ExecutionContext context, IScriptExtent e } } + var replacer = ReplaceOperatorImpl.Create(context, rr, substitute); IEnumerator list = LanguagePrimitives.GetEnumerator(lval); if (list == null) { @@ -978,7 +979,7 @@ internal static object ReplaceOperator(ExecutionContext context, IScriptExtent e lvalString = lval?.ToString() ?? string.Empty; } - return ReplaceOperatorImpl(context, lvalString, rr, substitute); + return replacer.Replace(lvalString); } else { @@ -986,51 +987,84 @@ internal static object ReplaceOperator(ExecutionContext context, IScriptExtent e while (ParserOps.MoveNext(context, errorPosition, list)) { string lvalString = PSObject.ToStringParser(context, ParserOps.Current(errorPosition, list)); - resultList.Add(ReplaceOperatorImpl(context, lvalString, rr, substitute)); + resultList.Add(replacer.Replace(lvalString)); } return resultList.ToArray(); } } - /// - /// ReplaceOperator implementation. - /// Abstracts away conversion of the optional substitute parameter to either a string or a MatchEvaluator delegate - /// and finally returns the result of the final Regex.Replace operation. - /// - /// The execution context in which to evaluate the expression. - /// The input string. - /// A Regex instance. - /// The substitute value. - /// The result of the regex.Replace operation. - private static object ReplaceOperatorImpl(ExecutionContext context, string input, Regex regex, object substitute) + private struct ReplaceOperatorImpl { - switch (substitute) + public static ReplaceOperatorImpl Create(ExecutionContext context, Regex regex, object substitute) + { + return new ReplaceOperatorImpl(context, regex, substitute); + } + + private readonly Regex _regex; + private readonly string _cachedReplacementString; + private readonly MatchEvaluator _cachedMatchEvaluator; + + private ReplaceOperatorImpl( + ExecutionContext context, + Regex regex, + object substitute) { - case string replacementString: - return regex.Replace(input, replacementString); + _regex = regex; + _cachedReplacementString = null; + _cachedMatchEvaluator = null; - case ScriptBlock sb: - MatchEvaluator me = match => - { - var result = sb.DoInvokeReturnAsIs( - useLocalScope: false, /* Use current scope to be consistent with 'ForEach/Where-Object {}' and 'collection.ForEach{}/Where{}' */ - errorHandlingBehavior: ScriptBlock.ErrorHandlingBehavior.WriteToCurrentErrorPipe, - dollarUnder: match, - input: AutomationNull.Value, - scriptThis: AutomationNull.Value, - args: Array.Empty()); - - return PSObject.ToStringParser(context, result); - }; - return regex.Replace(input, me); - - case object val when LanguagePrimitives.TryConvertTo(val, out MatchEvaluator matchEvaluator): - return regex.Replace(input, matchEvaluator); - - default: - string replacement = PSObject.ToStringParser(context, substitute); - return regex.Replace(input, replacement); + switch (substitute) + { + case string replacement: + _cachedReplacementString = replacement; + break; + + case ScriptBlock sb: + _cachedMatchEvaluator = GetMatchEvaluator(context, sb); + break; + + case object val when LanguagePrimitives.TryConvertTo(val, out _cachedMatchEvaluator): + break; + + default: + _cachedReplacementString = PSObject.ToStringParser(context, substitute); + break; + } + } + + // Local helper function to avoid creating an instance of the generated delegate helper class + // every time 'ReplaceOperatorImpl' is invoked. + private static MatchEvaluator GetMatchEvaluator(ExecutionContext context, ScriptBlock sb) + { + return match => + { + var result = sb.DoInvokeReturnAsIs( + useLocalScope: false, /* Use current scope to be consistent with 'ForEach/Where-Object {}' and 'collection.ForEach{}/Where{}' */ + errorHandlingBehavior: ScriptBlock.ErrorHandlingBehavior.WriteToCurrentErrorPipe, + dollarUnder: match, + input: AutomationNull.Value, + scriptThis: AutomationNull.Value, + args: Array.Empty()); + + return PSObject.ToStringParser(context, result); + }; + } + + /// + /// ReplaceOperator implementation. + /// Abstracts away conversion of the optional substitute parameter to either a string or a MatchEvaluator delegate + /// and finally returns the result of the final Regex.Replace operation. + /// + public object Replace(string input) + { + if (_cachedReplacementString is not null) + { + return _regex.Replace(input, _cachedReplacementString); + } + + Dbg.Assert(_cachedMatchEvaluator is not null, "_cachedMatchEvaluator should be not null when code reach here."); + return _regex.Replace(input, _cachedMatchEvaluator); } } diff --git a/src/System.Management.Automation/engine/lang/scriptblock.cs b/src/System.Management.Automation/engine/lang/scriptblock.cs index 6bf326ae81c..765809be306 100644 --- a/src/System.Management.Automation/engine/lang/scriptblock.cs +++ b/src/System.Management.Automation/engine/lang/scriptblock.cs @@ -596,7 +596,7 @@ internal void InvokeAsMemberFunction(object instance, object[] args) /// Get the PSModuleInfo object for the module that defined this /// scriptblock. /// - public PSModuleInfo Module { get => SessionStateInternal != null ? SessionStateInternal.Module : null; } + public PSModuleInfo Module { get => SessionStateInternal?.Module; } /// /// Return the PSToken object for this function definition... @@ -709,7 +709,7 @@ internal SessionState SessionState } } - return SessionStateInternal != null ? SessionStateInternal.PublicSessionState : null; + return SessionStateInternal?.PublicSessionState; } set @@ -1120,14 +1120,14 @@ internal SteppablePipeline(ExecutionContext context, PipelineProcessor pipeline) /// /// Begin execution of a steppable pipeline. This overload doesn't reroute output and error pipes. /// - /// true if you plan to write input into this pipe; false otherwise. + /// if you plan to write input into this pipe; otherwise. public void Begin(bool expectInput) => Begin(expectInput, commandRuntime: (ICommandRuntime)null); /// /// Begin execution of a steppable pipeline, using the command running currently in the specified context to figure /// out how to route the output and errors. /// - /// true if you plan to write input into this pipe; false otherwise. + /// if you plan to write input into this pipe; otherwise. /// Context used to figure out how to route the output and errors. public void Begin(bool expectInput, EngineIntrinsics contextToRedirectTo) { @@ -1138,7 +1138,7 @@ public void Begin(bool expectInput, EngineIntrinsics contextToRedirectTo) ExecutionContext executionContext = contextToRedirectTo.SessionState.Internal.ExecutionContext; CommandProcessorBase commandProcessor = executionContext.CurrentCommandProcessor; - ICommandRuntime crt = commandProcessor == null ? null : commandProcessor.CommandRuntime; + ICommandRuntime crt = commandProcessor?.CommandRuntime; Begin(expectInput, crt); } @@ -1313,14 +1313,6 @@ private void Dispose(bool disposing) _disposed = true; } - /// - /// Finalizer for class SteppablePipeline. - /// - ~SteppablePipeline() - { - Dispose(false); - } - #endregion IDispose } @@ -1447,13 +1439,21 @@ internal ScriptBlockInvocationEventArgs( } internal ScriptBlock ScriptBlock { get; set; } + internal bool UseLocalScope { get; set; } + internal ScriptBlock.ErrorHandlingBehavior ErrorHandlingBehavior { get; set; } + internal object DollarUnder { get; set; } + internal object Input { get; set; } + internal object ScriptThis { get; set; } + internal Pipe OutputPipe { get; set; } + internal InvocationInfo InvocationInfo { get; set; } + internal object[] Args { get; set; } /// diff --git a/src/System.Management.Automation/engine/parser/AstVisitor.cs b/src/System.Management.Automation/engine/parser/AstVisitor.cs index a20ea4a5ce8..5c09ee78dc6 100644 --- a/src/System.Management.Automation/engine/parser/AstVisitor.cs +++ b/src/System.Management.Automation/engine/parser/AstVisitor.cs @@ -201,35 +201,37 @@ public interface ICustomAstVisitor } /// +#nullable enable public interface ICustomAstVisitor2 : ICustomAstVisitor { /// - object VisitTypeDefinition(TypeDefinitionAst typeDefinitionAst) => DefaultVisit(typeDefinitionAst); + object? VisitTypeDefinition(TypeDefinitionAst typeDefinitionAst) => DefaultVisit(typeDefinitionAst); /// - object VisitPropertyMember(PropertyMemberAst propertyMemberAst) => DefaultVisit(propertyMemberAst); + object? VisitPropertyMember(PropertyMemberAst propertyMemberAst) => DefaultVisit(propertyMemberAst); /// - object VisitFunctionMember(FunctionMemberAst functionMemberAst) => DefaultVisit(functionMemberAst); + object? VisitFunctionMember(FunctionMemberAst functionMemberAst) => DefaultVisit(functionMemberAst); /// - object VisitBaseCtorInvokeMemberExpression(BaseCtorInvokeMemberExpressionAst baseCtorInvokeMemberExpressionAst) => DefaultVisit(baseCtorInvokeMemberExpressionAst); + object? VisitBaseCtorInvokeMemberExpression(BaseCtorInvokeMemberExpressionAst baseCtorInvokeMemberExpressionAst) => DefaultVisit(baseCtorInvokeMemberExpressionAst); /// - object VisitUsingStatement(UsingStatementAst usingStatement) => DefaultVisit(usingStatement); + object? VisitUsingStatement(UsingStatementAst usingStatement) => DefaultVisit(usingStatement); /// - object VisitConfigurationDefinition(ConfigurationDefinitionAst configurationDefinitionAst) => DefaultVisit(configurationDefinitionAst); + object? VisitConfigurationDefinition(ConfigurationDefinitionAst configurationDefinitionAst) => DefaultVisit(configurationDefinitionAst); /// - object VisitDynamicKeywordStatement(DynamicKeywordStatementAst dynamicKeywordAst) => DefaultVisit(dynamicKeywordAst); + object? VisitDynamicKeywordStatement(DynamicKeywordStatementAst dynamicKeywordAst) => DefaultVisit(dynamicKeywordAst); /// - object VisitTernaryExpression(TernaryExpressionAst ternaryExpressionAst) => DefaultVisit(ternaryExpressionAst); + object? VisitTernaryExpression(TernaryExpressionAst ternaryExpressionAst) => DefaultVisit(ternaryExpressionAst); /// - object VisitPipelineChain(PipelineChainAst statementChainAst) => DefaultVisit(statementChainAst); + object? VisitPipelineChain(PipelineChainAst statementChainAst) => DefaultVisit(statementChainAst); } +#nullable restore #if DEBUG internal class CheckAllParentsSet : AstVisitor2 @@ -425,7 +427,7 @@ internal static bool Contains(Ast ast, Func predicate, bool searchNes var searcher = new AstSearcher(predicate, stopOnFirst: true, searchNestedScriptBlocks: searchNestedScriptBlocks); ast.InternalVisit(searcher); - return searcher.Results.Any(); + return searcher.Results.Count > 0; } internal static bool IsUsingDollarInput(Ast ast) diff --git a/src/System.Management.Automation/engine/parser/Compiler.cs b/src/System.Management.Automation/engine/parser/Compiler.cs index 8c1acd9c6e2..5d632d55a38 100644 --- a/src/System.Management.Automation/engine/parser/Compiler.cs +++ b/src/System.Management.Automation/engine/parser/Compiler.cs @@ -1166,7 +1166,7 @@ internal static Type GetTypeConstraintForMethodResolution(ExpressionAst expr) expr = ((AttributedExpressionAst)expr).Child; } - return firstConvert == null ? null : firstConvert.Type.TypeName.GetReflectionType(); + return firstConvert?.Type.TypeName.GetReflectionType(); } internal static PSMethodInvocationConstraints CombineTypeConstraintForMethodResolution(Type targetType, Type argType) @@ -2045,7 +2045,7 @@ internal void Compile(CompiledScriptBlockData scriptBlock, bool optimize) } } - private Action CompileTree(Expression> lambda, CompileInterpretChoice compileInterpretChoice) + private static Action CompileTree(Expression> lambda, CompileInterpretChoice compileInterpretChoice) { if (lambda == null) { @@ -2589,7 +2589,7 @@ private Expression> CompileSingleLambda( return Expression.Lambda>(body, funcName, new[] { s_functionContext }); } - private void GenerateTypesAndUsings(ScriptBlockAst rootForDefiningTypesAndUsings, List exprs) + private static void GenerateTypesAndUsings(ScriptBlockAst rootForDefiningTypesAndUsings, List exprs) { // We don't postpone load assemblies, import modules from 'using' to the moment, when enclosed scriptblock is executed. // We do loading, when root of the script is compiled. @@ -6311,7 +6311,7 @@ internal static PSMethodInvocationConstraints GetInvokeMemberConstraints(InvokeM var targetTypeConstraint = GetTypeConstraintForMethodResolution(invokeMemberExpressionAst.Expression); return CombineTypeConstraintForMethodResolution( targetTypeConstraint, - arguments != null ? arguments.Select(Compiler.GetTypeConstraintForMethodResolution).ToArray() : null); + arguments?.Select(Compiler.GetTypeConstraintForMethodResolution).ToArray()); } internal static PSMethodInvocationConstraints GetInvokeMemberConstraints(BaseCtorInvokeMemberExpressionAst invokeMemberExpressionAst) @@ -6330,7 +6330,7 @@ internal static PSMethodInvocationConstraints GetInvokeMemberConstraints(BaseCto return CombineTypeConstraintForMethodResolution( targetTypeConstraint, - arguments != null ? arguments.Select(Compiler.GetTypeConstraintForMethodResolution).ToArray() : null); + arguments?.Select(Compiler.GetTypeConstraintForMethodResolution).ToArray()); } internal Expression InvokeMember( @@ -6343,7 +6343,7 @@ internal Expression InvokeMember( bool nullConditional = false) { var callInfo = new CallInfo(args.Count()); - var classScope = _memberFunctionType != null ? _memberFunctionType.Type : null; + var classScope = _memberFunctionType?.Type; var binder = name.Equals("new", StringComparison.OrdinalIgnoreCase) && @static ? (CallSiteBinder)PSCreateInstanceBinder.Get(callInfo, constraints, publicTypeOnly: true) : PSInvokeMemberBinder.Get(name, callInfo, @static, propertySet, constraints, classScope); @@ -6353,7 +6353,7 @@ internal Expression InvokeMember( return nullConditional ? GetNullConditionalWrappedExpression(target, dynamicExprFromBinder) : dynamicExprFromBinder; } - private Expression InvokeBaseCtorMethod(PSMethodInvocationConstraints constraints, Expression target, IEnumerable args) + private static Expression InvokeBaseCtorMethod(PSMethodInvocationConstraints constraints, Expression target, IEnumerable args) { var callInfo = new CallInfo(args.Count()); var binder = PSInvokeBaseCtorBinder.Get(callInfo, constraints); diff --git a/src/System.Management.Automation/engine/parser/ConstantValues.cs b/src/System.Management.Automation/engine/parser/ConstantValues.cs index ba244e29044..a8ada5f96d5 100644 --- a/src/System.Management.Automation/engine/parser/ConstantValues.cs +++ b/src/System.Management.Automation/engine/parser/ConstantValues.cs @@ -53,7 +53,9 @@ public static bool IsConstant(Ast ast, out object constantValue, bool forAttribu } internal bool CheckingAttributeArgument { get; set; } + internal bool CheckingClassAttributeArguments { get; set; } + internal bool CheckingRequiresArgument { get; set; } public object VisitErrorStatement(ErrorStatementAst errorStatementAst) { return false; } @@ -322,6 +324,7 @@ public object VisitParenExpression(ParenExpressionAst parenExpressionAst) internal class ConstantValueVisitor : ICustomAstVisitor2 { internal bool AttributeArgument { get; set; } + internal bool RequiresArgument { get; set; } [Conditional("DEBUG")] diff --git a/src/System.Management.Automation/engine/parser/PSType.cs b/src/System.Management.Automation/engine/parser/PSType.cs index cffb32e7092..7ffc308369f 100644 --- a/src/System.Management.Automation/engine/parser/PSType.cs +++ b/src/System.Management.Automation/engine/parser/PSType.cs @@ -921,7 +921,7 @@ private void DefineConstructor(IParameterMetadataProvider ipmp, ReadOnlyCollecti (i, n) => ctor.DefineParameter(i, ParameterAttributes.None, n)); } - private string GetMetaDataName(string name, int numberOfParameters) + private static string GetMetaDataName(string name, int numberOfParameters) { int currentId = Interlocked.Increment(ref s_globalCounter); string metaDataName = name + "_" + numberOfParameters + "_" + currentId; diff --git a/src/System.Management.Automation/engine/parser/Parser.cs b/src/System.Management.Automation/engine/parser/Parser.cs index 995418f8061..cac1019ea67 100644 --- a/src/System.Management.Automation/engine/parser/Parser.cs +++ b/src/System.Management.Automation/engine/parser/Parser.cs @@ -1666,7 +1666,7 @@ private ScriptBlockAst ScriptBlockBodyRule(Token lCurly, List statements.Add(predefinedStatementAst); } - IScriptExtent statementListExtent = paramBlockAst != null ? paramBlockAst.Extent : null; + IScriptExtent statementListExtent = paramBlockAst?.Extent; IScriptExtent scriptBlockExtent; while (true) @@ -1707,7 +1707,7 @@ private ScriptBlockAst NamedBlockListRule(Token lCurly, List NamedBlockAst endBlock = null; IScriptExtent startExtent = lCurly != null ? lCurly.Extent - : (paramBlockAst != null) ? paramBlockAst.Extent : null; + : paramBlockAst?.Extent; IScriptExtent endExtent = null; IScriptExtent extent = null; IScriptExtent scriptBlockExtent = null; @@ -2042,7 +2042,7 @@ private StatementAst StatementRule() statement = BlockStatementRule(token); break; case TokenKind.Configuration: - statement = ConfigurationStatementRule(attributes != null ? attributes.OfType() : null, token); + statement = ConfigurationStatementRule(attributes?.OfType(), token); break; case TokenKind.From: case TokenKind.Define: @@ -2848,7 +2848,7 @@ private StatementAst SwitchStatementRule(LabelToken labelToken, Token switchToke } return new SwitchStatementAst(ExtentOf(labelToken ?? switchToken, rCurly), - labelToken != null ? labelToken.LabelText : null, condition, flags, clauses, @default); + labelToken?.LabelText, condition, flags, clauses, @default); } private StatementAst ConfigurationStatementRule(IEnumerable customAttributes, Token configurationToken) @@ -3439,7 +3439,7 @@ private StatementAst ForeachStatementRule(LabelToken labelToken, Token forEachTo } return new ForEachStatementAst(ExtentOf(startOfStatement, body), - labelToken != null ? labelToken.LabelText : null, + labelToken?.LabelText, flags, throttleLimit, variableAst, pipeline, body); } @@ -3552,7 +3552,7 @@ private StatementAst ForStatementRule(LabelToken labelToken, Token forToken) } return new ForStatementAst(ExtentOf(labelToken ?? forToken, body), - labelToken != null ? labelToken.LabelText : null, initializer, condition, iterator, body); + labelToken?.LabelText, initializer, condition, iterator, body); } private StatementAst WhileStatementRule(LabelToken labelToken, Token whileToken) @@ -3634,7 +3634,7 @@ private StatementAst WhileStatementRule(LabelToken labelToken, Token whileToken) } return new WhileStatementAst(ExtentOf(labelToken ?? whileToken, body), - labelToken != null ? labelToken.LabelText : null, condition, body); + labelToken?.LabelText, condition, body); } /// @@ -4129,7 +4129,7 @@ private StatementAst DoWhileStatementRule(LabelToken labelToken, Token doToken) } IScriptExtent extent = ExtentOf(startExtent, rParen); - string label = (labelToken != null) ? labelToken.LabelText : null; + string label = labelToken?.LabelText; if (whileOrUntilToken.Kind == TokenKind.Until) { return new DoUntilStatementAst(extent, label, condition, body); @@ -4283,7 +4283,7 @@ private StatementAst ClassDefinitionRule(List customAttributes ? customAttributes[0].Extent : classToken.Extent; var extent = ExtentOf(startExtent, lastExtent); - var classDefn = new TypeDefinitionAst(extent, name.Value, customAttributes == null ? null : customAttributes.OfType(), members, TypeAttributes.Class, superClassesList); + var classDefn = new TypeDefinitionAst(extent, name.Value, customAttributes?.OfType(), members, TypeAttributes.Class, superClassesList); if (customAttributes != null && customAttributes.OfType().Any()) { if (nestedAsts == null) @@ -4574,7 +4574,7 @@ private MemberAst ClassMemberRule(string className, out List astsOnError) return null; } - private bool TryUseTokenAsSimpleName(Token token) + private static bool TryUseTokenAsSimpleName(Token token) { if (token.Kind == TokenKind.Identifier || token.Kind == TokenKind.DynamicKeyword @@ -4587,7 +4587,7 @@ private bool TryUseTokenAsSimpleName(Token token) return false; } - private void RecordErrorAsts(Ast errAst, ref List astsOnError) + private static void RecordErrorAsts(Ast errAst, ref List astsOnError) { if (errAst == null) { @@ -4602,7 +4602,7 @@ private void RecordErrorAsts(Ast errAst, ref List astsOnError) astsOnError.Add(errAst); } - private void RecordErrorAsts(IEnumerable errAsts, ref List astsOnError) + private static void RecordErrorAsts(IEnumerable errAsts, ref List astsOnError) { if (errAsts == null || !errAsts.Any()) { @@ -4744,7 +4744,7 @@ private StatementAst EnumDefinitionRule(List customAttributes, ? customAttributes[0].Extent : enumToken.Extent; var extent = ExtentOf(startExtent, rCurly); - var enumDefn = new TypeDefinitionAst(extent, name.Value, customAttributes == null ? null : customAttributes.OfType(), members, TypeAttributes.Enum, underlyingTypeConstraint == null ? null : new[] { underlyingTypeConstraint }); + var enumDefn = new TypeDefinitionAst(extent, name.Value, customAttributes?.OfType(), members, TypeAttributes.Enum, underlyingTypeConstraint == null ? null : new[] { underlyingTypeConstraint }); if (customAttributes != null && customAttributes.OfType().Any()) { // No need to report error since there is error reported in method StatementRule @@ -5623,7 +5623,7 @@ private StatementAst DataStatementRule(Token dataToken) IScriptExtent endErrorStatement = null; SkipNewlines(); var dataVariableNameAst = SimpleNameRule(); - string dataVariableName = (dataVariableNameAst != null) ? dataVariableNameAst.Value : null; + string dataVariableName = dataVariableNameAst?.Value; SkipNewlines(); Token supportedCommandToken = PeekToken(); @@ -6629,7 +6629,7 @@ internal Ast CommandRule(bool forDynamicKeyword) return new CommandAst(ExtentOf(firstToken, endExtent), elements, dotSource || ampersand ? firstToken.Kind : TokenKind.Unknown, - redirections != null ? redirections.Where(r => r != null) : null); + redirections?.Where(r => r != null)); } #endregion Pipelines @@ -7939,7 +7939,7 @@ private static void AssertErrorIdCorrespondsToMsgString(string errorId, string e private static object[] arrayOfOneArg { - get { return t_arrayOfOneArg ?? (t_arrayOfOneArg = new object[1]); } + get { return t_arrayOfOneArg ??= new object[1]; } } [ThreadStatic] @@ -7947,7 +7947,7 @@ private static object[] arrayOfOneArg private static object[] arrayOfTwoArgs { - get { return t_arrayOfTwoArgs ?? (t_arrayOfTwoArgs = new object[2]); } + get { return t_arrayOfTwoArgs ??= new object[2]; } } [ThreadStatic] @@ -8013,7 +8013,7 @@ internal void ReportError(ParseError error) SaveError(error); } - private void ReportErrorsAsWarnings(Collection errors) + private static void ReportErrorsAsWarnings(Collection errors) { var executionContext = Runspaces.Runspace.DefaultRunspace.ExecutionContext; if (executionContext != null && executionContext.InternalHost != null && executionContext.InternalHost.UI != null) diff --git a/src/System.Management.Automation/engine/parser/Position.cs b/src/System.Management.Automation/engine/parser/Position.cs index 24ce0d118a2..5e967e432b6 100644 --- a/src/System.Management.Automation/engine/parser/Position.cs +++ b/src/System.Management.Automation/engine/parser/Position.cs @@ -51,12 +51,13 @@ public interface IScriptPosition /// /// Represents the a span of text in a script. /// +#nullable enable public interface IScriptExtent { /// /// The filename the extent includes, or null if the extent is not included in any file. /// - string File { get; } + string? File { get; } /// /// The starting position of the extent. @@ -103,6 +104,7 @@ public interface IScriptExtent /// int EndOffset { get; } } +#nullable restore /// /// A few utility functions for script positions. diff --git a/src/System.Management.Automation/engine/parser/PreOrderVisitor.cs b/src/System.Management.Automation/engine/parser/PreOrderVisitor.cs index 0bf5368fddb..33b2fadec64 100644 --- a/src/System.Management.Automation/engine/parser/PreOrderVisitor.cs +++ b/src/System.Management.Automation/engine/parser/PreOrderVisitor.cs @@ -254,6 +254,7 @@ public abstract class AstVisitor2 : AstVisitor /// Implement this interface when you implement or when /// you want to do something after possibly visiting the children of the ast. /// +#nullable enable public interface IAstPostVisitHandler { /// diff --git a/src/System.Management.Automation/engine/parser/SafeValues.cs b/src/System.Management.Automation/engine/parser/SafeValues.cs index 37320de83d1..a727ae1d287 100644 --- a/src/System.Management.Automation/engine/parser/SafeValues.cs +++ b/src/System.Management.Automation/engine/parser/SafeValues.cs @@ -362,7 +362,8 @@ internal enum SafeValueContext { Default, GetPowerShell, - ModuleAnalysis + ModuleAnalysis, + SkipHashtableSizeCheck, } // future proofing @@ -371,7 +372,8 @@ private GetSafeValueVisitor() { } public static object GetSafeValue(Ast ast, ExecutionContext context, SafeValueContext safeValueContext) { t_context = context; - if (IsSafeValueVisitor.IsAstSafe(ast, safeValueContext)) + + if (safeValueContext == SafeValueContext.SkipHashtableSizeCheck || IsSafeValueVisitor.IsAstSafe(ast, safeValueContext)) { return ast.Accept(new GetSafeValueVisitor()); } @@ -480,7 +482,7 @@ public static object GetSafeValue(Ast ast, ExecutionContext context, SafeValueCo // this can throw, but there really isn't useful information we can add, as the // offending expression will be presented in the case of any failure // - private object GetSingleValueFromTarget(object target, object index) + private static object GetSingleValueFromTarget(object target, object index) { var targetString = target as string; if (targetString != null) @@ -517,7 +519,7 @@ private object GetSingleValueFromTarget(object target, object index) throw new Exception(); } - private object GetIndexedValueFromTarget(object target, object index) + private static object GetIndexedValueFromTarget(object target, object index) { var indexArray = index as object[]; return indexArray != null ? ((object[])indexArray).Select(i => GetSingleValueFromTarget(target, i)).ToArray() : GetSingleValueFromTarget(target, index); diff --git a/src/System.Management.Automation/engine/parser/SemanticChecks.cs b/src/System.Management.Automation/engine/parser/SemanticChecks.cs index ae959f0c58d..3afd10ff6e2 100644 --- a/src/System.Management.Automation/engine/parser/SemanticChecks.cs +++ b/src/System.Management.Automation/engine/parser/SemanticChecks.cs @@ -62,12 +62,12 @@ private bool AnalyzingStaticMember() return fnMemberAst != null ? fnMemberAst.IsStatic : ((PropertyMemberAst)currentMember).IsStatic; } - private bool IsValidAttributeArgument(Ast ast, IsConstantValueVisitor visitor) + private static bool IsValidAttributeArgument(Ast ast, IsConstantValueVisitor visitor) { return (bool)ast.Accept(visitor); } - private (string id, string msg) GetNonConstantAttributeArgErrorExpr(IsConstantValueVisitor visitor) + private static (string id, string msg) GetNonConstantAttributeArgErrorExpr(IsConstantValueVisitor visitor) { if (visitor.CheckingClassAttributeArguments) { @@ -670,7 +670,7 @@ private static string GetLabel(ExpressionAst expr) } var str = expr as StringConstantExpressionAst; - return str != null ? str.Value : null; + return str?.Value; } public override AstVisitAction VisitBreakStatement(BreakStatementAst breakStatementAst) @@ -1183,7 +1183,7 @@ public override AstVisitAction VisitInvokeMemberExpression(InvokeMemberExpressio return AstVisitAction.Continue; } - private void CheckMemberAccess(MemberExpressionAst ast) + private static void CheckMemberAccess(MemberExpressionAst ast) { // If the member access is not constant, it may be considered suspicious if (ast.Member is not ConstantExpressionAst) @@ -1201,7 +1201,7 @@ private void CheckMemberAccess(MemberExpressionAst ast) } // Mark all of the parents of an AST as suspicious - private void MarkAstParentsAsSuspicious(Ast ast) + private static void MarkAstParentsAsSuspicious(Ast ast) { Ast targetAst = ast; var parent = ast; diff --git a/src/System.Management.Automation/engine/parser/SymbolResolver.cs b/src/System.Management.Automation/engine/parser/SymbolResolver.cs index 603ae539cb1..2da38a4ed06 100644 --- a/src/System.Management.Automation/engine/parser/SymbolResolver.cs +++ b/src/System.Management.Automation/engine/parser/SymbolResolver.cs @@ -30,6 +30,7 @@ public TypeLookupResult(TypeDefinitionAst type = null) } public TypeDefinitionAst Type { get; set; } + public List ExternalNamespaces { get; set; } public bool IsAmbiguous() diff --git a/src/System.Management.Automation/engine/parser/TypeInferenceVisitor.cs b/src/System.Management.Automation/engine/parser/TypeInferenceVisitor.cs index 2543c5273d0..45f278b6b5a 100644 --- a/src/System.Management.Automation/engine/parser/TypeInferenceVisitor.cs +++ b/src/System.Management.Automation/engine/parser/TypeInferenceVisitor.cs @@ -132,7 +132,7 @@ public TypeInferenceContext() : this(PowerShell.Create(RunspaceMode.CurrentRunsp } /// - /// Initializes a new instance of the class. + /// Initializes a new instance of the class. /// The powerShell instance passed need to have a non null Runspace. /// /// The instance of powershell to use for expression evaluation needed for type inference. @@ -1217,7 +1217,7 @@ bool IsInPropertyArgument(object o) } var previousPipelineElement = GetPreviousPipelineCommand(commandAst); - var typeName = "Microsoft.PowerShell.Commands.GroupInfo"; + const string typeName = "Microsoft.PowerShell.Commands.GroupInfo"; var members = new List(); foreach (var prevType in InferTypes(previousPipelineElement)) { @@ -1699,7 +1699,7 @@ private bool TryGetTypeFromMember( return false; } - private void AddTypesFromMethodCacheEntry( + private static void AddTypesFromMethodCacheEntry( DotNetAdapter.MethodCacheEntry methodCacheEntry, List result, bool isInvokeMemberExpressionAst) @@ -2021,7 +2021,7 @@ private void InferTypeFrom(VariableExpressionAst variableExpressionAst, List /// The inferred types all the items in the array. /// The inferred strongly typed array type. - private PSTypeName GetArrayType(IEnumerable inferredTypes) + private static PSTypeName GetArrayType(IEnumerable inferredTypes) { PSTypeName foundType = null; foreach (PSTypeName inferredType in inferredTypes) @@ -2077,7 +2077,7 @@ private PSTypeName GetArrayType(IEnumerable inferredTypes) /// /// The type to infer enumerated item type from. /// The inferred enumerated item type. - private Type GetMostSpecificEnumeratedItemType(Type enumerableType) + private static Type GetMostSpecificEnumeratedItemType(Type enumerableType) { if (enumerableType.IsArray) { @@ -2141,19 +2141,19 @@ private Type GetMostSpecificEnumeratedItemType(Type enumerableType) /// The interface to test. /// /// A reference to a value indicating whether a non-generic enumerable type has been - /// seen. If is a non-generic enumerable type this - /// value will be set to . + /// seen. If is a non-generic enumerable type this + /// value will be set to . /// /// - /// A reference to a value indicating whether has been - /// seen. If is a this - /// value will be set to . + /// A reference to a value indicating whether has been + /// seen. If is a this + /// value will be set to . /// /// - /// The value of if it can be used to infer a specific - /// enumerated type, otherwise . + /// The value of if it can be used to infer a specific + /// enumerated type, otherwise . /// - private Type GetGenericCollectionLikeInterface( + private static Type GetGenericCollectionLikeInterface( Type interfaceType, ref bool hasSeenNonGeneric, ref bool hasSeenDictionaryEnumerator) @@ -2250,14 +2250,14 @@ private IEnumerable InferTypeFrom(IndexExpressionAst indexExpression } /// - /// Infers the types as if they were enumerated. For example, a - /// of type would be returned as . + /// Infers the types as if they were enumerated. For example, a + /// of type would be returned as . /// /// /// The potentially enumerable types to infer enumerated type from. /// /// The enumerated item types. - private IEnumerable GetInferredEnumeratedTypes(IEnumerable enumerableTypes) + private static IEnumerable GetInferredEnumeratedTypes(IEnumerable enumerableTypes) { foreach (PSTypeName maybeEnumerableType in enumerableTypes) { diff --git a/src/System.Management.Automation/engine/parser/TypeResolver.cs b/src/System.Management.Automation/engine/parser/TypeResolver.cs index b5e6ae733a1..85325b61305 100644 --- a/src/System.Management.Automation/engine/parser/TypeResolver.cs +++ b/src/System.Management.Automation/engine/parser/TypeResolver.cs @@ -246,7 +246,7 @@ private static Type CallResolveTypeNameWorkerHelper(TypeName typeName, try { exception = null; - var currentScope = context != null ? context.EngineSessionState.CurrentScope : null; + var currentScope = context?.EngineSessionState.CurrentScope; Type result = ResolveTypeNameWorker(typeName, currentScope, typeResolutionState.assemblies, t_searchedAssemblies, typeResolutionState, /*onlySearchInGivenAssemblies*/ false, /* reportAmbiguousException */ true, out exception); if (exception == null && result == null) diff --git a/src/System.Management.Automation/engine/parser/VariableAnalysis.cs b/src/System.Management.Automation/engine/parser/VariableAnalysis.cs index 092a9fc9a49..4cc8e98a2c0 100644 --- a/src/System.Management.Automation/engine/parser/VariableAnalysis.cs +++ b/src/System.Management.Automation/engine/parser/VariableAnalysis.cs @@ -25,12 +25,19 @@ internal VariableAnalysisDetails() } public int BitIndex { get; set; } + public int LocalTupleIndex { get; set; } + public Type Type { get; set; } + public string Name { get; set; } + public bool Automatic { get; set; } + public bool PreferenceVariable { get; set; } + public bool Assigned { get; set; } + public List AssociatedAsts { get; } } diff --git a/src/System.Management.Automation/engine/parser/ast.cs b/src/System.Management.Automation/engine/parser/ast.cs index b654ab0ccdc..156e0365b4a 100644 --- a/src/System.Management.Automation/engine/parser/ast.cs +++ b/src/System.Management.Automation/engine/parser/ast.cs @@ -29,11 +29,15 @@ namespace System.Management.Automation.Language using System.Runtime.CompilerServices; using System.Reflection.Emit; +#nullable enable + internal interface ISupportsAssignment { IAssignableValue GetAssignableValue(); } +#nullable restore + internal interface IAssignableValue { /// @@ -53,8 +57,11 @@ internal interface IAssignableValue internal interface IParameterMetadataProvider { bool HasAnyScriptBlockAttributes(); + RuntimeDefinedParameterDictionary GetParameterMetadata(bool automaticPositions, ref bool usesCmdletBinding); + IEnumerable GetScriptBlockAttributes(); + IEnumerable GetExperimentalAttributes(); bool UsesCmdletBinding(); @@ -195,6 +202,19 @@ public override string ToString() /// If is deemed unsafe /// public object SafeGetValue() + { + return SafeGetValue(skipHashtableSizeCheck: false); + } + + /// + /// Constructs the resultant object from the AST and returns it if it is safe. + /// + /// Set to skip hashtable limit validation. + /// The object represented by the AST as a safe object. + /// + /// If is deemed unsafe. + /// + public object SafeGetValue(bool skipHashtableSizeCheck) { try { @@ -204,7 +224,7 @@ public object SafeGetValue() context = System.Management.Automation.Runspaces.Runspace.DefaultRunspace.ExecutionContext; } - return GetSafeValueVisitor.GetSafeValue(this, context, GetSafeValueVisitor.SafeValueContext.Default); + return GetSafeValueVisitor.GetSafeValue(this, context, skipHashtableSizeCheck ? GetSafeValueVisitor.SafeValueContext.SkipHashtableSizeCheck : GetSafeValueVisitor.SafeValueContext.Default); } catch { @@ -286,6 +306,7 @@ internal void ClearParent() } internal abstract object Accept(ICustomAstVisitor visitor); + internal abstract AstVisitAction InternalVisit(AstVisitor visitor); internal static readonly PSTypeName[] EmptyPSTypeNameArray = Array.Empty(); @@ -770,6 +791,7 @@ public class ScriptBlockAst : Ast, IParameterMetadataProvider Utils.EmptyReadOnlyCollection(); internal bool HadErrors { get; set; } + internal bool IsConfiguration { get; private set; } internal bool PostParseChecksPerformed { get; set; } @@ -1749,7 +1771,7 @@ public class NamedBlockAst : Ast /// /// /// If is not one of the valid kinds for a named block, - /// or if is true and is neither + /// or if is and is neither /// nor . /// public NamedBlockAst(IScriptExtent extent, TokenKind blockName, StatementBlockAst statementBlock, bool unnamed) @@ -2656,7 +2678,7 @@ public override Ast Copy() internal override object Accept(ICustomAstVisitor visitor) { var visitor2 = visitor as ICustomAstVisitor2; - return visitor2 != null ? visitor2.VisitTypeDefinition(this) : null; + return visitor2?.VisitTypeDefinition(this); } internal override AstVisitAction InternalVisit(AstVisitor visitor) @@ -2904,7 +2926,7 @@ public override Ast Copy() internal override object Accept(ICustomAstVisitor visitor) { var visitor2 = visitor as ICustomAstVisitor2; - return visitor2 != null ? visitor2.VisitUsingStatement(this) : null; + return visitor2?.VisitUsingStatement(this); } internal override AstVisitAction InternalVisit(AstVisitor visitor) @@ -3132,7 +3154,7 @@ internal override string GetTooltip() internal override object Accept(ICustomAstVisitor visitor) { var visitor2 = visitor as ICustomAstVisitor2; - return visitor2 != null ? visitor2.VisitPropertyMember(this) : null; + return visitor2?.VisitPropertyMember(this); } internal override AstVisitAction InternalVisit(AstVisitor visitor) @@ -3352,7 +3374,7 @@ internal override string GetTooltip() internal override object Accept(ICustomAstVisitor visitor) { var visitor2 = visitor as ICustomAstVisitor2; - return visitor2 != null ? visitor2.VisitFunctionMember(this) : null; + return visitor2?.VisitFunctionMember(this); } internal override AstVisitAction InternalVisit(AstVisitor visitor) @@ -3444,7 +3466,7 @@ internal bool IsReturnTypeVoid() if (ReturnType == null) return true; var typeName = ReturnType.TypeName as TypeName; - return typeName == null ? false : typeName.IsType(typeof(void)); + return typeName != null && typeName.IsType(typeof(void)); } internal Type GetReturnType() @@ -3829,7 +3851,7 @@ IEnumerable IParameterMetadataProvider.GetExperimentalAtt ReadOnlyCollection IParameterMetadataProvider.Parameters { - get { return Parameters ?? (Body.ParamBlock != null ? Body.ParamBlock.Parameters : null); } + get { return Parameters ?? (Body.ParamBlock?.Parameters); } } PowerShell IParameterMetadataProvider.GetPowerShell(ExecutionContext context, Dictionary variables, bool isTrustedInput, @@ -5879,7 +5901,7 @@ public CommandAst(IScriptExtent extent, public string GetCommandName() { var name = CommandElements[0] as StringConstantExpressionAst; - return name != null ? name.Value : null; + return name?.Value; } /// @@ -6422,7 +6444,7 @@ public override Ast Copy() { LCurlyToken = this.LCurlyToken, ConfigurationToken = this.ConfigurationToken, - CustomAttributes = this.CustomAttributes == null ? null : this.CustomAttributes.Select(e => (AttributeAst)e.Copy()) + CustomAttributes = this.CustomAttributes?.Select(e => (AttributeAst)e.Copy()) }; } @@ -6431,7 +6453,7 @@ public override Ast Copy() internal override object Accept(ICustomAstVisitor visitor) { var visitor2 = visitor as ICustomAstVisitor2; - return visitor2 != null ? visitor2.VisitConfigurationDefinition(this) : null; + return visitor2?.VisitConfigurationDefinition(this); } internal override AstVisitAction InternalVisit(AstVisitor visitor) @@ -6463,7 +6485,9 @@ internal override AstVisitAction InternalVisit(AstVisitor visitor) #region Internal methods/properties internal Token LCurlyToken { get; set; } + internal Token ConfigurationToken { get; set; } + internal IEnumerable CustomAttributes { get; set; } /// @@ -6521,7 +6545,7 @@ internal PipelineAst GenerateSetItemPipelineAst() cea.Add(new CommandParameterAst(PositionUtilities.EmptyExtent, "ResourceModuleTuplesToImport", new ConstantExpressionAst(PositionUtilities.EmptyExtent, resourceModulePairsToImport), PositionUtilities.EmptyExtent)); var scriptBlockBody = new ScriptBlockAst(Body.Extent, - CustomAttributes == null ? null : CustomAttributes.Select(att => (AttributeAst)att.Copy()).ToList(), + CustomAttributes?.Select(att => (AttributeAst)att.Copy()).ToList(), null, new StatementBlockAst(Body.Extent, resourceBody, null), false, false); @@ -6580,7 +6604,7 @@ internal PipelineAst GenerateSetItemPipelineAst() var statmentBlockAst = new StatementBlockAst(this.Extent, funcStatements, null); var funcBody = new ScriptBlockAst(Body.Extent, - CustomAttributes == null ? null : CustomAttributes.Select(att => (AttributeAst)att.Copy()).ToList(), + CustomAttributes?.Select(att => (AttributeAst)att.Copy()).ToList(), paramBlockAst, statmentBlockAst, false, true); var funcBodyExp = new ScriptBlockExpressionAst(this.Extent, funcBody); @@ -6898,7 +6922,7 @@ public override Ast Copy() internal override object Accept(ICustomAstVisitor visitor) { var visitor2 = visitor as ICustomAstVisitor2; - return visitor2 != null ? visitor2.VisitDynamicKeywordStatement(this) : null; + return visitor2?.VisitDynamicKeywordStatement(this); } internal override AstVisitAction InternalVisit(AstVisitor visitor) @@ -6945,10 +6969,15 @@ internal DynamicKeyword Keyword private DynamicKeyword _keyword; internal Token LCurly { get; set; } + internal Token FunctionName { get; set; } + internal ExpressionAst InstanceName { get; set; } + internal ExpressionAst OriginalInstanceName { get; set; } + internal ExpressionAst BodyExpression { get; set; } + internal string ElementName { get; set; } private PipelineAst _commandCallPipelineAst; @@ -8103,7 +8132,7 @@ internal override AstVisitAction InternalVisit(AstVisitor visitor) internal override object Accept(ICustomAstVisitor visitor) { var visitor2 = visitor as ICustomAstVisitor2; - return visitor2 != null ? visitor2.VisitBaseCtorInvokeMemberExpression(this) : null; + return visitor2?.VisitBaseCtorInvokeMemberExpression(this); } } @@ -9233,6 +9262,7 @@ internal override AstVisitAction InternalVisit(AstVisitor visitor) internal int TupleIndex { get; set; } = VariableAnalysis.Unanalyzed; internal bool Automatic { get; set; } + internal bool Assigned { get; set; } IAssignableValue ISupportsAssignment.GetAssignableValue() diff --git a/src/System.Management.Automation/engine/parser/tokenizer.cs b/src/System.Management.Automation/engine/parser/tokenizer.cs index 3d66362745c..5ab09c0a40f 100644 --- a/src/System.Management.Automation/engine/parser/tokenizer.cs +++ b/src/System.Management.Automation/engine/parser/tokenizer.cs @@ -41,7 +41,7 @@ public enum DynamicKeywordNameMode /// Name may be optionally present, expression or bare word. /// OptionalName = 4, - }; + } /// /// Defines the body mode for a dynamic keyword. It can be a scriptblock, hashtable or command which means no body. @@ -77,8 +77,7 @@ private static Dictionary DynamicKeywords { get { - return t_dynamicKeywords ?? - (t_dynamicKeywords = new Dictionary(StringComparer.OrdinalIgnoreCase)); + return t_dynamicKeywords ??= new Dictionary(StringComparer.OrdinalIgnoreCase); } } @@ -92,8 +91,7 @@ private static Stack> DynamicKeywordsStack { get { - return t_dynamicKeywordsStack ?? - (t_dynamicKeywordsStack = new Stack>()); + return t_dynamicKeywordsStack ??= new Stack>(); } } @@ -320,8 +318,7 @@ public Dictionary Properties { get { - return _properties ?? - (_properties = new Dictionary(StringComparer.OrdinalIgnoreCase)); + return _properties ??= new Dictionary(StringComparer.OrdinalIgnoreCase); } } @@ -334,8 +331,7 @@ public Dictionary Parameters { get { - return _parameters ?? - (_parameters = new Dictionary(StringComparer.OrdinalIgnoreCase)); + return _parameters ??= new Dictionary(StringComparer.OrdinalIgnoreCase); } } @@ -426,7 +422,7 @@ public class DynamicKeywordProperty /// public List Attributes { - get { return _attributes ?? (_attributes = new List()); } + get { return _attributes ??= new List(); } } private List _attributes; @@ -436,7 +432,7 @@ public List Attributes /// public List Values { - get { return _values ?? (_values = new List()); } + get { return _values ??= new List(); } } private List _values; @@ -446,7 +442,7 @@ public List Values /// public Dictionary ValueMap { - get { return _valueMap ?? (_valueMap = new Dictionary(StringComparer.OrdinalIgnoreCase)); } + get { return _valueMap ??= new Dictionary(StringComparer.OrdinalIgnoreCase); } } private Dictionary _valueMap; @@ -721,6 +717,7 @@ internal Tokenizer(Parser parser) } internal TokenizerMode Mode { get; set; } + internal bool AllowSignedNumbers { get; set; } // TODO: use auto-properties when making 'ternary operator' an official feature. @@ -733,8 +730,11 @@ internal bool ForceEndNumberOnTernaryOpChars } internal bool WantSimpleName { get; set; } + internal bool InWorkflowContext { get; set; } + internal List TokenList { get; set; } + internal Token FirstToken { get; private set; } internal Token LastToken { get; private set; } @@ -826,7 +826,7 @@ internal void FinishNestedScan(TokenizerState ts) private char GetChar() { - Diagnostics.Assert(0 <= _currentIndex, "GetChar reading before start of input."); + Diagnostics.Assert(_currentIndex >= 0, "GetChar reading before start of input."); Diagnostics.Assert(_currentIndex <= _script.Length + 1, "GetChar reading after end of input."); // Increment _currentIndex, even if it goes over the Length so callers can call UngetChar to unget EOF. @@ -848,7 +848,7 @@ private void UngetChar() private char PeekChar() { - Diagnostics.Assert(0 <= _currentIndex && _currentIndex <= _script.Length, "PeekChar out of range."); + Diagnostics.Assert(_currentIndex >= 0 && _currentIndex <= _script.Length, "PeekChar out of range."); if (_currentIndex == _script.Length) { @@ -1045,7 +1045,7 @@ internal void Resync(int start) { _currentIndex = _script.Length + 1; } - else if (0 > _currentIndex) + else if (_currentIndex < 0) { _currentIndex = 0; } diff --git a/src/System.Management.Automation/engine/pipeline.cs b/src/System.Management.Automation/engine/pipeline.cs index 17fe22bcfd0..fb753652c93 100644 --- a/src/System.Management.Automation/engine/pipeline.cs +++ b/src/System.Management.Automation/engine/pipeline.cs @@ -91,14 +91,6 @@ private void Dispose(bool disposing) _disposed = true; } - /// - /// Finalizer for class PipelineProcessor. - /// - ~PipelineProcessor() - { - Dispose(false); - } - #endregion IDispose #region Execution Logging @@ -174,7 +166,7 @@ internal void LogExecutionException(Exception exception) Log(message, null, PipelineExecutionStatus.Error); } - private string GetCommand(InvocationInfo invocationInfo) + private static string GetCommand(InvocationInfo invocationInfo) { if (invocationInfo == null) return string.Empty; @@ -187,7 +179,7 @@ private string GetCommand(InvocationInfo invocationInfo) return string.Empty; } - private string GetCommand(Exception exception) + private static string GetCommand(Exception exception) { IContainsErrorRecord icer = exception as IContainsErrorRecord; if (icer != null && icer.ErrorRecord != null) diff --git a/src/System.Management.Automation/engine/regex.cs b/src/System.Management.Automation/engine/regex.cs index 06b9676c0e8..3f827dc08f8 100644 --- a/src/System.Management.Automation/engine/regex.cs +++ b/src/System.Management.Automation/engine/regex.cs @@ -43,7 +43,7 @@ public enum WildcardOptions /// Specifies culture-invariant matching. /// CultureInvariant = 4 - }; + } /// /// Represents a wildcard pattern. @@ -184,7 +184,7 @@ StringComparison GetStringComparison() if (index == Pattern.Length - 1 && Pattern[index] == '*') { // No special characters present in the pattern before last position and last character is asterisk. - var patternWithoutAsterisk = Pattern.AsMemory().Slice(0, index); + var patternWithoutAsterisk = Pattern.AsMemory(0, index); _isMatch = str => str.AsSpan().StartsWith(patternWithoutAsterisk.Span, GetStringComparison()); return; } @@ -325,7 +325,7 @@ public static bool ContainsWildcardCharacters(string pattern) /// converted to their unescaped form. /// /// - /// If is null. + /// If is null. /// public static string Unescape(string pattern) { @@ -729,7 +729,7 @@ internal static WildcardPatternException NewWildcardPatternException(string inva return e; } - }; + } /// /// Convert a string with wild cards into its equivalent regex. @@ -1264,7 +1264,7 @@ protected override void EndBracketExpression() } } - private struct CharacterNormalizer + private readonly struct CharacterNormalizer { private readonly CultureInfo _cultureInfo; private readonly bool _caseInsensitive; diff --git a/src/System.Management.Automation/engine/remoting/client/ClientMethodExecutor.cs b/src/System.Management.Automation/engine/remoting/client/ClientMethodExecutor.cs index 3defa2f8285..120ca07a5af 100644 --- a/src/System.Management.Automation/engine/remoting/client/ClientMethodExecutor.cs +++ b/src/System.Management.Automation/engine/remoting/client/ClientMethodExecutor.cs @@ -98,8 +98,7 @@ internal static void Dispatch( if (hostPrivateData != null) { PSNoteProperty allowSetShouldExit = hostPrivateData.Properties["AllowSetShouldExitFromRemote"] as PSNoteProperty; - hostAllowSetShouldExit = (allowSetShouldExit != null && allowSetShouldExit.Value is bool) ? - (bool)allowSetShouldExit.Value : false; + hostAllowSetShouldExit = allowSetShouldExit != null && allowSetShouldExit.Value is bool && (bool)allowSetShouldExit.Value; } } @@ -132,7 +131,7 @@ internal static void Dispatch( /// /// Is runspace pushed. /// - private bool IsRunspacePushed(PSHost host) + private static bool IsRunspacePushed(PSHost host) { if (!(host is IHostSupportsInteractiveSession host2)) { return false; } diff --git a/src/System.Management.Automation/engine/remoting/client/ClientRemotePowerShell.cs b/src/System.Management.Automation/engine/remoting/client/ClientRemotePowerShell.cs index 672fe188da7..4ea06ea2feb 100644 --- a/src/System.Management.Automation/engine/remoting/client/ClientRemotePowerShell.cs +++ b/src/System.Management.Automation/engine/remoting/client/ClientRemotePowerShell.cs @@ -645,7 +645,7 @@ private void HandleCloseCompleted(object sender, EventArgs args) // If RemoteSessionStateEventArgs are provided then use them to set the // session close reason when setting finished state. RemoteSessionStateEventArgs sessionEventArgs = args as RemoteSessionStateEventArgs; - Exception closeReason = (sessionEventArgs != null) ? sessionEventArgs.SessionStateInfo.Reason : null; + Exception closeReason = sessionEventArgs?.SessionStateInfo.Reason; PSInvocationState finishedState = (shell.InvocationStateInfo.State == PSInvocationState.Disconnected) ? PSInvocationState.Failed : PSInvocationState.Stopped; @@ -663,7 +663,7 @@ private void HandleCloseCompleted(object sender, EventArgs args) } } - private bool IsFinished(PSInvocationState state) + private static bool IsFinished(PSInvocationState state) { return (state == PSInvocationState.Completed || state == PSInvocationState.Failed || @@ -977,7 +977,7 @@ internal enum PSConnectionRetryStatus AutoDisconnectStarting = 4, AutoDisconnectSucceeded = 5, InternalErrorAbort = 6 - }; + } /// /// PSConnectionRetryStatusEventArgs. diff --git a/src/System.Management.Automation/engine/remoting/client/Job.cs b/src/System.Management.Automation/engine/remoting/client/Job.cs index b88e8003945..8e876902c26 100644 --- a/src/System.Management.Automation/engine/remoting/client/Job.cs +++ b/src/System.Management.Automation/engine/remoting/client/Job.cs @@ -379,12 +379,13 @@ internal JobIdentifier(int id, Guid instanceId) /// /// Interface to expose a job debugger. /// +#nullable enable public interface IJobDebugger { /// /// Job Debugger. /// - Debugger Debugger + Debugger? Debugger { get; } @@ -398,6 +399,7 @@ bool IsAsync set; } } +#nullable restore /// /// Represents a command running in background. A job object can internally @@ -2016,7 +2018,7 @@ internal void ConnectJob(Guid runspaceInstanceId) SubmitAndWaitForConnect(connectJobOperations); } - private void SubmitAndWaitForConnect(List connectJobOperations) + private static void SubmitAndWaitForConnect(List connectJobOperations) { using (ThrottleManager connectThrottleManager = new ThrottleManager()) { @@ -2968,7 +2970,7 @@ internal override bool CanDisconnect get { RemoteRunspace remoteRS = Runspace as RemoteRunspace; - return (remoteRS != null) ? remoteRS.CanDisconnect : false; + return remoteRS != null && remoteRS.CanDisconnect; } } @@ -4122,7 +4124,7 @@ private Pipeline DrainAndBlockRemoteOutput() return null; } - private void RestoreRemoteOutput(Pipeline runningCmd) + private static void RestoreRemoteOutput(Pipeline runningCmd) { if (runningCmd != null) { @@ -4518,9 +4520,10 @@ internal OutputProcessingStateEventArgs(bool processingOutput) } } +#nullable enable internal interface IOutputProcessingState { - event EventHandler OutputProcessingStateChanged; + event EventHandler? OutputProcessingStateChanged; } #endregion diff --git a/src/System.Management.Automation/engine/remoting/client/JobManager.cs b/src/System.Management.Automation/engine/remoting/client/JobManager.cs index b2e4f0d6454..f907cf922d8 100644 --- a/src/System.Management.Automation/engine/remoting/client/JobManager.cs +++ b/src/System.Management.Automation/engine/remoting/client/JobManager.cs @@ -616,7 +616,7 @@ private List GetFilteredJobs( /// /// /// - private bool CheckTypeNames(JobSourceAdapter sourceAdapter, string[] jobSourceAdapterTypes) + private static bool CheckTypeNames(JobSourceAdapter sourceAdapter, string[] jobSourceAdapterTypes) { // If no type names were specified then allow all adapter types. if (jobSourceAdapterTypes == null || @@ -641,7 +641,7 @@ private bool CheckTypeNames(JobSourceAdapter sourceAdapter, string[] jobSourceAd return false; } - private string GetAdapterName(JobSourceAdapter sourceAdapter) + private static string GetAdapterName(JobSourceAdapter sourceAdapter) { return (!string.IsNullOrEmpty(sourceAdapter.Name) ? sourceAdapter.Name : diff --git a/src/System.Management.Automation/engine/remoting/client/JobSourceAdapter.cs b/src/System.Management.Automation/engine/remoting/client/JobSourceAdapter.cs index de3d41d1956..f5a5022d705 100644 --- a/src/System.Management.Automation/engine/remoting/client/JobSourceAdapter.cs +++ b/src/System.Management.Automation/engine/remoting/client/JobSourceAdapter.cs @@ -238,7 +238,7 @@ public JobDefinition Definition /// public List Parameters { - get { return _parameters ?? (_parameters = new List()); } + get { return _parameters ??= new List(); } } /// diff --git a/src/System.Management.Automation/engine/remoting/client/RemoteRunspacePoolInternal.cs b/src/System.Management.Automation/engine/remoting/client/RemoteRunspacePoolInternal.cs index 3e873fbe42c..94584c613f5 100644 --- a/src/System.Management.Automation/engine/remoting/client/RemoteRunspacePoolInternal.cs +++ b/src/System.Management.Automation/engine/remoting/client/RemoteRunspacePoolInternal.cs @@ -1426,8 +1426,7 @@ private static void UpdateWSManConnectionInfo( string compressionModeString = pspCompressionMode.Value as string; if (compressionModeString != null) { - wsmanConnectionInfo.UseCompression = compressionModeString.Equals("NoCompression", StringComparison.OrdinalIgnoreCase) - ? false : true; + wsmanConnectionInfo.UseCompression = !compressionModeString.Equals("NoCompression", StringComparison.OrdinalIgnoreCase); } } @@ -1436,8 +1435,7 @@ private static void UpdateWSManConnectionInfo( string encodingString = pspEncoding.Value as string; if (encodingString != null) { - wsmanConnectionInfo.UseUTF16 = encodingString.Equals("UTF16", StringComparison.OrdinalIgnoreCase) - ? true : false; + wsmanConnectionInfo.UseUTF16 = encodingString.Equals("UTF16", StringComparison.OrdinalIgnoreCase); } } @@ -1446,8 +1444,7 @@ private static void UpdateWSManConnectionInfo( string machineProfileLoadedString = pspProfile.Value as string; if (machineProfileLoadedString != null) { - wsmanConnectionInfo.NoMachineProfile = machineProfileLoadedString.Equals("Yes", StringComparison.OrdinalIgnoreCase) - ? false : true; + wsmanConnectionInfo.NoMachineProfile = !machineProfileLoadedString.Equals("Yes", StringComparison.OrdinalIgnoreCase); } } @@ -1882,7 +1879,7 @@ private void WaitAndRaiseConnectEventsProc(object state) private readonly RunspaceConnectionInfo _connectionInfo; // connection info with which this // runspace is created // data structure handler handling - private RunspacePoolAsyncResult _openAsyncResult;// async result object generated on + private RunspacePoolAsyncResult _openAsyncResult; // async result object generated on // CoreOpen private RunspacePoolAsyncResult _closeAsyncResult; // async result object generated by // BeginClose diff --git a/src/System.Management.Automation/engine/remoting/client/RemotingProtocol2.cs b/src/System.Management.Automation/engine/remoting/client/RemotingProtocol2.cs index 501a87e6ed9..8b8908b6e61 100644 --- a/src/System.Management.Automation/engine/remoting/client/RemotingProtocol2.cs +++ b/src/System.Management.Automation/engine/remoting/client/RemotingProtocol2.cs @@ -233,7 +233,7 @@ internal void CreatePowerShellOnServerAndInvoke(ClientRemotePowerShell shell) // Find out if this is an invoke and disconnect operation and if so whether the endpoint // supports disconnect. Throw exception if disconnect is not supported. - bool invokeAndDisconnect = (shell.Settings != null) ? shell.Settings.InvokeAndDisconnect : false; + bool invokeAndDisconnect = shell.Settings != null && shell.Settings.InvokeAndDisconnect; if (invokeAndDisconnect && !EndpointSupportsDisconnect) { throw new PSRemotingDataStructureException(RemotingErrorIdStrings.EndpointDoesNotSupportDisconnect); @@ -873,6 +873,7 @@ private void HandleSessionCreateCompleted(object sender, CreateCompleteEventArgs private readonly Dictionary _associatedPowerShellDSHandlers = new Dictionary(); + // data structure handlers of all ClientRemotePowerShell which are // associated with this runspace pool private readonly object _associationSyncObject = new object(); @@ -937,7 +938,7 @@ internal bool EndpointSupportsDisconnect get { WSManClientSessionTransportManager wsmanTransportManager = _transportManager as WSManClientSessionTransportManager; - return (wsmanTransportManager != null) ? wsmanTransportManager.SupportsDisconnect : false; + return wsmanTransportManager != null && wsmanTransportManager.SupportsDisconnect; } } @@ -1412,7 +1413,7 @@ internal void ProcessDisconnect(RunspacePoolStateInfo rsStateInfo) // disconnect may be called on a pipeline that is already disconnected. PSInvocationStateInfo stateInfo = new PSInvocationStateInfo(PSInvocationState.Disconnected, - (rsStateInfo != null) ? rsStateInfo.Reason : null); + rsStateInfo?.Reason); Dbg.Assert(InvocationStateInfoReceived != null, "ClientRemotePowerShell should subscribe to all data structure handler events"); diff --git a/src/System.Management.Automation/engine/remoting/client/RunspaceRef.cs b/src/System.Management.Automation/engine/remoting/client/RunspaceRef.cs index 4dfcb01555b..dfd1cd3bf7f 100644 --- a/src/System.Management.Automation/engine/remoting/client/RunspaceRef.cs +++ b/src/System.Management.Automation/engine/remoting/client/RunspaceRef.cs @@ -93,7 +93,7 @@ private PSCommand ParsePsCommandUsingScriptBlock(string line, bool? useLocalScop // and if we are not in a loopback configuration mode, in which case we always force remote script commands // to be parsed and evaluated on the remote session (not in the current local session). RemoteRunspace remoteRunspace = _runspaceRef.Value as RemoteRunspace; - bool isConfiguredLoopback = (remoteRunspace != null) ? remoteRunspace.IsConfiguredLoopBack : false; + bool isConfiguredLoopback = remoteRunspace != null && remoteRunspace.IsConfiguredLoopBack; bool isTrustedInput = !isConfiguredLoopback && (localRunspace.ExecutionContext.LanguageMode == PSLanguageMode.FullLanguage); // Create PowerShell from ScriptBlock. @@ -139,7 +139,7 @@ internal PSCommand CreatePsCommand(string line, bool isScript, bool? useNewScope /// /// Creates the PSCommand when the runspace is not overridden. /// - private PSCommand CreatePsCommandNotOverridden(string line, bool isScript, bool? useNewScope) + private static PSCommand CreatePsCommandNotOverridden(string line, bool isScript, bool? useNewScope) { PSCommand command = new PSCommand(); @@ -407,7 +407,7 @@ private void StartProgressBar( } } - private void StopProgressBar( + private static void StopProgressBar( long sourceId) { s_RCProgress.StopProgress(sourceId); diff --git a/src/System.Management.Automation/engine/remoting/client/ThrottlingJob.cs b/src/System.Management.Automation/engine/remoting/client/ThrottlingJob.cs index b1d9c968b10..a00fdee17c2 100644 --- a/src/System.Management.Automation/engine/remoting/client/ThrottlingJob.cs +++ b/src/System.Management.Automation/engine/remoting/client/ThrottlingJob.cs @@ -191,8 +191,8 @@ internal enum ChildJobFlags /// /// Child job can call method - /// or - /// or + /// or + /// or /// method /// of the instance it belongs to. /// @@ -269,12 +269,12 @@ private int CountOfRunningOrReadyToRunChildJobs /// Passing 0 requests to turn off throttling (i.e. allow unlimited number of child jobs to run) /// /// - /// true if this is used from a cmdlet invoked without -AsJob switch. - /// false if this is used from a cmdlet invoked with -AsJob switch. + /// if this is used from a cmdlet invoked without -AsJob switch. + /// if this is used from a cmdlet invoked with -AsJob switch. /// - /// If is true, then + /// If is , then /// memory can be managed more aggressively (for example ChildJobs can be discarded as soon as they complete) - /// because the is not exposed to the end user. + /// because the is not exposed to the end user. /// internal ThrottlingJob(string command, string jobName, string jobTypeName, int maximumConcurrentChildJobs, bool cmdletMode) : base(command, jobName) @@ -387,7 +387,7 @@ internal void AddChildJobWithoutBlocking(StartableJob childJob, ChildJobFlags fl newJobStateInfo = new JobStateInfo(JobState.Running); } - if (ChildJobFlags.CreatesChildJobs == (ChildJobFlags.CreatesChildJobs & flags)) + if ((ChildJobFlags.CreatesChildJobs & flags) == ChildJobFlags.CreatesChildJobs) { _setOfChildJobsThatCanAddMoreChildJobs.Add(childJob.InstanceId); } @@ -777,8 +777,8 @@ private List GetChildJobsSnapshot() /// /// Indicates if job has more data available. - /// true if any of the child jobs have more data OR if have not been called yet; - /// false otherwise. + /// if any of the child jobs have more data OR if have not been called yet; + /// otherwise. /// public override bool HasMoreData { diff --git a/src/System.Management.Automation/engine/remoting/client/clientremotesessionprotocolstatemachine.cs b/src/System.Management.Automation/engine/remoting/client/clientremotesessionprotocolstatemachine.cs index ca26f32cc5b..d035ce6e820 100644 --- a/src/System.Management.Automation/engine/remoting/client/clientremotesessionprotocolstatemachine.cs +++ b/src/System.Management.Automation/engine/remoting/client/clientremotesessionprotocolstatemachine.cs @@ -48,6 +48,7 @@ internal class ClientRemoteSessionDSHandlerStateMachine private readonly Queue _processPendingEventsQueue = new Queue(); + // all events raised through the state machine // will be queued in this private readonly object _syncObject = new object(); @@ -775,7 +776,7 @@ private void DoFatal(object sender, RemoteSessionStateMachineEventArgs eventArgs #endregion Event Handlers - private void CleanAll() + private static void CleanAll() { } diff --git a/src/System.Management.Automation/engine/remoting/client/remoterunspace.cs b/src/System.Management.Automation/engine/remoting/client/remoterunspace.cs index 7824c350c78..7ddd657872e 100644 --- a/src/System.Management.Automation/engine/remoting/client/remoterunspace.cs +++ b/src/System.Management.Automation/engine/remoting/client/remoterunspace.cs @@ -1201,7 +1201,7 @@ internal void DoConcurrentCheckAndAddToRunningPipelines(RemotePipeline pipeline, /// internal override SessionStateProxy GetSessionStateProxy() { - return _sessionStateProxy ?? (_sessionStateProxy = new RemoteSessionStateProxy(this)); + return _sessionStateProxy ??= new RemoteSessionStateProxy(this); } private RemoteSessionStateProxy _sessionStateProxy = null; @@ -1936,17 +1936,17 @@ public override DebuggerCommandResults ProcessCommand(PSCommand command, PSDataC { // Allow the IncompleteParseException to throw so that the console // can handle here strings and continued parsing. - if (re.ErrorRecord.CategoryInfo.Reason == typeof(IncompleteParseException).Name) + if (re.ErrorRecord.CategoryInfo.Reason == nameof(IncompleteParseException)) { throw new IncompleteParseException( - (re.ErrorRecord.Exception != null) ? re.ErrorRecord.Exception.Message : null, + re.ErrorRecord.Exception?.Message, re.ErrorRecord.FullyQualifiedErrorId); } // Allow the RemoteException and InvalidRunspacePoolStateException to propagate so that the host can // clean up the debug session. - if ((re.ErrorRecord.CategoryInfo.Reason == typeof(InvalidRunspacePoolStateException).Name) || - (re.ErrorRecord.CategoryInfo.Reason == typeof(RemoteException).Name)) + if ((re.ErrorRecord.CategoryInfo.Reason == nameof(InvalidRunspacePoolStateException)) || + (re.ErrorRecord.CategoryInfo.Reason == nameof(RemoteException))) { throw new PSRemotingTransportException( (re.ErrorRecord.Exception != null) ? re.ErrorRecord.Exception.Message : string.Empty); @@ -2660,7 +2660,7 @@ private void ProcessDebuggerStopEvent(DebuggerStopEventArgs args) // Attempt to process debugger stop event on original thread if it // is available (i.e., if it is blocked by EndInvoke). PowerShell powershell = _runspace.RunspacePool.RemoteRunspacePoolInternal.GetCurrentRunningPowerShell(); - AsyncResult invokeAsyncResult = (powershell != null) ? powershell.EndInvokeAsyncResult : null; + AsyncResult invokeAsyncResult = powershell?.EndInvokeAsyncResult; bool invokedOnBlockedThread = false; if ((invokeAsyncResult != null) && (!invokeAsyncResult.IsCompleted)) diff --git a/src/System.Management.Automation/engine/remoting/client/remoterunspaceinfo.cs b/src/System.Management.Automation/engine/remoting/client/remoterunspaceinfo.cs index 1a975f5a785..1fa03edf25b 100644 --- a/src/System.Management.Automation/engine/remoting/client/remoterunspaceinfo.cs +++ b/src/System.Management.Automation/engine/remoting/client/remoterunspaceinfo.cs @@ -208,7 +208,7 @@ public Runspace Runspace public override string ToString() { // PSSession is a PowerShell type name and so should not be localized. - string formatString = "[PSSession]{0}"; + const string formatString = "[PSSession]{0}"; return StringUtil.Format(formatString, Name); } @@ -347,9 +347,9 @@ private string GetTransportName() /// /// Shell configuration name. /// Display shell name. - private string GetDisplayShellName(string shell) + private static string GetDisplayShellName(string shell) { - string shellPrefix = System.Management.Automation.Remoting.Client.WSManNativeApi.ResourceURIPrefix; + const string shellPrefix = System.Management.Automation.Remoting.Client.WSManNativeApi.ResourceURIPrefix; int index = shell.IndexOf(shellPrefix, StringComparison.OrdinalIgnoreCase); return (index == 0) ? shell.Substring(shellPrefix.Length) : shell; diff --git a/src/System.Management.Automation/engine/remoting/commands/CustomShellCommands.cs b/src/System.Management.Automation/engine/remoting/commands/CustomShellCommands.cs index ae13e4fda76..c9202190221 100644 --- a/src/System.Management.Automation/engine/remoting/commands/CustomShellCommands.cs +++ b/src/System.Management.Automation/engine/remoting/commands/CustomShellCommands.cs @@ -589,8 +589,8 @@ protected override void ProcessRecord() restartServiceTarget, restartServiceAction, restartWSManRequiredForUI, - runAsCredential != null ? runAsCredential.UserName : null, - runAsCredential != null ? runAsCredential.Password : null, + runAsCredential?.UserName, + runAsCredential?.Password, AccessMode, isSddlSpecified, _configTableSDDL, @@ -641,7 +641,7 @@ protected override void EndProcessing() /// 1. New shell successfully registered. However cannot delete temporary plugin file {0}. /// Reason for failure: {1}. /// - private void DeleteFile(string tmpFileName) + private static void DeleteFile(string tmpFileName) { Dbg.Assert(!string.IsNullOrEmpty(tmpFileName), "tmpFile cannot be null or empty."); @@ -693,7 +693,7 @@ private void DeleteFile(string tmpFileName) /// 2. Cannot write shell configuration data into temporary file {0}. Try again. /// Reason for failure: {1}. /// - private string ConstructTemporaryFile(string pluginContent) + private static string ConstructTemporaryFile(string pluginContent) { // Path.GetTempFileName creates a temporary file whereas GetRandomFileName does not. string tmpFileName = System.IO.Path.Combine(System.IO.Path.GetTempPath(), System.IO.Path.GetRandomFileName()) + "psshell.xml"; @@ -798,7 +798,7 @@ private string ConstructPluginContent(out string srcConfigFilePath, out string d destConfigFilePath = null; StringBuilder initParameters = new StringBuilder(); - bool assemblyAndTypeTokensSet = false; + const bool assemblyAndTypeTokensSet = false; // DISC endpoint if (Path != null) diff --git a/src/System.Management.Automation/engine/remoting/commands/DebugJob.cs b/src/System.Management.Automation/engine/remoting/commands/DebugJob.cs index 979912619f2..777f56807fe 100644 --- a/src/System.Management.Automation/engine/remoting/commands/DebugJob.cs +++ b/src/System.Management.Automation/engine/remoting/commands/DebugJob.cs @@ -237,7 +237,7 @@ private bool CheckForDebuggableJob() return debuggableJobFound; } - private bool GetJobDebuggable(Job job) + private static bool GetJobDebuggable(Job job) { if (job is IJobDebugger) { diff --git a/src/System.Management.Automation/engine/remoting/commands/DisconnectPSSession.cs b/src/System.Management.Automation/engine/remoting/commands/DisconnectPSSession.cs index 5e4f3b8c129..0e2458daba0 100644 --- a/src/System.Management.Automation/engine/remoting/commands/DisconnectPSSession.cs +++ b/src/System.Management.Automation/engine/remoting/commands/DisconnectPSSession.cs @@ -109,7 +109,7 @@ private PSSessionOption PSSessionOption { // no need to lock as the cmdlet parameters will not be assigned // from multiple threads. - return _sessionOption ?? (_sessionOption = new PSSessionOption()); + return _sessionOption ??= new PSSessionOption(); } } @@ -346,7 +346,7 @@ private bool ValidateIdleTimeout(PSSession session) { int idleTimeout = session.Runspace.ConnectionInfo.IdleTimeout; int maxIdleTimeout = session.Runspace.ConnectionInfo.MaxIdleTimeout; - int minIdleTimeout = BaseTransportManager.MinimumIdleTimeout; + const int minIdleTimeout = BaseTransportManager.MinimumIdleTimeout; if (idleTimeout != BaseTransportManager.UseServerDefaultIdleTimeout && (idleTimeout > maxIdleTimeout || idleTimeout < minIdleTimeout)) @@ -363,7 +363,7 @@ private bool ValidateIdleTimeout(PSSession session) return true; } - private string GetLocalhostWithNetworkAccessEnabled(Dictionary psSessions) + private static string GetLocalhostWithNetworkAccessEnabled(Dictionary psSessions) { System.Text.StringBuilder sb = new System.Text.StringBuilder(); diff --git a/src/System.Management.Automation/engine/remoting/commands/EnterPSHostProcessCommand.cs b/src/System.Management.Automation/engine/remoting/commands/EnterPSHostProcessCommand.cs index 454cc10efd0..756250eb8d7 100644 --- a/src/System.Management.Automation/engine/remoting/commands/EnterPSHostProcessCommand.cs +++ b/src/System.Management.Automation/engine/remoting/commands/EnterPSHostProcessCommand.cs @@ -292,7 +292,7 @@ private Runspace CreateNamedPipeRunspace(NamedPipeConnectionInfo connectionInfo) return remoteRunspace; } - private void PrepareRunspace(Runspace runspace) + private static void PrepareRunspace(Runspace runspace) { string promptFn = StringUtil.Format(RemotingErrorIdStrings.EnterPSHostProcessPrompt, @"function global:prompt { """, @@ -574,7 +574,7 @@ protected override void EndProcessing() #region Private Methods - private int[] GetProcIdsFromProcs(Process[] processes) + private static int[] GetProcIdsFromProcs(Process[] processes) { List returnIds = new List(); foreach (Process process in processes) @@ -585,7 +585,7 @@ private int[] GetProcIdsFromProcs(Process[] processes) return returnIds.ToArray(); } - private int[] GetProcIdsFromNames(string[] names) + private static int[] GetProcIdsFromNames(string[] names) { if ((names == null) || (names.Length == 0)) { diff --git a/src/System.Management.Automation/engine/remoting/commands/InvokeCommandCommand.cs b/src/System.Management.Automation/engine/remoting/commands/InvokeCommandCommand.cs index 677a767d1fd..b60f3131f24 100644 --- a/src/System.Management.Automation/engine/remoting/commands/InvokeCommandCommand.cs +++ b/src/System.Management.Automation/engine/remoting/commands/InvokeCommandCommand.cs @@ -1875,7 +1875,7 @@ private void StartProgressBar( this.Host); } - private void StopProgressBar( + private static void StopProgressBar( long sourceId) { s_RCProgress.StopProgress(sourceId); @@ -1954,7 +1954,7 @@ private void DetermineThrowStatementBehavior() /// Process the stream object before writing it in the specified collection. /// /// Stream object to process. - private void PreProcessStreamObject(PSStreamObject streamObject) + private static void PreProcessStreamObject(PSStreamObject streamObject) { ErrorRecord errorRecord = streamObject.Value as ErrorRecord; diff --git a/src/System.Management.Automation/engine/remoting/commands/NewPSSessionConfigurationFile.cs b/src/System.Management.Automation/engine/remoting/commands/NewPSSessionConfigurationFile.cs index 02115bb2f47..f306246e289 100644 --- a/src/System.Management.Automation/engine/remoting/commands/NewPSSessionConfigurationFile.cs +++ b/src/System.Management.Automation/engine/remoting/commands/NewPSSessionConfigurationFile.cs @@ -857,7 +857,7 @@ protected override void ProcessRecord() { if (Full) { - string exampleModulesToImport = "'MyCustomModule', @{ ModuleName = 'MyCustomModule'; ModuleVersion = '1.0.0.0'; GUID = '4d30d5f0-cb16-4898-812d-f20a6c596bdf' }"; + const string exampleModulesToImport = "'MyCustomModule', @{ ModuleName = 'MyCustomModule'; ModuleVersion = '1.0.0.0'; GUID = '4d30d5f0-cb16-4898-812d-f20a6c596bdf' }"; result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.ModulesToImport, RemotingErrorIdStrings.DISCModulesToImportComment, exampleModulesToImport, streamWriter, true)); } } @@ -1621,7 +1621,7 @@ protected override void ProcessRecord() // Modules to import if (_modulesToImport == null) { - string exampleModulesToImport = "'MyCustomModule', @{ ModuleName = 'MyCustomModule'; ModuleVersion = '1.0.0.0'; GUID = '4d30d5f0-cb16-4898-812d-f20a6c596bdf' }"; + const string exampleModulesToImport = "'MyCustomModule', @{ ModuleName = 'MyCustomModule'; ModuleVersion = '1.0.0.0'; GUID = '4d30d5f0-cb16-4898-812d-f20a6c596bdf' }"; result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.ModulesToImport, RemotingErrorIdStrings.DISCModulesToImportComment, exampleModulesToImport, streamWriter, true)); } else diff --git a/src/System.Management.Automation/engine/remoting/commands/NewPSSessionOptionCommand.cs b/src/System.Management.Automation/engine/remoting/commands/NewPSSessionOptionCommand.cs index 5ad0df8910c..2a6dbc30679 100644 --- a/src/System.Management.Automation/engine/remoting/commands/NewPSSessionOptionCommand.cs +++ b/src/System.Management.Automation/engine/remoting/commands/NewPSSessionOptionCommand.cs @@ -48,7 +48,7 @@ public int MaximumRedirection public SwitchParameter NoCompression { get; set; } /// - /// If true then Operating System won't load the user profile (i.e. registry keys under HKCU) on the remote server + /// If then Operating System won't load the user profile (i.e. registry keys under HKCU) on the remote server /// which can result in a faster session creation time. This option won't have any effect if the remote machine has /// already loaded the profile (i.e. in another session). /// diff --git a/src/System.Management.Automation/engine/remoting/commands/PSRemotingCmdlet.cs b/src/System.Management.Automation/engine/remoting/commands/PSRemotingCmdlet.cs index 0e422808f1a..bbb2056189c 100644 --- a/src/System.Management.Automation/engine/remoting/commands/PSRemotingCmdlet.cs +++ b/src/System.Management.Automation/engine/remoting/commands/PSRemotingCmdlet.cs @@ -1879,7 +1879,7 @@ internal Pipeline CreatePipeline(RemoteRunspace remoteRunspace) /// /// Check the powershell version of the remote server. /// - private string GetRemoteServerPsVersion(RemoteRunspace remoteRunspace) + private static string GetRemoteServerPsVersion(RemoteRunspace remoteRunspace) { if (remoteRunspace.ConnectionInfo is NewProcessConnectionInfo) { @@ -2427,7 +2427,7 @@ private List GetUsingVariableValues(List paramUsi /// /// /// A list of UsingExpressionAsts ordered by the StartOffset. - private List GetUsingVariables(ScriptBlock localScriptBlock) + private static List GetUsingVariables(ScriptBlock localScriptBlock) { if (localScriptBlock == null) { @@ -3003,9 +3003,9 @@ private Dictionary GetMatchingRunspacesByVMNameContainerId(bool var matchingRunspaceInfos = remoteRunspaceInfos .Where(session => (supportWildChar ? inputNamePattern.IsMatch(session.VMName) : inputName.Equals(session.ContainerId)) && - ((sessionNamePattern == null) ? true : sessionNamePattern.IsMatch(session.Name)) && + (sessionNamePattern == null || sessionNamePattern.IsMatch(session.Name)) && QueryRunspaces.TestRunspaceState(session.Runspace, filterState) && - ((configurationNamePattern == null) ? true : configurationNamePattern.IsMatch(session.ConfigurationName)) && + (configurationNamePattern == null || configurationNamePattern.IsMatch(session.ConfigurationName)) && (session.ComputerType == computerType)) .ToList(); @@ -3063,7 +3063,7 @@ private Dictionary GetMatchingRunspacesByVMNameContainerIdSessi : inputName.Equals(session.ContainerId)) && sessionInstanceId.Equals(session.InstanceId) && QueryRunspaces.TestRunspaceState(session.Runspace, filterState) && - ((configurationNamePattern == null) ? true : configurationNamePattern.IsMatch(session.ConfigurationName)) && + (configurationNamePattern == null || configurationNamePattern.IsMatch(session.ConfigurationName)) && (session.ComputerType == computerType)) .ToList(); @@ -3106,9 +3106,9 @@ private Dictionary GetMatchingRunspacesByVMId(bool writeobject, var matchingRunspaceInfos = remoteRunspaceInfos .Where(session => vmId.Equals(session.VMId) && - ((sessionNamePattern == null) ? true : sessionNamePattern.IsMatch(session.Name)) && + (sessionNamePattern == null || sessionNamePattern.IsMatch(session.Name)) && QueryRunspaces.TestRunspaceState(session.Runspace, filterState) && - ((configurationNamePattern == null) ? true : configurationNamePattern.IsMatch(session.ConfigurationName)) && + (configurationNamePattern == null || configurationNamePattern.IsMatch(session.ConfigurationName)) && (session.ComputerType == TargetMachineType.VirtualMachine)) .ToList(); @@ -3143,7 +3143,7 @@ private Dictionary GetMatchingRunspacesByVMIdSessionInstanceId( .Where(session => vmId.Equals(session.VMId) && sessionInstanceId.Equals(session.InstanceId) && QueryRunspaces.TestRunspaceState(session.Runspace, filterState) && - ((configurationNamePattern == null) ? true : configurationNamePattern.IsMatch(session.ConfigurationName)) && + (configurationNamePattern == null || configurationNamePattern.IsMatch(session.ConfigurationName)) && (session.ComputerType == TargetMachineType.VirtualMachine)) .ToList(); @@ -4328,7 +4328,7 @@ public PSSessionOption() public bool NoCompression { get; set; } = false; /// - /// If true then Operating System won't load the user profile (i.e. registry keys under HKCU) on the remote server + /// If then Operating System won't load the user profile (i.e. registry keys under HKCU) on the remote server /// which can result in a faster session creation time. This option won't have any effect if the remote machine has /// already loaded the profile (i.e. in another session). /// diff --git a/src/System.Management.Automation/engine/remoting/commands/PushRunspaceCommand.cs b/src/System.Management.Automation/engine/remoting/commands/PushRunspaceCommand.cs index 29e85600500..cbc5f82742b 100644 --- a/src/System.Management.Automation/engine/remoting/commands/PushRunspaceCommand.cs +++ b/src/System.Management.Automation/engine/remoting/commands/PushRunspaceCommand.cs @@ -791,12 +791,13 @@ private RemoteRunspace GetRunspaceMatchingCondition( /// private RemoteRunspace GetRunspaceMatchingRunspaceId(Guid remoteRunspaceId) { - Predicate condition = (PSSession info) => info.InstanceId == remoteRunspaceId; - PSRemotingErrorId tooFew = PSRemotingErrorId.RemoteRunspaceNotAvailableForSpecifiedRunspaceId; - PSRemotingErrorId tooMany = PSRemotingErrorId.RemoteRunspaceHasMultipleMatchesForSpecifiedRunspaceId; - string tooFewResourceString = RemotingErrorIdStrings.RemoteRunspaceNotAvailableForSpecifiedRunspaceId; - string tooManyResourceString = RemotingErrorIdStrings.RemoteRunspaceHasMultipleMatchesForSpecifiedRunspaceId; - return GetRunspaceMatchingCondition(condition, tooFew, tooMany, tooFewResourceString, tooManyResourceString, remoteRunspaceId); + return GetRunspaceMatchingCondition( + condition: info => info.InstanceId == remoteRunspaceId, + tooFew: PSRemotingErrorId.RemoteRunspaceNotAvailableForSpecifiedRunspaceId, + tooMany: PSRemotingErrorId.RemoteRunspaceHasMultipleMatchesForSpecifiedRunspaceId, + tooFewResourceString: RemotingErrorIdStrings.RemoteRunspaceNotAvailableForSpecifiedRunspaceId, + tooManyResourceString: RemotingErrorIdStrings.RemoteRunspaceHasMultipleMatchesForSpecifiedRunspaceId, + errorArgument: remoteRunspaceId); } /// @@ -804,12 +805,13 @@ private RemoteRunspace GetRunspaceMatchingRunspaceId(Guid remoteRunspaceId) /// private RemoteRunspace GetRunspaceMatchingSessionId(int sessionId) { - Predicate condition = (PSSession info) => info.Id == sessionId; - PSRemotingErrorId tooFew = PSRemotingErrorId.RemoteRunspaceNotAvailableForSpecifiedSessionId; - PSRemotingErrorId tooMany = PSRemotingErrorId.RemoteRunspaceHasMultipleMatchesForSpecifiedSessionId; - string tooFewResourceString = RemotingErrorIdStrings.RemoteRunspaceNotAvailableForSpecifiedSessionId; - string tooManyResourceString = RemotingErrorIdStrings.RemoteRunspaceHasMultipleMatchesForSpecifiedSessionId; - return GetRunspaceMatchingCondition(condition, tooFew, tooMany, tooFewResourceString, tooManyResourceString, sessionId); + return GetRunspaceMatchingCondition( + condition: info => info.Id == sessionId, + tooFew: PSRemotingErrorId.RemoteRunspaceNotAvailableForSpecifiedSessionId, + tooMany: PSRemotingErrorId.RemoteRunspaceHasMultipleMatchesForSpecifiedSessionId, + tooFewResourceString: RemotingErrorIdStrings.RemoteRunspaceNotAvailableForSpecifiedSessionId, + tooManyResourceString: RemotingErrorIdStrings.RemoteRunspaceHasMultipleMatchesForSpecifiedSessionId, + errorArgument: sessionId); } /// @@ -817,16 +819,13 @@ private RemoteRunspace GetRunspaceMatchingSessionId(int sessionId) /// private RemoteRunspace GetRunspaceMatchingName(string name) { - Predicate condition = (PSSession info) => - { - // doing case-insensitive match for session name - return info.Name.Equals(name, StringComparison.OrdinalIgnoreCase); - }; - PSRemotingErrorId tooFew = PSRemotingErrorId.RemoteRunspaceNotAvailableForSpecifiedName; - PSRemotingErrorId tooMany = PSRemotingErrorId.RemoteRunspaceHasMultipleMatchesForSpecifiedName; - string tooFewResourceString = RemotingErrorIdStrings.RemoteRunspaceNotAvailableForSpecifiedName; - string tooManyResourceString = RemotingErrorIdStrings.RemoteRunspaceHasMultipleMatchesForSpecifiedName; - return GetRunspaceMatchingCondition(condition, tooFew, tooMany, tooFewResourceString, tooManyResourceString, name); + return GetRunspaceMatchingCondition( + condition: info => info.Name.Equals(name, StringComparison.OrdinalIgnoreCase), + tooFew: PSRemotingErrorId.RemoteRunspaceNotAvailableForSpecifiedName, + tooMany: PSRemotingErrorId.RemoteRunspaceHasMultipleMatchesForSpecifiedName, + tooFewResourceString: RemotingErrorIdStrings.RemoteRunspaceNotAvailableForSpecifiedName, + tooManyResourceString: RemotingErrorIdStrings.RemoteRunspaceHasMultipleMatchesForSpecifiedName, + errorArgument: name); } private Job FindJobForRunspace(Guid id) @@ -1084,7 +1083,7 @@ private RemoteRunspace GetRunspaceForVMSession() /// /// Create temporary remote runspace. /// - private RemoteRunspace CreateTemporaryRemoteRunspaceForPowerShellDirect(PSHost host, RunspaceConnectionInfo connectionInfo) + private static RemoteRunspace CreateTemporaryRemoteRunspaceForPowerShellDirect(PSHost host, RunspaceConnectionInfo connectionInfo) { // Create and open the runspace. TypeTable typeTable = TypeTable.LoadDefaultTypeFiles(); diff --git a/src/System.Management.Automation/engine/remoting/commands/ReceivePSSession.cs b/src/System.Management.Automation/engine/remoting/commands/ReceivePSSession.cs index faf8bfdaa00..12cced4ae91 100644 --- a/src/System.Management.Automation/engine/remoting/commands/ReceivePSSession.cs +++ b/src/System.Management.Automation/engine/remoting/commands/ReceivePSSession.cs @@ -1115,7 +1115,7 @@ private void ConnectSessionToJob(PSSession session, PSRemotingJob job = null) /// Session to connect. /// Optional exception object. /// Connected session or null. - private PSSession ConnectSession(PSSession session, out Exception ex) + private static PSSession ConnectSession(PSSession session, out Exception ex) { ex = null; diff --git a/src/System.Management.Automation/engine/remoting/commands/RemoveJob.cs b/src/System.Management.Automation/engine/remoting/commands/RemoveJob.cs index 51fe75b19bc..f8c0a71a0df 100644 --- a/src/System.Management.Automation/engine/remoting/commands/RemoveJob.cs +++ b/src/System.Management.Automation/engine/remoting/commands/RemoveJob.cs @@ -540,7 +540,7 @@ internal List FindJobsMatchingByFilter(bool writeobject) /// /// /// - private bool FindJobsMatchingByFilterHelper(List matches, List jobsToSearch) + private static bool FindJobsMatchingByFilterHelper(List matches, List jobsToSearch) { // check that filter only has job properties // if so, filter on one at a time using helpers. diff --git a/src/System.Management.Automation/engine/remoting/commands/newrunspacecommand.cs b/src/System.Management.Automation/engine/remoting/commands/newrunspacecommand.cs index a6342196fa8..3122d7e1176 100644 --- a/src/System.Management.Automation/engine/remoting/commands/newrunspacecommand.cs +++ b/src/System.Management.Automation/engine/remoting/commands/newrunspacecommand.cs @@ -530,7 +530,7 @@ private void HandleRunspaceStateChanged(object sender, OperationStateEventArgs s transErrorCode, _defaultFQEID); - if (WSManNativeApi.ERROR_WSMAN_NO_LOGON_SESSION_EXIST == transErrorCode) + if (transErrorCode == WSManNativeApi.ERROR_WSMAN_NO_LOGON_SESSION_EXIST) { errorDetails += System.Environment.NewLine + string.Format(System.Globalization.CultureInfo.CurrentCulture, RemotingErrorIdStrings.RemotingErrorNoLogonSessionExist); } @@ -661,7 +661,7 @@ private List CreateRunspacesWhenRunspaceParameterSpecified() if (originalWSManConnectionInfo != null) { newWSManConnectionInfo = originalWSManConnectionInfo.Copy(); - newWSManConnectionInfo.EnableNetworkAccess = (newWSManConnectionInfo.EnableNetworkAccess || EnableNetworkAccess) ? true : false; + newWSManConnectionInfo.EnableNetworkAccess = newWSManConnectionInfo.EnableNetworkAccess || EnableNetworkAccess; newConnectionInfo = newWSManConnectionInfo; } else diff --git a/src/System.Management.Automation/engine/remoting/commands/remotingcommandutil.cs b/src/System.Management.Automation/engine/remoting/commands/remotingcommandutil.cs index 2537abe6369..094dcedc6ad 100644 --- a/src/System.Management.Automation/engine/remoting/commands/remotingcommandutil.cs +++ b/src/System.Management.Automation/engine/remoting/commands/remotingcommandutil.cs @@ -87,7 +87,7 @@ internal static void CheckRemotingCmdletPrerequisites() return; #else bool notSupported = true; - string WSManKeyPath = "Software\\Microsoft\\Windows\\CurrentVersion\\WSMAN\\"; + const string WSManKeyPath = "Software\\Microsoft\\Windows\\CurrentVersion\\WSMAN\\"; CheckHostRemotingPrerequisites(); diff --git a/src/System.Management.Automation/engine/remoting/common/Indexer.cs b/src/System.Management.Automation/engine/remoting/common/Indexer.cs index 243a1580ea5..019eb9dfce4 100644 --- a/src/System.Management.Automation/engine/remoting/common/Indexer.cs +++ b/src/System.Management.Automation/engine/remoting/common/Indexer.cs @@ -49,7 +49,7 @@ internal Indexer(int[] lengths) /// Check lengths non negative. /// [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] - private bool CheckLengthsNonNegative(int[] lengths) + private static bool CheckLengthsNonNegative(int[] lengths) { for (int i = 0; i < lengths.Length; ++i) { diff --git a/src/System.Management.Automation/engine/remoting/common/RemoteSessionNamedPipe.cs b/src/System.Management.Automation/engine/remoting/common/RemoteSessionNamedPipe.cs index d50b7989b66..6f520e0ac26 100644 --- a/src/System.Management.Automation/engine/remoting/common/RemoteSessionNamedPipe.cs +++ b/src/System.Management.Automation/engine/remoting/common/RemoteSessionNamedPipe.cs @@ -466,7 +466,7 @@ internal RemoteSessionNamedPipeServer( /// Named pipe core name. /// /// NamedPipeServerStream. - private NamedPipeServerStream CreateNamedPipe( + private static NamedPipeServerStream CreateNamedPipe( string serverName, string namespaceName, string coreName, @@ -1291,9 +1291,6 @@ public ContainerSessionNamedPipeClient( /// protected override NamedPipeClientStream DoConnect(int timeout) { - // Create pipe flags. - uint pipeFlags = NamedPipeNative.FILE_FLAG_OVERLAPPED; - // // WaitNamedPipe API is not supported by Windows Server container now, so we need to repeatedly // attempt connection to pipe server until timeout expires. @@ -1306,13 +1303,13 @@ protected override NamedPipeClientStream DoConnect(int timeout) { // Get handle to pipe. pipeHandle = NamedPipeNative.CreateFile( - _pipeName, - NamedPipeNative.GENERIC_READ | NamedPipeNative.GENERIC_WRITE, - 0, - IntPtr.Zero, - NamedPipeNative.OPEN_EXISTING, - pipeFlags, - IntPtr.Zero); + lpFileName: _pipeName, + dwDesiredAccess: NamedPipeNative.GENERIC_READ | NamedPipeNative.GENERIC_WRITE, + dwShareMode: 0, + SecurityAttributes: IntPtr.Zero, + dwCreationDisposition: NamedPipeNative.OPEN_EXISTING, + dwFlagsAndAttributes: NamedPipeNative.FILE_FLAG_OVERLAPPED, + hTemplateFile: IntPtr.Zero); int lastError = Marshal.GetLastWin32Error(); if (pipeHandle.IsInvalid) diff --git a/src/System.Management.Automation/engine/remoting/common/RunspaceConnectionInfo.cs b/src/System.Management.Automation/engine/remoting/common/RunspaceConnectionInfo.cs index 6b4e91efae3..9debc89ce76 100644 --- a/src/System.Management.Automation/engine/remoting/common/RunspaceConnectionInfo.cs +++ b/src/System.Management.Automation/engine/remoting/common/RunspaceConnectionInfo.cs @@ -642,7 +642,7 @@ public override string CertificateThumbprint public bool UseCompression { get; set; } = true; /// - /// If true then Operating System won't load the user profile (i.e. registry keys under HKCU) on the remote server + /// If then Operating System won't load the user profile (i.e. registry keys under HKCU) on the remote server /// which can result in a faster session creation time. This option won't have any effect if the remote machine has /// already loaded the profile (i.e. in another session). /// @@ -1096,7 +1096,7 @@ internal override BaseClientSessionTransportManager CreateClientSessionTransport #region Private Methods - private string ResolveShellUri(string shell) + private static string ResolveShellUri(string shell) { string resolvedShellUri = shell; if (string.IsNullOrEmpty(resolvedShellUri)) @@ -2050,9 +2050,9 @@ internal int StartSSHProcess( { string filePath = string.Empty; #if UNIX - string sshCommand = "ssh"; + const string sshCommand = "ssh"; #else - string sshCommand = "ssh.exe"; + const string sshCommand = "ssh.exe"; #endif var context = Runspaces.LocalPipeline.GetExecutionContextFromTLS(); if (context != null) @@ -2297,7 +2297,7 @@ private static string[] ParseArgv(ProcessStartInfo psi) case '"': // Special case for arguments within quotes // Just return argument value within the quotes - while ((++i < argsLength) && argsToParse[i] != '"') { }; + while ((++i < argsLength) && argsToParse[i] != '"') { } if (iStart < argsLength - 1) { iStart++; @@ -2307,12 +2307,12 @@ private static string[] ParseArgv(ProcessStartInfo psi) default: // Common case for parsing arguments with space character delimiter - while ((++i < argsLength) && argsToParse[i] != ' ') { }; + while ((++i < argsLength) && argsToParse[i] != ' ') { } break; } argvList.Add(argsToParse.Substring(iStart, (i-iStart))); - while ((++i < argsLength) && argsToParse[i] == ' ') { }; + while ((++i < argsLength) && argsToParse[i] == ' ') { } } return argvList.ToArray(); @@ -2625,21 +2625,15 @@ private static Process CreateProcessWithRedirectedStd( private static SafePipeHandle GetNamedPipeHandle(string pipeName) { - // Create pipe flags for asynchronous pipes. - uint pipeFlags = NamedPipeNative.FILE_FLAG_OVERLAPPED; - - // We want an inheritable handle. - PlatformInvokes.SECURITY_ATTRIBUTES securityAttributes = new PlatformInvokes.SECURITY_ATTRIBUTES(); - // Get handle to pipe. var fileHandle = PlatformInvokes.CreateFileW( - pipeName, - NamedPipeNative.GENERIC_READ | NamedPipeNative.GENERIC_WRITE, - 0, - securityAttributes, - NamedPipeNative.OPEN_EXISTING, - pipeFlags, - IntPtr.Zero); + lpFileName: pipeName, + dwDesiredAccess: NamedPipeNative.GENERIC_READ | NamedPipeNative.GENERIC_WRITE, + dwShareMode: 0, + lpSecurityAttributes: new PlatformInvokes.SECURITY_ATTRIBUTES(), // Create an inheritable handle. + dwCreationDisposition: NamedPipeNative.OPEN_EXISTING, + dwFlagsAndAttributes: NamedPipeNative.FILE_FLAG_OVERLAPPED, // Open in asynchronous mode. + hTemplateFile: IntPtr.Zero); int lastError = Marshal.GetLastWin32Error(); if (fileHandle == PlatformInvokes.INVALID_HANDLE_VALUE) @@ -3458,7 +3452,7 @@ private void GetContainerPropertiesInternal() } } - if (ContainerObRoot == null) + if (ContainerObRoot == null) { throw new PSInvalidOperationException(RemotingErrorIdStrings.CannotGetHostInteropTypes); } @@ -3493,7 +3487,7 @@ private void GetContainerPropertiesInternal() /// /// Run some tasks on MTA thread if needed. /// - private void RunOnMTAThread(ThreadStart threadProc) + private static void RunOnMTAThread(ThreadStart threadProc) { if (Thread.CurrentThread.GetApartmentState() == ApartmentState.MTA) { @@ -3512,7 +3506,7 @@ private void RunOnMTAThread(ThreadStart threadProc) /// /// Get error message from the thrown exception. /// - private string GetErrorMessageFromException(Exception e) + private static string GetErrorMessageFromException(Exception e) { string errorMessage = e.Message; diff --git a/src/System.Management.Automation/engine/remoting/common/WireDataFormat/EncodeAndDecode.cs b/src/System.Management.Automation/engine/remoting/common/WireDataFormat/EncodeAndDecode.cs index fc011b313e2..03a3cd51a87 100644 --- a/src/System.Management.Automation/engine/remoting/common/WireDataFormat/EncodeAndDecode.cs +++ b/src/System.Management.Automation/engine/remoting/common/WireDataFormat/EncodeAndDecode.cs @@ -1196,10 +1196,10 @@ internal static RemoteDataObject GenerateRunspacePoolStateInfo( // Add Reason property if (stateInfo.Reason != null) { - // If Reason is of not type IContainsErrorRecord, a new ErrorRecord is - // created using this errorId - string errorId = "RemoteRunspaceStateInfoReason"; - PSNoteProperty exceptionProperty = GetExceptionProperty(stateInfo.Reason, errorId, ErrorCategory.NotSpecified); + PSNoteProperty exceptionProperty = GetExceptionProperty( + exception: stateInfo.Reason, + errorId: "RemoteRunspaceStateInfoReason", + category: ErrorCategory.NotSpecified); dataAsPSObject.Properties.Add(exceptionProperty); } @@ -1515,12 +1515,10 @@ internal static RemoteDataObject GeneratePowerShellStateInfo(PSInvocationStateIn // Add exception property if (stateInfo.Reason != null) { - // If Reason is of not type IContainsErrorRecord, - // a new ErrorRecord is created using this errorId - string errorId = "RemotePSInvocationStateInfoReason"; - PSNoteProperty exceptionProperty = - GetExceptionProperty(stateInfo.Reason, errorId, - ErrorCategory.NotSpecified); + PSNoteProperty exceptionProperty = GetExceptionProperty( + exception: stateInfo.Reason, + errorId: "RemotePSInvocationStateInfoReason", + category: ErrorCategory.NotSpecified); dataAsPSObject.Properties.Add(exceptionProperty); } @@ -1563,6 +1561,9 @@ internal static ErrorRecord GetErrorRecordFromException(Exception exception) /// /// Gets a Note Property for the exception. /// + /// + /// If is of not type IContainsErrorRecord, a new ErrorRecord is created. + /// /// /// ErrorId to use if exception is not of type IContainsErrorRecord. /// ErrorCategory to use if exception is not of type IContainsErrorRecord. @@ -2236,7 +2237,7 @@ internal static PowerShell GetCommandDiscoveryPipeline(object data) } else { - module = new string[] { "" }; + module = new string[] { string.Empty }; } ModuleSpecification[] fullyQualifiedName = null; @@ -2280,7 +2281,7 @@ internal static PowerShell GetCommandDiscoveryPipeline(object data) /// Gets the NoInput setting from the specified data. /// /// Data to decode. - /// true if there is no pipeline input; false otherwise. + /// if there is no pipeline input; otherwise. internal static bool GetNoInput(object data) { PSObject dataAsPSObject = PSObject.AsPSObject(data); @@ -2297,7 +2298,7 @@ internal static bool GetNoInput(object data) /// Gets the AddToHistory setting from the specified data. /// /// Data to decode. - /// true if there is addToHistory data; false otherwise. + /// if there is addToHistory data; otherwise. internal static bool GetAddToHistory(object data) { PSObject dataAsPSObject = PSObject.AsPSObject(data); @@ -2314,7 +2315,7 @@ internal static bool GetAddToHistory(object data) /// Gets the IsNested setting from the specified data. /// /// Data to decode. - /// true if there is IsNested data; false otherwise. + /// if there is IsNested data; otherwise. internal static bool GetIsNested(object data) { PSObject dataAsPSObject = PSObject.AsPSObject(data); diff --git a/src/System.Management.Automation/engine/remoting/common/WireDataFormat/RemoteHost.cs b/src/System.Management.Automation/engine/remoting/common/WireDataFormat/RemoteHost.cs index f0f37381e7c..c29be13487b 100644 --- a/src/System.Management.Automation/engine/remoting/common/WireDataFormat/RemoteHost.cs +++ b/src/System.Management.Automation/engine/remoting/common/WireDataFormat/RemoteHost.cs @@ -198,7 +198,7 @@ internal void ExecuteVoidMethod(PSHost clientHost) /// /// Get remote runspace to close. /// - private RemoteRunspace GetRemoteRunspaceToClose(PSHost clientHost) + private static RemoteRunspace GetRemoteRunspaceToClose(PSHost clientHost) { // Figure out if we need to close the remote runspace. Return null if we don't. @@ -440,7 +440,7 @@ internal Collection PerformSecurityChecksOnHostMessage(string co /// /// Caption to modify. /// New modified caption. - private string ModifyCaption(string caption) + private static string ModifyCaption(string caption) { string pscaption = CredUI.PromptForCredential_DefaultCaption; @@ -465,7 +465,7 @@ private string ModifyCaption(string caption) /// computername to include in the /// message /// Message which contains a warning as well. - private string ModifyMessage(string message, string computerName) + private static string ModifyMessage(string message, string computerName) { string modifiedMessage = PSRemotingErrorInvariants.FormatResourceString( RemotingErrorIdStrings.RemoteHostPromptForCredentialModifiedMessage, @@ -485,7 +485,7 @@ private string ModifyMessage(string message, string computerName) /// Resource string to use. /// A constructed remote host call message /// which will display the warning. - private RemoteHostCall ConstructWarningMessageForSecureString(string computerName, + private static RemoteHostCall ConstructWarningMessageForSecureString(string computerName, string resourceString) { string warning = PSRemotingErrorInvariants.FormatResourceString( @@ -506,7 +506,7 @@ private RemoteHostCall ConstructWarningMessageForSecureString(string computerNam /// in warning /// A constructed remote host call message /// which will display the warning. - private RemoteHostCall ConstructWarningMessageForGetBufferContents(string computerName) + private static RemoteHostCall ConstructWarningMessageForGetBufferContents(string computerName) { string warning = PSRemotingErrorInvariants.FormatResourceString( RemotingErrorIdStrings.RemoteHostGetBufferContents, diff --git a/src/System.Management.Automation/engine/remoting/common/WireDataFormat/RemotingDataObject.cs b/src/System.Management.Automation/engine/remoting/common/WireDataFormat/RemotingDataObject.cs index 664c2a91ae0..0fed6cc759d 100644 --- a/src/System.Management.Automation/engine/remoting/common/WireDataFormat/RemotingDataObject.cs +++ b/src/System.Management.Automation/engine/remoting/common/WireDataFormat/RemotingDataObject.cs @@ -213,7 +213,7 @@ private void SerializeHeader(Stream streamToWriteTo) return; } - private void SerializeUInt(uint data, Stream streamToWriteTo) + private static void SerializeUInt(uint data, Stream streamToWriteTo) { Dbg.Assert(streamToWriteTo != null, "stream to write to cannot be null"); @@ -241,7 +241,7 @@ private static uint DeserializeUInt(Stream serializedDataStream) return result; } - private void SerializeGuid(Guid guid, Stream streamToWriteTo) + private static void SerializeGuid(Guid guid, Stream streamToWriteTo) { Dbg.Assert(streamToWriteTo != null, "stream to write to cannot be null"); diff --git a/src/System.Management.Automation/engine/remoting/common/fragmentor.cs b/src/System.Management.Automation/engine/remoting/common/fragmentor.cs index 87543552c53..4685af1e75d 100644 --- a/src/System.Management.Automation/engine/remoting/common/fragmentor.cs +++ b/src/System.Management.Automation/engine/remoting/common/fragmentor.cs @@ -105,7 +105,7 @@ internal FragmentedRemoteObject(byte[] blob, long objectId, long fragmentId, ObjectId = objectId; FragmentId = fragmentId; - IsStartFragment = (fragmentId == 0) ? true : false; + IsStartFragment = fragmentId == 0; IsEndFragment = isEndFragment; _blob = blob; @@ -205,10 +205,10 @@ internal byte[] Blob /// internal byte[] GetBytes() { - int objectIdSize = 8; // number of bytes of long - int fragmentIdSize = 8; // number of bytes of long - int flagsSize = 1; // 1 byte for IsEndOfFrag and IsControl - int blobLengthSize = 4; // number of bytes of int + const int objectIdSize = 8; // number of bytes of long + const int fragmentIdSize = 8; // number of bytes of long + const int flagsSize = 1; // 1 byte for IsEndOfFrag and IsControl + const int blobLengthSize = 4; // number of bytes of int int totalLength = objectIdSize + fragmentIdSize + flagsSize + blobLengthSize + BlobLength; @@ -883,9 +883,11 @@ protected override void Dispose(bool disposing) /// /// public override bool CanRead { get { return true; } } + /// /// public override bool CanSeek { get { return false; } } + /// /// public override bool CanWrite { get { return true; } } @@ -893,6 +895,7 @@ protected override void Dispose(bool disposing) /// Gets the length of the stream in bytes. /// public override long Length { get { return _length; } } + /// /// public override long Position @@ -908,6 +911,7 @@ public override long Position public override void Flush() { } + /// /// /// @@ -917,6 +921,7 @@ public override long Seek(long offset, SeekOrigin origin) { throw new NotSupportedException(); } + /// /// /// diff --git a/src/System.Management.Automation/engine/remoting/common/psstreamobject.cs b/src/System.Management.Automation/engine/remoting/common/psstreamobject.cs index cb985ac5ed0..3419bde7966 100644 --- a/src/System.Management.Automation/engine/remoting/common/psstreamobject.cs +++ b/src/System.Management.Automation/engine/remoting/common/psstreamobject.cs @@ -75,7 +75,9 @@ public class PSStreamObject /// /// public PSStreamObjectType ObjectType { get; set; } + internal object Value { get; set; } + internal Guid Id { get; set; } internal PSStreamObject(PSStreamObjectType objectType, object value, Guid id) diff --git a/src/System.Management.Automation/engine/remoting/common/throttlemanager.cs b/src/System.Management.Automation/engine/remoting/common/throttlemanager.cs index cf742cdba7d..afccc28362a 100644 --- a/src/System.Management.Automation/engine/remoting/common/throttlemanager.cs +++ b/src/System.Management.Automation/engine/remoting/common/throttlemanager.cs @@ -675,9 +675,9 @@ internal class Operation : IThrottleOperation private Thread workerThreadStart; private Thread workerThreadStop; - public bool Done { set; get; } + public bool Done { get; set; } - public int SleepTime { set; get; } = 100; + public int SleepTime { get; set; } = 100; private void WorkerThreadMethodStart() { diff --git a/src/System.Management.Automation/engine/remoting/fanin/BaseTransportManager.cs b/src/System.Management.Automation/engine/remoting/fanin/BaseTransportManager.cs index aa496990dd8..5d12914074c 100644 --- a/src/System.Management.Automation/engine/remoting/fanin/BaseTransportManager.cs +++ b/src/System.Management.Automation/engine/remoting/fanin/BaseTransportManager.cs @@ -97,7 +97,7 @@ internal enum ConnectionStatus AutoDisconnectStarting = 4, AutoDisconnectSucceeded = 5, InternalErrorAbort = 6 - }; + } /// /// ConnectionStatusEventArgs. @@ -757,7 +757,7 @@ internal void EnqueueAndStartProcessingThread(RemoteDataObject remoteO /// /// Remote data object. /// True if remote data object requires a user response. - private bool CheckForInteractiveHostCall(RemoteDataObject remoteObject) + private static bool CheckForInteractiveHostCall(RemoteDataObject remoteObject) { bool interactiveHostCall = false; @@ -972,7 +972,7 @@ internal virtual void PrepareForConnect() #region Clean up /// - /// Finalizer. + /// Finalizes an instance of the class. /// ~BaseClientTransportManager() { @@ -1524,7 +1524,7 @@ internal static byte[] ExtractEncodedXmlElement(string xmlBuffer, string xmlTag) XmlReader reader = XmlReader.Create(new StringReader(xmlBuffer), readerSettings); string additionalData; - if (XmlNodeType.Element == reader.MoveToContent()) + if (reader.MoveToContent() == XmlNodeType.Element) { additionalData = reader.ReadElementContentAsString(xmlTag, reader.NamespaceURI); } diff --git a/src/System.Management.Automation/engine/remoting/fanin/InitialSessionStateProvider.cs b/src/System.Management.Automation/engine/remoting/fanin/InitialSessionStateProvider.cs index 2914d42af3d..6cde06cea36 100644 --- a/src/System.Management.Automation/engine/remoting/fanin/InitialSessionStateProvider.cs +++ b/src/System.Management.Automation/engine/remoting/fanin/InitialSessionStateProvider.cs @@ -157,7 +157,7 @@ private void Update(string optionName, string optionValue) /// /// 1. "optionName" is already defined /// - private void AssertValueNotAssigned(string optionName, object originalValue) + private static void AssertValueNotAssigned(string optionName, object originalValue) { if (originalValue != null) { @@ -401,7 +401,7 @@ public virtual InitialSessionState GetInitialSessionState(PSSessionConfiguration /// /// User Identity for which this information is requested /// - /// Application private data or null + /// Application private data or public virtual PSPrimitiveDictionary GetApplicationPrivateData(PSSenderInfo senderInfo) { return null; @@ -1896,7 +1896,7 @@ private void MergeConfigHashIntoConfigHash(IDictionary childConfigHash) } } - private string GetRoleCapabilityPath(string roleCapability) + private static string GetRoleCapabilityPath(string roleCapability) { string moduleName = "*"; if (roleCapability.Contains('\\')) @@ -2395,7 +2395,7 @@ public override InitialSessionState GetInitialSessionState(PSSenderInfo senderIn if (Convert.ToBoolean(_configHash[ConfigFileConstants.MountUserDrive], CultureInfo.InvariantCulture)) { iss.UserDriveEnabled = true; - iss.UserDriveUserName = (senderInfo != null) ? senderInfo.UserInfo.Identity.Name : null; + iss.UserDriveUserName = senderInfo?.UserInfo.Identity.Name; // Set user drive max drive if provided. if (_configHash.ContainsKey(ConfigFileConstants.UserDriveMaxSize)) @@ -2620,7 +2620,7 @@ private static void ProcessVisibleCommand(InitialSessionState iss, string comman /// /// Creates an alias entry. /// - private SessionStateAliasEntry CreateSessionStateAliasEntry(Hashtable alias, bool isAliasVisibilityDefined) + private static SessionStateAliasEntry CreateSessionStateAliasEntry(Hashtable alias, bool isAliasVisibilityDefined) { string name = TryGetValue(alias, ConfigFileConstants.AliasNameToken); @@ -2660,7 +2660,7 @@ private SessionStateAliasEntry CreateSessionStateAliasEntry(Hashtable alias, boo /// Creates a function entry. /// /// - private SessionStateFunctionEntry CreateSessionStateFunctionEntry(Hashtable function, bool isFunctionVisibilityDefined) + private static SessionStateFunctionEntry CreateSessionStateFunctionEntry(Hashtable function, bool isFunctionVisibilityDefined) { string name = TryGetValue(function, ConfigFileConstants.FunctionNameToken); @@ -2700,7 +2700,7 @@ private SessionStateFunctionEntry CreateSessionStateFunctionEntry(Hashtable func /// /// Creates a variable entry. /// - private SessionStateVariableEntry CreateSessionStateVariableEntry(Hashtable variable, PSLanguageMode languageMode) + private static SessionStateVariableEntry CreateSessionStateVariableEntry(Hashtable variable, PSLanguageMode languageMode) { string name = TryGetValue(variable, ConfigFileConstants.VariableNameToken); diff --git a/src/System.Management.Automation/engine/remoting/fanin/OutOfProcTransportManager.cs b/src/System.Management.Automation/engine/remoting/fanin/OutOfProcTransportManager.cs index 8cd28d17845..b8f6da13c17 100644 --- a/src/System.Management.Automation/engine/remoting/fanin/OutOfProcTransportManager.cs +++ b/src/System.Management.Automation/engine/remoting/fanin/OutOfProcTransportManager.cs @@ -144,12 +144,19 @@ private static string CreatePSGuidPacket(string element, Guid psGuid) #region Packet Processing Helper Methods / Delegates internal delegate void DataPacketReceived(byte[] rawData, string stream, Guid psGuid); + internal delegate void DataAckPacketReceived(Guid psGuid); + internal delegate void CommandCreationPacketReceived(Guid psGuid); + internal delegate void CommandCreationAckReceived(Guid psGuid); + internal delegate void ClosePacketReceived(Guid psGuid); + internal delegate void CloseAckPacketReceived(Guid psGuid); + internal delegate void SignalPacketReceived(Guid psGuid); + internal delegate void SignalAckPacketReceived(Guid psGuid); internal struct DataProcessingDelegates diff --git a/src/System.Management.Automation/engine/remoting/fanin/PSSessionConfigurationData.cs b/src/System.Management.Automation/engine/remoting/fanin/PSSessionConfigurationData.cs index 17aac7adfdf..6da557cca40 100644 --- a/src/System.Management.Automation/engine/remoting/fanin/PSSessionConfigurationData.cs +++ b/src/System.Management.Automation/engine/remoting/fanin/PSSessionConfigurationData.cs @@ -18,7 +18,9 @@ public sealed class PSSessionConfigurationData { /// /// +#pragma warning disable CA2211 // Non-constant fields should not be visible public static bool IsServerManager; +#pragma warning restore CA2211 // Non-constant fields should not be visible #region Public Properties diff --git a/src/System.Management.Automation/engine/remoting/fanin/PriorityCollection.cs b/src/System.Management.Automation/engine/remoting/fanin/PriorityCollection.cs index d354574c37b..1bf8afd3dd1 100644 --- a/src/System.Management.Automation/engine/remoting/fanin/PriorityCollection.cs +++ b/src/System.Management.Automation/engine/remoting/fanin/PriorityCollection.cs @@ -163,8 +163,8 @@ Verify arrays and dataToBeSent objects before referencing. */ if (_dataSyncObjects != null && _dataToBeSent != null) { - int promptResponseIndex = (int)DataPriorityType.PromptResponse; - int defaultIndex = (int)DataPriorityType.Default; + const int promptResponseIndex = (int)DataPriorityType.PromptResponse; + const int defaultIndex = (int)DataPriorityType.Default; lock (_dataSyncObjects[promptResponseIndex]) { diff --git a/src/System.Management.Automation/engine/remoting/fanin/WSManNativeAPI.cs b/src/System.Management.Automation/engine/remoting/fanin/WSManNativeAPI.cs index 404dd3b576d..6dd3614a62f 100644 --- a/src/System.Management.Automation/engine/remoting/fanin/WSManNativeAPI.cs +++ b/src/System.Management.Automation/engine/remoting/fanin/WSManNativeAPI.cs @@ -192,7 +192,7 @@ internal static MarshalledObject Create(T obj) /// public void Dispose() { - if (IntPtr.Zero != _dataPtr) + if (_dataPtr != IntPtr.Zero) { Marshal.FreeHGlobal(_dataPtr); _dataPtr = IntPtr.Zero; @@ -612,7 +612,7 @@ internal enum WSManDataType : uint WSMAN_DATA_TYPE_BINARY = 2, WSMAN_DATA_TYPE_WS_XML_READER = 3, WSMAN_DATA_TYPE_DWORD = 4 - }; + } [StructLayout(LayoutKind.Sequential)] internal class WSManDataStruct @@ -687,18 +687,6 @@ internal WSManData_ManToUn(string data) Marshal.StructureToPtr(_internalData, _marshalledObject, false); } - /// - /// Finalizer - /// - /// Note: Do not depend on the finalizer! This object should be - /// properly disposed of when no longer needed via a direct call - /// to Dispose(). - /// - ~WSManData_ManToUn() - { - Dispose(false); - } - /// /// Gets the type of data. /// @@ -747,6 +735,14 @@ private void Dispose(bool isDisposing) } } + /// + /// Finalizes an instance of the class. + /// + ~WSManData_ManToUn() + { + Dispose(false); + } + /// /// Implicit IntPtr conversion. /// @@ -869,7 +865,7 @@ internal static WSManData_UnToMan UnMarshal(IntPtr unmanagedData) { WSManData_UnToMan result = null; - if (IntPtr.Zero != unmanagedData) + if (unmanagedData != IntPtr.Zero) { WSManDataStruct resultInternal = Marshal.PtrToStructure(unmanagedData); result = WSManData_UnToMan.UnMarshal(resultInternal); @@ -972,7 +968,7 @@ internal WSManStreamIDSet_ManToUn(string[] streamIds) /// internal void Dispose() { - if (IntPtr.Zero != _streamSetInfo.streamIDs) + if (_streamSetInfo.streamIDs != IntPtr.Zero) { int sizeOfIntPtr = Marshal.SizeOf(); for (int index = 0; index < _streamSetInfo.streamIDsCount; index++) @@ -980,7 +976,7 @@ internal void Dispose() IntPtr streamAddress = IntPtr.Zero; streamAddress = Marshal.ReadIntPtr(_streamSetInfo.streamIDs, index * sizeOfIntPtr); - if (IntPtr.Zero != streamAddress) + if (streamAddress != IntPtr.Zero) { Marshal.FreeHGlobal(streamAddress); streamAddress = IntPtr.Zero; @@ -1019,7 +1015,7 @@ internal static WSManStreamIDSet_UnToMan UnMarshal(IntPtr unmanagedData) { WSManStreamIDSet_UnToMan result = null; - if (IntPtr.Zero != unmanagedData) + if (unmanagedData != IntPtr.Zero) { WSManStreamIDSetStruct resultInternal = Marshal.PtrToStructure(unmanagedData); @@ -1140,7 +1136,7 @@ internal WSManOptionSet(WSManOption[] options) /// public void Dispose() { - if (IntPtr.Zero != _optionSet.options) + if (_optionSet.options != IntPtr.Zero) { Marshal.FreeHGlobal(_optionSet.options); _optionSet.options = IntPtr.Zero; @@ -1174,7 +1170,7 @@ public static implicit operator IntPtr(WSManOptionSet optionSet) /// internal static WSManOptionSet UnMarshal(IntPtr unmanagedData) { - if (IntPtr.Zero == unmanagedData) + if (unmanagedData == IntPtr.Zero) { return new WSManOptionSet(); } @@ -1264,7 +1260,7 @@ internal WSManCommandArgSet(byte[] firstArgument) public void Dispose() { IntPtr firstArgAddress = Marshal.ReadIntPtr(_internalData.args); - if (IntPtr.Zero != firstArgAddress) + if (firstArgAddress != IntPtr.Zero) { Marshal.FreeHGlobal(firstArgAddress); } @@ -1302,7 +1298,7 @@ internal static WSManCommandArgSet UnMarshal(IntPtr unmanagedData) { WSManCommandArgSet result = new WSManCommandArgSet(); - if (IntPtr.Zero != unmanagedData) + if (unmanagedData != IntPtr.Zero) { WSManCommandArgSetInternal resultInternal = Marshal.PtrToStructure(unmanagedData); @@ -1486,7 +1482,7 @@ internal static WSManShellStartupInfo_UnToMan UnMarshal(IntPtr unmanagedData) { WSManShellStartupInfo_UnToMan result = null; - if (IntPtr.Zero != unmanagedData) + if (unmanagedData != IntPtr.Zero) { WSManShellStartupInfoStruct resultInternal = Marshal.PtrToStructure(unmanagedData); @@ -1522,7 +1518,7 @@ internal static WSManEnvironmentVariableSet UnMarshal(IntPtr unmanagedData) { WSManEnvironmentVariableSet result = null; - if (IntPtr.Zero != unmanagedData) + if (unmanagedData != IntPtr.Zero) { WSManEnvironmentVariableSetInternal resultInternal = Marshal.PtrToStructure(unmanagedData); @@ -1841,7 +1837,7 @@ internal static WSManCreateShellDataResult UnMarshal(IntPtr unmanagedData) { WSManCreateShellDataResult result = new WSManCreateShellDataResult(); - if (IntPtr.Zero != unmanagedData) + if (unmanagedData != IntPtr.Zero) { WSManCreateShellDataResultInternal resultInternal = Marshal.PtrToStructure(unmanagedData); @@ -2058,7 +2054,7 @@ internal static WSManPluginRequest UnMarshal(IntPtr unmanagedData) // Dbg.Assert(IntPtr.Zero != unmanagedData, "unmanagedData must be non-null. This means WinRM sent a bad pointer."); WSManPluginRequest result = null; - if (IntPtr.Zero != unmanagedData) + if (unmanagedData != IntPtr.Zero) { WSManPluginRequestInternal resultInternal = Marshal.PtrToStructure(unmanagedData); @@ -2116,7 +2112,7 @@ internal static WSManSenderDetails UnMarshal(IntPtr unmanagedData) { WSManSenderDetails result = null; - if (IntPtr.Zero != unmanagedData) + if (unmanagedData != IntPtr.Zero) { WSManSenderDetailsInternal resultInternal = Marshal.PtrToStructure(unmanagedData); @@ -2169,7 +2165,7 @@ internal static WSManCertificateDetails UnMarshal(IntPtr unmanagedData) { WSManCertificateDetails result = null; - if (IntPtr.Zero != unmanagedData) + if (unmanagedData != IntPtr.Zero) { WSManCertificateDetailsInternal resultInternal = Marshal.PtrToStructure(unmanagedData); @@ -2218,7 +2214,7 @@ internal static WSManOperationInfo UnMarshal(IntPtr unmanagedData) { WSManOperationInfo result = null; - if (IntPtr.Zero != unmanagedData) + if (unmanagedData != IntPtr.Zero) { WSManOperationInfoInternal resultInternal = Marshal.PtrToStructure(unmanagedData); @@ -2459,15 +2455,15 @@ internal static extern int WSManGetSessionOptionAsDword(IntPtr wsManSessionHandl internal static string WSManGetSessionOptionAsString(IntPtr wsManAPIHandle, WSManSessionOption option) { - Dbg.Assert(IntPtr.Zero != wsManAPIHandle, "wsManAPIHandle cannot be null."); + Dbg.Assert(wsManAPIHandle != IntPtr.Zero, "wsManAPIHandle cannot be null."); // The error code taken from winerror.h used for getting buffer length. const int ERROR_INSUFFICIENT_BUFFER = 122; string returnval = string.Empty; int bufferSize = 0; // calculate buffer size required - if (ERROR_INSUFFICIENT_BUFFER != WSManGetSessionOptionAsString(wsManAPIHandle, - option, 0, null, out bufferSize)) + if (WSManGetSessionOptionAsString(wsManAPIHandle, + option, 0, null, out bufferSize) != ERROR_INSUFFICIENT_BUFFER) { return returnval; } @@ -2805,7 +2801,7 @@ internal static extern void WSManSignalShellEx(IntPtr shellOperationHandle, /// internal static string WSManGetErrorMessage(IntPtr wsManAPIHandle, int errorCode) { - Dbg.Assert(IntPtr.Zero != wsManAPIHandle, "wsManAPIHandle cannot be null."); + Dbg.Assert(wsManAPIHandle != IntPtr.Zero, "wsManAPIHandle cannot be null."); // The error code taken from winerror.h used for getting buffer length. const int ERROR_INSUFFICIENT_BUFFER = 122; @@ -2816,8 +2812,8 @@ internal static string WSManGetErrorMessage(IntPtr wsManAPIHandle, int errorCode string returnval = string.Empty; int bufferSize = 0; // calculate buffer size required - if (ERROR_INSUFFICIENT_BUFFER != WSManGetErrorMessage(wsManAPIHandle, - 0, langCode, errorCode, 0, null, out bufferSize)) + if (WSManGetErrorMessage(wsManAPIHandle, + 0, langCode, errorCode, 0, null, out bufferSize) != ERROR_INSUFFICIENT_BUFFER) { return returnval; } @@ -3019,6 +3015,7 @@ internal static extern void WSManPluginRegisterShutdownCallback( /// unit testing. /// Note: It is implemented as a class to avoid exposing it outside the module. /// +#nullable enable internal interface IWSManNativeApiFacade { // TODO: Expand this to cover the rest of the API once I prove that it works! @@ -3037,7 +3034,7 @@ int WSManPluginOperationComplete( int WSManPluginReceiveResult( IntPtr requestDetails, int flags, - string stream, + string? stream, IntPtr streamResult, string commandState, int exitCode); @@ -3052,6 +3049,7 @@ void WSManPluginRegisterShutdownCallback( IntPtr shutdownCallback, IntPtr shutdownContext); } +#nullable restore /// /// Concrete implementation of the PInvoke facade for use in the production code. diff --git a/src/System.Management.Automation/engine/remoting/fanin/WSManPlugin.cs b/src/System.Management.Automation/engine/remoting/fanin/WSManPlugin.cs index a8ffc052f4f..9382beb9b31 100644 --- a/src/System.Management.Automation/engine/remoting/fanin/WSManPlugin.cs +++ b/src/System.Management.Automation/engine/remoting/fanin/WSManPlugin.cs @@ -333,7 +333,7 @@ internal void CreateShell( if (inboundShellInformation != null) { - if ((uint)WSManNativeApi.WSManDataType.WSMAN_DATA_TYPE_TEXT != inboundShellInformation.Type) + if (inboundShellInformation.Type != (uint)WSManNativeApi.WSManDataType.WSMAN_DATA_TYPE_TEXT) { // only text data is supported ReportOperationComplete( @@ -361,7 +361,7 @@ internal void CreateShell( requestDetails.ToString(), requestDetails.ToString()); result = wsmanPinvokeStatic.WSManPluginReportContext(requestDetails.unmanagedHandle, 0, requestDetails.unmanagedHandle); - if (WSManPluginConstants.ExitCodeSuccess != result) + if (result != WSManPluginConstants.ExitCodeSuccess) { ReportOperationComplete( requestDetails, @@ -563,7 +563,7 @@ private void AddToActiveShellSessions( lock (_syncObject) { IntPtr key = newShellSession.creationRequestDetails.unmanagedHandle; - Dbg.Assert(IntPtr.Zero != key, "NULL handles should not be provided"); + Dbg.Assert(key != IntPtr.Zero, "NULL handles should not be provided"); if (!_activeShellSessions.ContainsKey(key)) { @@ -574,7 +574,7 @@ private void AddToActiveShellSessions( } } - if (-1 != count) + if (count != -1) { // Raise session count changed event WSManServerChannelEvents.RaiseActiveSessionsChangedEvent(new ActiveSessionsChangedEventArgs(count)); @@ -614,7 +614,7 @@ private void DeleteFromActiveShellSessions( } } - if (-1 != count) + if (count != -1) { // Raise session count changed event WSManServerChannelEvents.RaiseActiveSessionsChangedEvent(new ActiveSessionsChangedEventArgs(count)); @@ -640,7 +640,7 @@ private void HandleShellSessionClosed( /// /// /// - private bool validateIncomingContexts( + private static bool validateIncomingContexts( WSManNativeApi.WSManPluginRequest requestDetails, IntPtr shellContext, string inputFunctionName) @@ -662,7 +662,7 @@ private bool validateIncomingContexts( return false; } - if (IntPtr.Zero == shellContext) + if (shellContext == IntPtr.Zero) { ReportOperationComplete( requestDetails, @@ -871,7 +871,7 @@ internal void ConnectShellOrCommand( return; } - if (IntPtr.Zero == commandContext) + if (commandContext == IntPtr.Zero) { mgdShellSession.ExecuteConnect(requestDetails, flags, inboundConnectInformation); return; @@ -964,7 +964,7 @@ internal void SendOneItemToShellOrCommand( return; } - if (IntPtr.Zero == commandContext) + if (commandContext == IntPtr.Zero) { // the data is destined for shell (runspace) session. so let shell handle it mgdShellSession.SendOneItemToSession(requestDetails, flags, stream, inboundData); @@ -1075,7 +1075,7 @@ internal void EnableShellOrCommandToSendDataToClient( "EnableShellOrCommandToSendDataToClient: Instruction destined to shell or for command", string.Empty); - if (IntPtr.Zero == commandContext) + if (commandContext == IntPtr.Zero) { // the instruction is destined for shell (runspace) session. so let shell handle it if (mgdShellSession.EnableSessionToSendDataToClient(requestDetails, flags, streamSet, ctxtToReport)) @@ -1111,7 +1111,7 @@ internal void EnableShellOrCommandToSendDataToClient( /// /// /// - private PSSenderInfo GetPSSenderInfo( + private static PSSenderInfo GetPSSenderInfo( WSManNativeApi.WSManSenderDetails senderDetails) { // senderDetails will not be null. @@ -1168,7 +1168,7 @@ private PSSenderInfo GetPSSenderInfo( /// environment variable, which is set in the WSMan layer for Virtual or RunAs accounts. /// /// ClientToken IntPtr. - private IntPtr GetRunAsClientToken() + private static IntPtr GetRunAsClientToken() { string clientTokenStr = System.Environment.GetEnvironmentVariable(WSManRunAsClientTokenName); if (clientTokenStr != null) @@ -1576,7 +1576,7 @@ internal static void PerformWSManPluginSignal( WSManNativeApi.WSManPluginRequest request = WSManNativeApi.WSManPluginRequest.UnMarshal(requestDetails); // Close Command - if (IntPtr.Zero != commandContext) + if (commandContext != IntPtr.Zero) { if (!string.Equals(code, WSManPluginConstants.CtrlCSignal, StringComparison.Ordinal)) { @@ -1640,7 +1640,7 @@ internal static void PerformCloseOperation( return; } - if (IntPtr.Zero == context.commandContext) + if (context.commandContext == IntPtr.Zero) { // this is targeted at shell pluginToUse.CloseShellOperation(context); @@ -1794,13 +1794,13 @@ internal static void SetThreadProperties( WSManPluginConstants.WSManPluginParamsGetRequestedDataLocale, outputStruct); // ref nativeDataLocaleData); - bool retrievingDataLocaleSucceeded = ((int)WSManPluginErrorCodes.NoError == hResult); + bool retrievingDataLocaleSucceeded = (hResult == (int)WSManPluginErrorCodes.NoError); WSManNativeApi.WSManData_UnToMan dataLocaleData = WSManNativeApi.WSManData_UnToMan.UnMarshal(outputStruct); // nativeDataLocaleData // Set the UI Culture try { - if (retrievingLocaleSucceeded && ((uint)WSManNativeApi.WSManDataType.WSMAN_DATA_TYPE_TEXT == localeData.Type)) + if (retrievingLocaleSucceeded && (localeData.Type == (uint)WSManNativeApi.WSManDataType.WSMAN_DATA_TYPE_TEXT)) { CultureInfo uiCultureToUse = new CultureInfo(localeData.Text); Thread.CurrentThread.CurrentUICulture = uiCultureToUse; @@ -1814,7 +1814,7 @@ internal static void SetThreadProperties( // Set the Culture try { - if (retrievingDataLocaleSucceeded && ((uint)WSManNativeApi.WSManDataType.WSMAN_DATA_TYPE_TEXT == dataLocaleData.Type)) + if (retrievingDataLocaleSucceeded && (dataLocaleData.Type == (uint)WSManNativeApi.WSManDataType.WSMAN_DATA_TYPE_TEXT)) { CultureInfo cultureToUse = new CultureInfo(dataLocaleData.Text); Thread.CurrentThread.CurrentCulture = cultureToUse; @@ -1883,7 +1883,7 @@ internal static void ReportOperationComplete( WSManPluginErrorCodes errorCode) { if (requestDetails != null && - IntPtr.Zero != requestDetails.unmanagedHandle) + requestDetails.unmanagedHandle != IntPtr.Zero) { wsmanPinvokeStatic.WSManPluginOperationComplete( requestDetails.unmanagedHandle, @@ -1906,7 +1906,7 @@ internal static void ReportOperationComplete( WSManPluginErrorCodes errorCode, string errorMessage = "") { - if (IntPtr.Zero == requestDetails) + if (requestDetails == IntPtr.Zero) { // cannot report if requestDetails is null. return; diff --git a/src/System.Management.Automation/engine/remoting/fanin/WSManPluginFacade.cs b/src/System.Management.Automation/engine/remoting/fanin/WSManPluginFacade.cs index 6735f51b5ca..e2679fcdf44 100644 --- a/src/System.Management.Automation/engine/remoting/fanin/WSManPluginFacade.cs +++ b/src/System.Management.Automation/engine/remoting/fanin/WSManPluginFacade.cs @@ -234,11 +234,7 @@ private void Dispose(bool disposing) } /// - /// Use C# destructor syntax for finalization code. - /// This destructor will run only if the Dispose method - /// does not get called. - /// It gives your base class the opportunity to finalize. - /// Do not provide destructors in types derived from this class. + /// Finalizes an instance of the class. /// ~WSManPluginEntryDelegates() { @@ -433,7 +429,7 @@ private WSManPluginManagedEntryWrapper() { } public static int InitPlugin( IntPtr wkrPtrs) { - if (IntPtr.Zero == wkrPtrs) + if (wkrPtrs == IntPtr.Zero) { return WSManPluginConstants.ExitCodeFailure; } @@ -473,7 +469,7 @@ public static void WSManPluginConnect( IntPtr commandContext, IntPtr inboundConnectInformation) { - if (IntPtr.Zero == pluginContext) + if (pluginContext == IntPtr.Zero) { WSManPluginInstance.ReportOperationComplete( requestDetails, @@ -505,7 +501,7 @@ public static void WSManPluginShell( IntPtr startupInfo, IntPtr inboundShellInformation) { - if (IntPtr.Zero == pluginContext) + if (pluginContext == IntPtr.Zero) { WSManPluginInstance.ReportOperationComplete( requestDetails, @@ -561,7 +557,7 @@ public static void WSManPluginCommand( [MarshalAs(UnmanagedType.LPWStr)] string commandLine, IntPtr arguments) { - if (IntPtr.Zero == pluginContext) + if (pluginContext == IntPtr.Zero) { WSManPluginInstance.ReportOperationComplete( requestDetails, @@ -622,7 +618,7 @@ public static void WSManPluginSend( [MarshalAs(UnmanagedType.LPWStr)] string stream, IntPtr inboundData) { - if (IntPtr.Zero == pluginContext) + if (pluginContext == IntPtr.Zero) { WSManPluginInstance.ReportOperationComplete( requestDetails, @@ -654,7 +650,7 @@ public static void WSManPluginReceive( IntPtr commandContext, IntPtr streamSet) { - if (IntPtr.Zero == pluginContext) + if (pluginContext == IntPtr.Zero) { WSManPluginInstance.ReportOperationComplete( requestDetails, @@ -686,7 +682,7 @@ public static void WSManPluginSignal( IntPtr commandContext, [MarshalAs(UnmanagedType.LPWStr)] string code) { - if ((IntPtr.Zero == pluginContext) || (IntPtr.Zero == shellContext)) + if ((pluginContext == IntPtr.Zero) || (shellContext == IntPtr.Zero)) { WSManPluginInstance.ReportOperationComplete( requestDetails, @@ -766,11 +762,7 @@ private void Dispose(bool disposing) } /// - /// Use C# destructor syntax for finalization code. - /// This destructor will run only if the Dispose method - /// does not get called. - /// It gives your base class the opportunity to finalize. - /// Do not provide destructors in types derived from this class. + /// Finalizes an instance of the class. /// ~WSManPluginManagedEntryInstanceWrapper() { diff --git a/src/System.Management.Automation/engine/remoting/fanin/WSManPluginShellSession.cs b/src/System.Management.Automation/engine/remoting/fanin/WSManPluginShellSession.cs index cf6cdd613df..51635922e0b 100644 --- a/src/System.Management.Automation/engine/remoting/fanin/WSManPluginShellSession.cs +++ b/src/System.Management.Automation/engine/remoting/fanin/WSManPluginShellSession.cs @@ -111,11 +111,7 @@ protected virtual void Dispose(bool disposing) } /// - /// Use C# destructor syntax for finalization code. - /// This destructor will run only if the Dispose method - /// does not get called. - /// It gives your base class the opportunity to finalize. - /// Do not provide destructors in types derived from this class. + /// Finalizes an instance of the class. /// ~WSManPluginServerSession() { @@ -152,7 +148,7 @@ internal void SendOneItemToSession( return; } - if ((uint)WSManNativeApi.WSManDataType.WSMAN_DATA_TYPE_BINARY != inboundData.Type) + if (inboundData.Type != (uint)WSManNativeApi.WSManDataType.WSMAN_DATA_TYPE_BINARY) { // only binary data is supported WSManPluginInstance.ReportOperationComplete( @@ -256,7 +252,7 @@ internal void ReportContext() // TO BE FIXED - As soon as this API is called, WinRM service will send CommandResponse back and Signal is expected anytime // If Signal comes and executes before registering the notification handle, cleanup will be messed result = WSManNativeApi.WSManPluginReportContext(creationRequestDetails.unmanagedHandle, 0, creationRequestDetails.unmanagedHandle); - if (Platform.IsWindows && (WSManPluginConstants.ExitCodeSuccess == result)) + if (Platform.IsWindows && (result == WSManPluginConstants.ExitCodeSuccess)) { registeredShutdownNotification = 1; @@ -281,7 +277,7 @@ internal void ReportContext() } } - if ((WSManPluginConstants.ExitCodeSuccess != result) || (isRegisterWaitForSingleObjectFailed)) + if ((result != WSManPluginConstants.ExitCodeSuccess) || (isRegisterWaitForSingleObjectFailed)) { string errorMessage; if (isRegisterWaitForSingleObjectFailed) @@ -591,7 +587,7 @@ private void AddToActiveCmdSessions( } IntPtr key = newCmdSession.creationRequestDetails.unmanagedHandle; - Dbg.Assert(IntPtr.Zero != key, "NULL handles should not be provided"); + Dbg.Assert(key != IntPtr.Zero, "NULL handles should not be provided"); if (!_activeCommandSessions.ContainsKey(key)) { diff --git a/src/System.Management.Automation/engine/remoting/fanin/WSManPluginTransportManager.cs b/src/System.Management.Automation/engine/remoting/fanin/WSManPluginTransportManager.cs index 312c880b59b..9cc10ce435e 100644 --- a/src/System.Management.Automation/engine/remoting/fanin/WSManPluginTransportManager.cs +++ b/src/System.Management.Automation/engine/remoting/fanin/WSManPluginTransportManager.cs @@ -181,7 +181,7 @@ internal override void ReportExecutionStatusAsRunning() } } - if ((int)WSManPluginErrorCodes.NoError != result) + if (result != (int)WSManPluginErrorCodes.NoError) { ReportError(result, "WSManPluginReceiveResult"); } @@ -247,7 +247,7 @@ protected override void SendDataToClient( } } - if ((int)WSManPluginErrorCodes.NoError != result) + if (result != (int)WSManPluginErrorCodes.NoError) { ReportError(result, "WSManPluginReceiveResult"); } @@ -304,6 +304,7 @@ internal override void RemoveCommandTransportManager( _activeCmdTransportManagers.Remove(cmdId); } } + #endregion internal bool EnableTransportManagerSendDataToClient( WSManNativeApi.WSManPluginRequest requestDetails, diff --git a/src/System.Management.Automation/engine/remoting/fanin/WSManTransportManager.cs b/src/System.Management.Automation/engine/remoting/fanin/WSManTransportManager.cs index 414020eaa42..20db6a1dd1d 100644 --- a/src/System.Management.Automation/engine/remoting/fanin/WSManTransportManager.cs +++ b/src/System.Management.Automation/engine/remoting/fanin/WSManTransportManager.cs @@ -456,6 +456,7 @@ private void ProcessShellData(string data) new Dictionary(); private static long s_sessionTMSeed; + // generate unique session id private static long GetNextSessionTMHandleId() { @@ -1203,7 +1204,7 @@ internal override void CloseAsync() else if (_startMode == WSManTransportManagerUtils.tmStartModes.Create || _startMode == WSManTransportManagerUtils.tmStartModes.Connect) { - if (IntPtr.Zero == _wsManShellOperationHandle) + if (_wsManShellOperationHandle == IntPtr.Zero) { shouldRaiseCloseCompleted = true; } @@ -1472,7 +1473,7 @@ private void Initialize(Uri connectionUri, WSManConnectionInfo connectionInfo) proxyAuthCredentials = new WSManNativeApi.WSManUserNameAuthenticationCredentials(userName, password, authMechanism); } - WSManNativeApi.WSManProxyInfo proxyInfo = (ProxyAccessType.None == connectionInfo.ProxyAccessType) ? + WSManNativeApi.WSManProxyInfo proxyInfo = (connectionInfo.ProxyAccessType == ProxyAccessType.None) ? null : new WSManNativeApi.WSManProxyInfo(connectionInfo.ProxyAccessType, proxyAuthCredentials); @@ -1695,7 +1696,7 @@ internal void ClearReceiveOrSendResources(int flags, bool shouldClearSend) } // For send..clear always - if (IntPtr.Zero != _wsManSendOperationHandle) + if (_wsManSendOperationHandle != IntPtr.Zero) { WSManNativeApi.WSManCloseOperation(_wsManSendOperationHandle, 0); _wsManSendOperationHandle = IntPtr.Zero; @@ -1706,7 +1707,7 @@ internal void ClearReceiveOrSendResources(int flags, bool shouldClearSend) // clearing for receive..Clear only when the end of operation is reached. if (flags == (int)WSManNativeApi.WSManCallbackFlags.WSMAN_FLAG_CALLBACK_END_OF_OPERATION) { - if (IntPtr.Zero != _wsManReceiveOperationHandle) + if (_wsManReceiveOperationHandle != IntPtr.Zero) { WSManNativeApi.WSManCloseOperation(_wsManReceiveOperationHandle, 0); _wsManReceiveOperationHandle = IntPtr.Zero; @@ -1894,7 +1895,7 @@ private static void OnCreateSessionCallback(IntPtr operationContext, } } - if (IntPtr.Zero != error) + if (error != IntPtr.Zero) { WSManNativeApi.WSManError errorStruct = WSManNativeApi.WSManError.UnMarshal(error); @@ -1924,7 +1925,7 @@ private static void OnCreateSessionCallback(IntPtr operationContext, } // check if the session supports disconnect - sessionTM.SupportsDisconnect = ((flags & (int)WSManNativeApi.WSManCallbackFlags.WSMAN_FLAG_CALLBACK_SHELL_SUPPORTS_DISCONNECT) != 0) ? true : false; + sessionTM.SupportsDisconnect = (flags & (int)WSManNativeApi.WSManCallbackFlags.WSMAN_FLAG_CALLBACK_SHELL_SUPPORTS_DISCONNECT) != 0; // openContent is used by redirection ie., while redirecting to // a new machine.. this is not needed anymore as the connection @@ -1995,7 +1996,7 @@ private static void OnCloseSessionCompleted(IntPtr operationContext, sessionTM.RunspacePoolInstanceId.ToString(), "OnCloseSessionCompleted"); - if (IntPtr.Zero != error) + if (error != IntPtr.Zero) { WSManNativeApi.WSManError errorStruct = WSManNativeApi.WSManError.UnMarshal(error); @@ -2054,7 +2055,7 @@ private static void OnRemoteSessionDisconnectCompleted(IntPtr operationContext, sessionTM._disconnectSessionCompleted = null; } - if (IntPtr.Zero != error) + if (error != IntPtr.Zero) { WSManNativeApi.WSManError errorStruct = WSManNativeApi.WSManError.UnMarshal(error); @@ -2136,7 +2137,7 @@ private static void OnRemoteSessionReconnectCompleted(IntPtr operationContext, sessionTM._reconnectSessionCompleted = null; } - if (IntPtr.Zero != error) + if (error != IntPtr.Zero) { WSManNativeApi.WSManError errorStruct = WSManNativeApi.WSManError.UnMarshal(error); @@ -2246,7 +2247,7 @@ private static void OnRemoteSessionConnectCallback(IntPtr operationContext, return; } - if (IntPtr.Zero != error) + if (error != IntPtr.Zero) { WSManNativeApi.WSManError errorStruct = WSManNativeApi.WSManError.UnMarshal(error); @@ -2353,7 +2354,7 @@ private static void OnRemoteSessionSendCompleted(IntPtr operationContext, return; } - if (IntPtr.Zero != error) + if (error != IntPtr.Zero) { WSManNativeApi.WSManError errorStruct = WSManNativeApi.WSManError.UnMarshal(error); @@ -2423,7 +2424,7 @@ private static void OnRemoteSessionDataReceived(IntPtr operationContext, return; } - if (IntPtr.Zero != error) + if (error != IntPtr.Zero) { WSManNativeApi.WSManError errorStruct = WSManNativeApi.WSManError.UnMarshal(error); @@ -2730,7 +2731,7 @@ public void Dispose() _inputStreamSet.Dispose(); _outputStreamSet.Dispose(); - if (IntPtr.Zero != _handle) + if (_handle != IntPtr.Zero) { int result = 0; @@ -2918,7 +2919,7 @@ internal WSManClientCommandTransportManager(WSManConnectionInfo connectionInfo, WSManClientSessionTransportManager sessnTM) : base(shell, sessnTM.CryptoHelper, sessnTM) { - Dbg.Assert(IntPtr.Zero != wsManShellOperationHandle, "Shell operation handle cannot be IntPtr.Zero."); + Dbg.Assert(wsManShellOperationHandle != IntPtr.Zero, "Shell operation handle cannot be IntPtr.Zero."); Dbg.Assert(connectionInfo != null, "connectionInfo cannot be null"); _wsManShellOperationHandle = wsManShellOperationHandle; @@ -3160,7 +3161,7 @@ internal override void CloseAsync() // There is no valid cmd operation handle..so just // raise close completed. - if (IntPtr.Zero == _wsManCmdOperationHandle) + if (_wsManCmdOperationHandle == IntPtr.Zero) { shouldRaiseCloseCompleted = true; } @@ -3286,7 +3287,7 @@ internal void ClearReceiveOrSendResources(int flags, bool shouldClearSend) } // For send..clear always - if (IntPtr.Zero != _wsManSendOperationHandle) + if (_wsManSendOperationHandle != IntPtr.Zero) { WSManNativeApi.WSManCloseOperation(_wsManSendOperationHandle, 0); _wsManSendOperationHandle = IntPtr.Zero; @@ -3297,7 +3298,7 @@ internal void ClearReceiveOrSendResources(int flags, bool shouldClearSend) // clearing for receive..Clear only when the end of operation is reached. if (flags == (int)WSManNativeApi.WSManCallbackFlags.WSMAN_FLAG_CALLBACK_END_OF_OPERATION) { - if (IntPtr.Zero != _wsManReceiveOperationHandle) + if (_wsManReceiveOperationHandle != IntPtr.Zero) { WSManNativeApi.WSManCloseOperation(_wsManReceiveOperationHandle, 0); _wsManReceiveOperationHandle = IntPtr.Zero; @@ -3386,7 +3387,7 @@ private static void OnCreateCmdCompleted(IntPtr operationContext, // Remove this once WSMan fixes its code. cmdTM._wsManCmdOperationHandle = commandOperationHandle; - if (IntPtr.Zero != error) + if (error != IntPtr.Zero) { WSManNativeApi.WSManError errorStruct = WSManNativeApi.WSManError.UnMarshal(error); if (errorStruct.errorCode != 0) @@ -3484,7 +3485,7 @@ private static void OnConnectCmdCompleted(IntPtr operationContext, cmdTM._wsManCmdOperationHandle = commandOperationHandle; - if (IntPtr.Zero != error) + if (error != IntPtr.Zero) { WSManNativeApi.WSManError errorStruct = WSManNativeApi.WSManError.UnMarshal(error); if (errorStruct.errorCode != 0) @@ -3655,7 +3656,7 @@ private static void OnRemoteCmdSendCompleted(IntPtr operationContext, return; } - if (IntPtr.Zero != error) + if (error != IntPtr.Zero) { WSManNativeApi.WSManError errorStruct = WSManNativeApi.WSManError.UnMarshal(error); // Ignore Command aborted error. Command aborted is raised by WSMan to @@ -3732,7 +3733,7 @@ private static void OnRemoteCmdDataReceived(IntPtr operationContext, return; } - if (IntPtr.Zero != error) + if (error != IntPtr.Zero) { WSManNativeApi.WSManError errorStruct = WSManNativeApi.WSManError.UnMarshal(error); if (errorStruct.errorCode != 0) @@ -3812,7 +3813,7 @@ private static void OnReconnectCmdCompleted(IntPtr operationContext, return; } - if (IntPtr.Zero != error) + if (error != IntPtr.Zero) { WSManNativeApi.WSManError errorStruct = WSManNativeApi.WSManError.UnMarshal(error); if (errorStruct.errorCode != 0) @@ -3885,7 +3886,7 @@ private static void OnRemoteCmdSignalCompleted(IntPtr operationContext, } // release the resources related to signal - if (IntPtr.Zero != cmdTM._cmdSignalOperationHandle) + if (cmdTM._cmdSignalOperationHandle != IntPtr.Zero) { WSManNativeApi.WSManCloseOperation(cmdTM._cmdSignalOperationHandle, 0); cmdTM._cmdSignalOperationHandle = IntPtr.Zero; @@ -3904,7 +3905,7 @@ private static void OnRemoteCmdSignalCompleted(IntPtr operationContext, return; } - if (IntPtr.Zero != error) + if (error != IntPtr.Zero) { WSManNativeApi.WSManError errorStruct = WSManNativeApi.WSManError.UnMarshal(error); if (errorStruct.errorCode != 0) diff --git a/src/System.Management.Automation/engine/remoting/server/OutOfProcServerMediator.cs b/src/System.Management.Automation/engine/remoting/server/OutOfProcServerMediator.cs index 67817c8c6e2..1c2728cc6d6 100644 --- a/src/System.Management.Automation/engine/remoting/server/OutOfProcServerMediator.cs +++ b/src/System.Management.Automation/engine/remoting/server/OutOfProcServerMediator.cs @@ -125,7 +125,7 @@ protected void OnDataPacketReceived(byte[] rawData, string stream, Guid psGuid) streamTemp = System.Management.Automation.Remoting.Client.WSManNativeApi.WSMAN_STREAM_ID_PROMPTRESPONSE; } - if (Guid.Empty == psGuid) + if (psGuid == Guid.Empty) { lock (_syncObject) { diff --git a/src/System.Management.Automation/engine/remoting/server/ServerMethodExecutor.cs b/src/System.Management.Automation/engine/remoting/server/ServerMethodExecutor.cs index d9b4d734900..d98239c3c33 100644 --- a/src/System.Management.Automation/engine/remoting/server/ServerMethodExecutor.cs +++ b/src/System.Management.Automation/engine/remoting/server/ServerMethodExecutor.cs @@ -92,7 +92,7 @@ internal void ExecuteVoidMethod(RemoteHostMethodId methodId, object[] parameters Dbg.Assert(parameters != null, "Expected parameters != null"); // Use void call ID so that the call is known to not have a return value. - long callId = ServerDispatchTable.VoidCallId; + const long callId = ServerDispatchTable.VoidCallId; RemoteHostCall remoteHostCall = new RemoteHostCall(callId, methodId, parameters); // Dispatch the call but don't wait for response since the return value is void. diff --git a/src/System.Management.Automation/engine/remoting/server/ServerRemoteHost.cs b/src/System.Management.Automation/engine/remoting/server/ServerRemoteHost.cs index 4d9985e0d18..ca7ff805c02 100644 --- a/src/System.Management.Automation/engine/remoting/server/ServerRemoteHost.cs +++ b/src/System.Management.Automation/engine/remoting/server/ServerRemoteHost.cs @@ -334,8 +334,8 @@ public override void PushRunspace(Runspace runspace) // PSEdit support. Existence of RemoteSessionOpenFileEvent event indicates host supports PSEdit _hostSupportsPSEdit = false; - PSEventManager localEventManager = (Runspace != null) ? Runspace.Events : null; - _hostSupportsPSEdit = (localEventManager != null) ? localEventManager.GetEventSubscribers(HostUtilities.RemoteSessionOpenFileEvent).GetEnumerator().MoveNext() : false; + PSEventManager localEventManager = Runspace?.Events; + _hostSupportsPSEdit = localEventManager != null && localEventManager.GetEventSubscribers(HostUtilities.RemoteSessionOpenFileEvent).GetEnumerator().MoveNext(); if (_hostSupportsPSEdit) { AddPSEditForRunspace(remoteRunspace); diff --git a/src/System.Management.Automation/engine/remoting/server/ServerRemotingProtocol2.cs b/src/System.Management.Automation/engine/remoting/server/ServerRemotingProtocol2.cs index 8d35ba456c1..f87f89b5bac 100644 --- a/src/System.Management.Automation/engine/remoting/server/ServerRemotingProtocol2.cs +++ b/src/System.Management.Automation/engine/remoting/server/ServerRemotingProtocol2.cs @@ -417,6 +417,7 @@ private void HandleRemoveAssociation(object sender, EventArgs e) private readonly Dictionary _associatedShells = new Dictionary(); + // powershell data structure handlers associated with this // runspace pool data structure handler private readonly object _associationSyncObject = new object(); diff --git a/src/System.Management.Automation/engine/remoting/server/ServerRunspacePoolDriver.cs b/src/System.Management.Automation/engine/remoting/server/ServerRunspacePoolDriver.cs index bf235088a41..21cb200e561 100644 --- a/src/System.Management.Automation/engine/remoting/server/ServerRunspacePoolDriver.cs +++ b/src/System.Management.Automation/engine/remoting/server/ServerRunspacePoolDriver.cs @@ -31,7 +31,9 @@ namespace System.Management.Automation internal interface IRSPDriverInvoke { void EnterNestedPipeline(); + void ExitNestedPipeline(); + bool HandleStopSignal(); } @@ -1246,7 +1248,7 @@ private enum PreProcessCommandResult /// The PreProcessCommandResult used for managing breakpoints. /// BreakpointManagement, - }; + } private class DebuggerCommandArgument { @@ -1484,9 +1486,7 @@ private static PreProcessCommandResult PreProcessDebuggerCommand( Breakpoint breakpoint = serverRemoteDebugger.GetBreakpoint(breakpointId, runspaceId); preProcessOutput.Add( - breakpoint == null - ? false - : serverRemoteDebugger.RemoveBreakpoint(breakpoint, runspaceId)); + breakpoint != null && serverRemoteDebugger.RemoveBreakpoint(breakpoint, runspaceId)); result = PreProcessCommandResult.BreakpointManagement; } @@ -1626,7 +1626,7 @@ public bool IsAvailable pump = null; } - return (pump != null) ? !(pump.IsBusy) : false; + return (pump != null) && !(pump.IsBusy); } } @@ -2064,7 +2064,7 @@ public override bool IsActive public override void SetDebuggerStepMode(bool enabled) { // Enable both the wrapper and wrapped debuggers for debugging before setting step mode. - DebugModes mode = DebugModes.LocalScript | DebugModes.RemoteScript; + const DebugModes mode = DebugModes.LocalScript | DebugModes.RemoteScript; base.SetDebugMode(mode); _wrappedDebugger.Value.SetDebugMode(mode); @@ -2710,7 +2710,7 @@ internal void StartPowerShellCommand( powershell.InvocationStateChanged += HandlePowerShellInvocationStateChanged; powershell.SetIsNested(false); - string script = @" + const string script = @" param ($Debugger, $Commands, $output) trap { throw $_ } diff --git a/src/System.Management.Automation/engine/remoting/server/ServerSteppablePipelineSubscriber.cs b/src/System.Management.Automation/engine/remoting/server/ServerSteppablePipelineSubscriber.cs index 556d71e2a9b..328571647cb 100644 --- a/src/System.Management.Automation/engine/remoting/server/ServerSteppablePipelineSubscriber.cs +++ b/src/System.Management.Automation/engine/remoting/server/ServerSteppablePipelineSubscriber.cs @@ -62,6 +62,7 @@ internal void SubscribeEvents(ServerSteppablePipelineDriver driver) #region Events and Handlers public event EventHandler StartSteppablePipeline; + public event EventHandler RunProcessRecord; /// diff --git a/src/System.Management.Automation/engine/remoting/server/serverremotesession.cs b/src/System.Management.Automation/engine/remoting/server/serverremotesession.cs index 9f91e8a255d..7b08c674301 100644 --- a/src/System.Management.Automation/engine/remoting/server/serverremotesession.cs +++ b/src/System.Management.Automation/engine/remoting/server/serverremotesession.cs @@ -206,7 +206,7 @@ internal static ServerRemoteSession CreateServerRemoteSession( throw PSTraceSource.NewInvalidOperationException("RemotingErrorIdStrings.NonExistentInitialSessionStateProvider", configurationProviderId); } - string shellPrefix = System.Management.Automation.Remoting.Client.WSManNativeApi.ResourceURIPrefix; + const string shellPrefix = System.Management.Automation.Remoting.Client.WSManNativeApi.ResourceURIPrefix; int index = configurationProviderId.IndexOf(shellPrefix, StringComparison.OrdinalIgnoreCase); senderInfo.ConfigurationName = (index == 0) ? configurationProviderId.Substring(shellPrefix.Length) : string.Empty; ServerRemoteSession result = new ServerRemoteSession( @@ -285,10 +285,10 @@ internal override RemotingDestination MySelf /// This parameter contains the remote data received from client. /// /// - /// If the parameter is null. + /// If the parameter is null. /// /// - /// If the parameter does not contain remote data. + /// If the parameter does not contain remote data. /// /// /// If the destination of the data is not for server. @@ -696,7 +696,7 @@ internal void ExecuteConnect(byte[] connectData, out byte[] connectResponseData) // as this is executed only when connecting from a new client that does not have any previous fragments context. // no problem even if fragment Ids in this response and the sessiontransport stream clash (interfere) and its guaranteed // that the fragments in connect response are always complete (enclose a complete object). - SerializedDataStream stream = new SerializedDataStream(4 * 1024);//Each message with fragment headers cannot cross 4k + SerializedDataStream stream = new SerializedDataStream(4 * 1024); //Each message with fragment headers cannot cross 4k stream.Enter(); capability.Serialize(stream, fragmentor); stream.Exit(); diff --git a/src/System.Management.Automation/engine/remoting/server/serverremotesessionstatemachine.cs b/src/System.Management.Automation/engine/remoting/server/serverremotesessionstatemachine.cs index 8be75b445b4..732e5a836ab 100644 --- a/src/System.Management.Automation/engine/remoting/server/serverremotesessionstatemachine.cs +++ b/src/System.Management.Automation/engine/remoting/server/serverremotesessionstatemachine.cs @@ -39,6 +39,7 @@ internal class ServerRemoteSessionDSHandlerStateMachine private readonly Queue _processPendingEventsQueue = new Queue(); + // whether some thread is actively processing events // in a loop. If this is set then other threads // should simply add to the queue and not attempt @@ -1001,7 +1002,7 @@ private void HandleKeyExchangeTimeout(object sender) /// It can also be used for graceful shutdown of the server process, which is not currently /// implemented. /// - private void CleanAll() + private static void CleanAll() { } diff --git a/src/System.Management.Automation/engine/runtime/Binding/Binders.cs b/src/System.Management.Automation/engine/runtime/Binding/Binders.cs index b8fed047fc0..83dc432ef55 100644 --- a/src/System.Management.Automation/engine/runtime/Binding/Binders.cs +++ b/src/System.Management.Automation/engine/runtime/Binding/Binders.cs @@ -1202,7 +1202,7 @@ internal static PSInvokeDynamicMemberBinder Get(CallInfo callInfo, TypeDefinitio { PSInvokeDynamicMemberBinder result; - var classScope = classScopeAst != null ? classScopeAst.Type : null; + var classScope = classScopeAst?.Type; lock (s_binderCache) { var key = Tuple.Create(callInfo, constraints, propertySetter, @static, classScope); @@ -1296,7 +1296,7 @@ internal static PSGetDynamicMemberBinder Get(TypeDefinitionAst classScope, bool PSGetDynamicMemberBinder binder; lock (s_binderCache) { - var type = classScope != null ? classScope.Type : null; + var type = classScope?.Type; var tuple = Tuple.Create(type, @static); if (!s_binderCache.TryGetValue(tuple, out binder)) { @@ -1406,7 +1406,7 @@ internal static PSSetDynamicMemberBinder Get(TypeDefinitionAst classScope, bool PSSetDynamicMemberBinder binder; lock (s_binderCache) { - var type = classScope != null ? classScope.Type : null; + var type = classScope?.Type; var tuple = Tuple.Create(type, @static); if (!s_binderCache.TryGetValue(tuple, out binder)) { @@ -2035,36 +2035,39 @@ private static object NullRule(CallSite site, object obj) internal static bool IsValueTypeMutable(Type type) { - if (type.IsPrimitive || type.IsEnum) + // First, check for enums/primitives and compiler-defined attributes. + if (type.IsPrimitive + || type.IsEnum + || type.IsDefined(typeof(System.Runtime.CompilerServices.IsReadOnlyAttribute), inherit: false)) { return false; } - // If there are any fields, the type is mutable. - if (type.GetFields(BindingFlags.Public | BindingFlags.Instance).Length > 0) + // If the builtin attribute is not present, check for a custom attribute from by the compiler. If the + // library targets netstandard2.0, the compiler can't be sure the attribute will be provided by the runtime, + // and defines its own attribute of the same name during compilation. To account for this, we must check the + // type by name, not by reference. + foreach (object attribute in type.GetCustomAttributes(inherit: false)) { - return true; + if (attribute.GetType().FullName.Equals( + "System.Runtime.CompilerServices.IsReadOnlyAttribute", + StringComparison.Ordinal)) + { + return false; + } } - // If there are any properties with setters, the type is mutable. - var properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); - for (int index = 0; index < properties.Length; index++) + // Fallback: check all fields (public + private) to verify whether they're all readonly. + // If any field is not readonly, the value type is potentially mutable. + foreach (var field in type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)) { - var property = properties[index]; - if (property.CanWrite) + if (!field.IsInitOnly) { return true; } } - // If there are any methods other than the property getters, the type might - // be mutable, so assume the type is mutable. - var methods = type.GetMethods(BindingFlags.Public | BindingFlags.Instance); - if (methods.Length != properties.Length) - { - return true; - } - + // If all fields are init-only (read-only), then the value type is immutable. return false; } @@ -5071,7 +5074,7 @@ internal static void TypeTableMemberPossiblyUpdated(string memberName) public static PSGetMemberBinder Get(string memberName, TypeDefinitionAst classScope, bool @static) { - return Get(memberName, classScope != null ? classScope.Type : null, @static, false); + return Get(memberName, classScope?.Type, @static, false); } public static PSGetMemberBinder Get(string memberName, Type classScope, bool @static) @@ -5629,7 +5632,7 @@ internal PSMemberInfo GetPSMemberInfo(DynamicMetaObject target, PSMemberInfo memberInfo = null; ConsolidatedString typenames = null; var context = LocalPipeline.GetExecutionContextFromTLS(); - var typeTable = context != null ? context.TypeTable : null; + var typeTable = context?.TypeTable; if (hasTypeTableMember) { @@ -5842,7 +5845,7 @@ internal static object GetAdaptedValue(object obj, string member) } } - var adapterSet = PSObject.GetMappedAdapter(obj, context != null ? context.TypeTable : null); + var adapterSet = PSObject.GetMappedAdapter(obj, context?.TypeTable); if (memberInfo == null) { memberInfo = adapterSet.OriginalAdapter.BaseGetMember(obj, member); @@ -5881,7 +5884,7 @@ internal static bool IsTypeNameSame(object value, string typeName) internal static TypeTable GetTypeTableFromTLS() { var executionContext = LocalPipeline.GetExecutionContextFromTLS(); - return executionContext != null ? executionContext.TypeTable : null; + return executionContext?.TypeTable; } internal static bool TryGetInstanceMember(object value, string memberName, out PSMemberInfo memberInfo) @@ -5964,7 +5967,7 @@ private static readonly Dictionary public static PSSetMemberBinder Get(string memberName, TypeDefinitionAst classScopeAst, bool @static) { - var classScope = classScopeAst != null ? classScopeAst.Type : null; + var classScope = classScopeAst?.Type; return Get(memberName, classScope, @static); } @@ -5998,7 +6001,7 @@ public override string ToString() return string.Format(CultureInfo.InvariantCulture, "SetMember: {0}{1} ver:{2}", _static ? "static " : string.Empty, Name, _getMemberBinder._version); } - private Expression GetTransformedExpression(IEnumerable transformationAttributes, Expression originalExpression) + private static Expression GetTransformedExpression(IEnumerable transformationAttributes, Expression originalExpression) { if (transformationAttributes == null) { @@ -6286,7 +6289,7 @@ public override DynamicMetaObject FallbackSetMember(DynamicMetaObject target, Dy if (value.Value == null) { expr = Expression.Block( - Expression.Assign(lhs, this.GetTransformedExpression(argumentTransformationAttributes, Expression.Constant(null, lhsType))), + Expression.Assign(lhs, GetTransformedExpression(argumentTransformationAttributes, Expression.Constant(null, lhsType))), ExpressionCache.NullConstant); } else @@ -6295,7 +6298,7 @@ public override DynamicMetaObject FallbackSetMember(DynamicMetaObject target, Dy Expression assignmentExpression; if (transformationNeeded) { - var transformedExpr = this.GetTransformedExpression(argumentTransformationAttributes, value.Expression); + var transformedExpr = GetTransformedExpression(argumentTransformationAttributes, value.Expression); assignmentExpression = DynamicExpression.Dynamic(PSConvertBinder.Get(nullableUnderlyingType), nullableUnderlyingType, transformedExpr); } else @@ -6317,7 +6320,7 @@ public override DynamicMetaObject FallbackSetMember(DynamicMetaObject target, Dy if (transformationNeeded) { assignedValue = DynamicExpression.Dynamic(PSConvertBinder.Get(lhsType), lhsType, - this.GetTransformedExpression(argumentTransformationAttributes, value.Expression)); + GetTransformedExpression(argumentTransformationAttributes, value.Expression)); } else { @@ -6446,7 +6449,7 @@ internal static object SetAdaptedValue(object obj, string member, object value) } } - var adapterSet = PSObject.GetMappedAdapter(obj, context != null ? context.TypeTable : null); + var adapterSet = PSObject.GetMappedAdapter(obj, context?.TypeTable); if (memberInfo == null) { memberInfo = adapterSet.OriginalAdapter.BaseGetMember(obj, member); @@ -7401,7 +7404,7 @@ internal static bool IsHeterogeneousArray(object[] args) internal static object InvokeAdaptedMember(object obj, string methodName, object[] args) { var context = LocalPipeline.GetExecutionContextFromTLS(); - var adapterSet = PSObject.GetMappedAdapter(obj, context != null ? context.TypeTable : null); + var adapterSet = PSObject.GetMappedAdapter(obj, context?.TypeTable); var methodInfo = adapterSet.OriginalAdapter.BaseGetMember(obj, methodName) as PSMethodInfo; if (methodInfo == null && adapterSet.DotNetAdapter != null) { @@ -7446,7 +7449,7 @@ internal static object InvokeAdaptedMember(object obj, string methodName, object internal static object InvokeAdaptedSetMember(object obj, string methodName, object[] args, object valueToSet) { var context = LocalPipeline.GetExecutionContextFromTLS(); - var adapterSet = PSObject.GetMappedAdapter(obj, context != null ? context.TypeTable : null); + var adapterSet = PSObject.GetMappedAdapter(obj, context?.TypeTable); var methodInfo = adapterSet.OriginalAdapter.BaseGetMember(obj, methodName); if (methodInfo == null && adapterSet.DotNetAdapter != null) { diff --git a/src/System.Management.Automation/engine/runtime/CompiledScriptBlock.cs b/src/System.Management.Automation/engine/runtime/CompiledScriptBlock.cs index a706315f52e..97625a9e46a 100644 --- a/src/System.Management.Automation/engine/runtime/CompiledScriptBlock.cs +++ b/src/System.Management.Automation/engine/runtime/CompiledScriptBlock.cs @@ -307,18 +307,29 @@ private IParameterMetadataProvider DelayParseScriptText() } internal Type LocalsMutableTupleType { get; set; } + internal Type UnoptimizedLocalsMutableTupleType { get; set; } + internal Func LocalsMutableTupleCreator { get; set; } + internal Func UnoptimizedLocalsMutableTupleCreator { get; set; } + internal Dictionary NameToIndexMap { get; set; } internal Action DynamicParamBlock { get; set; } + internal Action UnoptimizedDynamicParamBlock { get; set; } + internal Action BeginBlock { get; set; } + internal Action UnoptimizedBeginBlock { get; set; } + internal Action ProcessBlock { get; set; } + internal Action UnoptimizedProcessBlock { get; set; } + internal Action EndBlock { get; set; } + internal Action UnoptimizedEndBlock { get; set; } internal IScriptExtent[] SequencePoints { get; set; } @@ -332,11 +343,15 @@ private IParameterMetadataProvider DelayParseScriptText() private bool? _isProductCode; internal bool DebuggerHidden { get; set; } + internal bool DebuggerStepThrough { get; set; } + internal Guid Id { get; private set; } internal bool HasLogged { get; set; } + internal bool SkipLogging { get; set; } + internal bool IsFilter { get; } internal bool IsProductCode @@ -989,7 +1004,7 @@ internal void InvokeWithPipeImpl( args = Array.Empty(); } - bool runOptimized = context._debuggingMode > 0 ? false : createLocalScope; + bool runOptimized = context._debuggingMode <= 0 && createLocalScope; var codeToInvoke = GetCodeToInvoke(ref runOptimized, clauseToInvoke); if (codeToInvoke == null) { @@ -2192,7 +2207,7 @@ public PSScriptCmdlet(ScriptBlock scriptBlock, bool useNewScope, bool fromScript _scriptBlock = scriptBlock; _useLocalScope = useNewScope; _fromScriptFile = fromScriptFile; - _runOptimized = _scriptBlock.Compile(optimized: context._debuggingMode > 0 ? false : useNewScope); + _runOptimized = _scriptBlock.Compile(optimized: context._debuggingMode <= 0 && useNewScope); _localsTuple = _scriptBlock.MakeLocalsTuple(_runOptimized); _localsTuple.SetAutomaticVariable(AutomaticVariable.PSCmdlet, this, context); _scriptBlock.SetPSScriptRootAndPSCommandPath(_localsTuple, context); diff --git a/src/System.Management.Automation/engine/runtime/MutableTuple.cs b/src/System.Management.Automation/engine/runtime/MutableTuple.cs index 4d813166795..e7ee0d615df 100644 --- a/src/System.Management.Automation/engine/runtime/MutableTuple.cs +++ b/src/System.Management.Automation/engine/runtime/MutableTuple.cs @@ -149,6 +149,7 @@ public void SetValue(int index, object value) } protected abstract object GetValueImpl(int index); + protected abstract void SetValueImpl(int index, object value); /// diff --git a/src/System.Management.Automation/engine/runtime/Operations/ArrayOps.cs b/src/System.Management.Automation/engine/runtime/Operations/ArrayOps.cs index f6b71fad1ef..fa4c2c2b565 100644 --- a/src/System.Management.Automation/engine/runtime/Operations/ArrayOps.cs +++ b/src/System.Management.Automation/engine/runtime/Operations/ArrayOps.cs @@ -234,7 +234,7 @@ internal static string IndexStringMessage(object index) // Convert this index into something printable (we hope)... string msgString = PSObject.ToString(null, index, ",", null, null, true, true); if (msgString.Length > 20) - msgString = string.Concat(msgString.AsSpan().Slice(0, 20), " ..."); + msgString = string.Concat(msgString.AsSpan(0, 20), " ..."); return msgString; } diff --git a/src/System.Management.Automation/engine/runtime/Operations/ClassOps.cs b/src/System.Management.Automation/engine/runtime/Operations/ClassOps.cs index 7b06697afa1..5afe23a6362 100644 --- a/src/System.Management.Automation/engine/runtime/Operations/ClassOps.cs +++ b/src/System.Management.Automation/engine/runtime/Operations/ClassOps.cs @@ -284,7 +284,7 @@ public static void ValidateSetProperty(Type type, string propertyName, object va { var validateAttributes = type.GetProperty(propertyName).GetCustomAttributes(); var executionContext = LocalPipeline.GetExecutionContextFromTLS(); - var engineIntrinsics = executionContext == null ? null : executionContext.EngineIntrinsics; + var engineIntrinsics = executionContext?.EngineIntrinsics; foreach (var validateAttribute in validateAttributes) { validateAttribute.InternalValidate(value, engineIntrinsics); diff --git a/src/System.Management.Automation/engine/runtime/Operations/MiscOps.cs b/src/System.Management.Automation/engine/runtime/Operations/MiscOps.cs index fdc259a684e..df8b36eb40f 100644 --- a/src/System.Management.Automation/engine/runtime/Operations/MiscOps.cs +++ b/src/System.Management.Automation/engine/runtime/Operations/MiscOps.cs @@ -407,7 +407,7 @@ private static string GetParameterText(string parameterName) else { string whitespaces = parameterName.Substring(endPosition); - parameterText = string.Concat("-", parameterName.AsSpan().Slice(0, endPosition), ":", whitespaces); + parameterText = string.Concat("-", parameterName.AsSpan(0, endPosition), ":", whitespaces); } return parameterText; @@ -449,7 +449,7 @@ internal static void InvokePipeline(object input, for (int i = 0; i < pipeElements.Length; i++) { - commandRedirection = commandRedirections != null ? commandRedirections[i] : null; + commandRedirection = commandRedirections?[i]; commandProcessor = AddCommand(pipelineProcessor, pipeElements[i], pipeElementAsts[i], commandRedirection, context); } @@ -1308,7 +1308,7 @@ internal ScriptBlock GetScriptBlock(ExecutionContext context, bool isFilter) Diagnostics.Assert(_scriptBlock == null || _scriptBlock.SessionStateInternal == null, "Cached script block should not hold on to session state"); - var result = (_scriptBlock ?? (_scriptBlock = new ScriptBlock(_ast, isFilter))).Clone(); + var result = (_scriptBlock ??= new ScriptBlock(_ast, isFilter)).Clone(); result.SessionStateInternal = context.EngineSessionState; return result; } diff --git a/src/System.Management.Automation/engine/runtime/ScriptBlockToPowerShell.cs b/src/System.Management.Automation/engine/runtime/ScriptBlockToPowerShell.cs index 09e21f5c7b4..f5d2f51f698 100644 --- a/src/System.Management.Automation/engine/runtime/ScriptBlockToPowerShell.cs +++ b/src/System.Management.Automation/engine/runtime/ScriptBlockToPowerShell.cs @@ -16,6 +16,7 @@ internal class ScriptBlockToPowerShellChecker : AstVisitor private readonly HashSet _validVariables = new HashSet(StringComparer.OrdinalIgnoreCase); internal ScriptBlockAst ScriptBeingConverted { get; set; } + internal bool UsesParameter { get; private set; } internal bool HasUsingExpr { get; private set; } @@ -546,7 +547,6 @@ private void ConvertCommand(CommandAst commandAst, bool isTrustedInput) Diagnostics.Assert(commandAst.Redirections.Count == 1, "only 1 kind of redirection is supported"); Diagnostics.Assert(commandAst.Redirections[0] is MergingRedirectionAst, "unexpected redirection type"); - PipelineResultTypes toType = PipelineResultTypes.Output; PipelineResultTypes fromType; switch (commandAst.Redirections[0].FromStream) { @@ -580,7 +580,7 @@ private void ConvertCommand(CommandAst commandAst, bool isTrustedInput) break; } - command.MergeMyResults(fromType, toType); + command.MergeMyResults(fromType, toResult: PipelineResultTypes.Output); } _powershell.AddCommand(command); diff --git a/src/System.Management.Automation/engine/serialization.cs b/src/System.Management.Automation/engine/serialization.cs index 488b73d14fc..a01f67b81e2 100644 --- a/src/System.Management.Automation/engine/serialization.cs +++ b/src/System.Management.Automation/engine/serialization.cs @@ -201,7 +201,7 @@ internal Serializer(XmlWriter writer) /// Writer to be used for serialization. /// Depth of serialization. /// - /// if true then types.ps1xml can override depth + /// if then types.ps1xml can override depth /// for a particular types (using SerializationDepth property) /// internal Serializer(XmlWriter writer, int depth, bool useDepthFromTypes) @@ -540,7 +540,7 @@ private void Start() // If version is not provided, we assume it is the default string version = InternalSerializer.DefaultVersion; - if (DeserializationOptions.NoRootElement == (_context.options & DeserializationOptions.NoRootElement)) + if ((_context.options & DeserializationOptions.NoRootElement) == DeserializationOptions.NoRootElement) { _done = _reader.EOF; } @@ -571,7 +571,7 @@ internal bool Done() { if (!_done) { - if (DeserializationOptions.NoRootElement == (_context.options & DeserializationOptions.NoRootElement)) + if ((_context.options & DeserializationOptions.NoRootElement) == DeserializationOptions.NoRootElement) { _done = _reader.EOF; } @@ -661,7 +661,7 @@ internal static void AddDeserializationPrefix(ref string type) /// /// /// - /// true if is either a live or deserialized instance of class or one of its subclasses; false otherwise. + /// if is either a live or deserialized instance of class or one of its subclasses; otherwise. internal static bool IsInstanceOfType(object o, Type type) { if (type == null) @@ -682,7 +682,7 @@ internal static bool IsInstanceOfType(object o, Type type) /// /// /// - /// true if is a deserialized instance of class or one of its subclasses; false otherwise. + /// if is a deserialized instance of class or one of its subclasses; otherwise. internal static bool IsDeserializedInstanceOfType(object o, Type type) { if (type == null) @@ -791,7 +791,7 @@ internal enum ContainerType List, Enumerable, None - }; + } /// /// This internal helper class provides methods for serializing mshObject. @@ -866,7 +866,7 @@ internal TypeTable TypeTable /// internal void Start() { - if (SerializationOptions.NoRootElement != (_context.options & SerializationOptions.NoRootElement)) + if ((_context.options & SerializationOptions.NoRootElement) != SerializationOptions.NoRootElement) { this.WriteStartElement(SerializationStrings.RootElementTag); this.WriteAttribute(SerializationStrings.VersionAttribute, InternalSerializer.DefaultVersion); @@ -878,7 +878,7 @@ internal void Start() /// internal void End() { - if (SerializationOptions.NoRootElement != (_context.options & SerializationOptions.NoRootElement)) + if ((_context.options & SerializationOptions.NoRootElement) != SerializationOptions.NoRootElement) { _writer.WriteEndElement(); } @@ -1893,9 +1893,8 @@ private Collection> ExtendedMembersCollection { get { - return _extendedMembersCollection ?? - (_extendedMembersCollection = - PSObject.GetMemberCollection(PSMemberViewTypes.Extended, _typeTable)); + return _extendedMembersCollection ??= + PSObject.GetMemberCollection(PSMemberViewTypes.Extended, _typeTable); } } @@ -1905,8 +1904,7 @@ private Collection> AllPropertiesCollection { get { - return _allPropertiesCollection ?? - (_allPropertiesCollection = PSObject.GetPropertyCollection(PSMemberViewTypes.All, _typeTable)); + return _allPropertiesCollection ??= PSObject.GetPropertyCollection(PSMemberViewTypes.All, _typeTable); } } @@ -2750,7 +2748,7 @@ internal static void WriteSecureString(InternalSerializer serializer, string str private void WriteStartElement(string elementTag) { Dbg.Assert(!string.IsNullOrEmpty(elementTag), "Caller should validate the parameter"); - if (SerializationOptions.NoNamespace == (_context.options & SerializationOptions.NoNamespace)) + if ((_context.options & SerializationOptions.NoNamespace) == SerializationOptions.NoNamespace) { _writer.WriteStartElement(elementTag); } @@ -2828,7 +2826,7 @@ internal static string EncodeString(string s) /// /// This is the real workhorse that encodes strings. - /// See for more information. + /// See for more information. /// /// String to encode. /// IndexOfFirstEncodableCharacter. @@ -2908,7 +2906,7 @@ private void WriteEncodedElementString(string name, string value) value = EncodeString(value); - if (SerializationOptions.NoNamespace == (_context.options & SerializationOptions.NoNamespace)) + if ((_context.options & SerializationOptions.NoNamespace) == SerializationOptions.NoNamespace) { _writer.WriteElementString(name, value); } @@ -2957,6 +2955,10 @@ private bool UnknownTagsAllowed } } + [SuppressMessage( + "Performance", + "CA1822:Mark members as static", + Justification = "Accesses instance members in preprocessor branch.")] private bool DuplicateRefIdsAllowed { get @@ -3196,7 +3198,7 @@ private void CheckIfStopping() internal const string CimHashCodeProperty = "Hash"; internal const string CimMiXmlProperty = "MiXml"; - private bool RehydrateCimInstanceProperty( + private static bool RehydrateCimInstanceProperty( CimInstance cimInstance, PSPropertyInfo deserializedProperty, HashSet namesOfModifiedProperties) @@ -4418,7 +4420,7 @@ internal static object DeserializeScriptBlock(InternalDeserializer deserializer) { Dbg.Assert(deserializer != null, "Caller should validate the parameter"); string scriptBlockBody = deserializer.ReadDecodedElementString(SerializationStrings.ScriptBlockTag); - if (DeserializationOptions.DeserializeScriptBlocks == (deserializer._context.options & DeserializationOptions.DeserializeScriptBlocks)) + if ((deserializer._context.options & DeserializationOptions.DeserializeScriptBlocks) == DeserializationOptions.DeserializeScriptBlocks) { return ScriptBlock.Create(scriptBlockBody); } @@ -4652,7 +4654,7 @@ internal static object DeserializeProgressRecord(InternalDeserializer deserializ activityId = int.Parse(deserializer.ReadDecodedElementString(SerializationStrings.ProgressRecordActivityId), CultureInfo.InvariantCulture); object tmp = deserializer.ReadOneObject(); - currentOperation = (tmp == null) ? null : tmp.ToString(); + currentOperation = tmp?.ToString(); parentActivityId = int.Parse(deserializer.ReadDecodedElementString(SerializationStrings.ProgressRecordParentActivityId), CultureInfo.InvariantCulture); percentComplete = int.Parse(deserializer.ReadDecodedElementString(SerializationStrings.ProgressRecordPercentComplete), CultureInfo.InvariantCulture); @@ -4768,7 +4770,7 @@ private void ReadStartElement(string element) { Dbg.Assert(!string.IsNullOrEmpty(element), "Caller should validate the parameter"); - if (DeserializationOptions.NoNamespace == (_context.options & DeserializationOptions.NoNamespace)) + if ((_context.options & DeserializationOptions.NoNamespace) == DeserializationOptions.NoNamespace) { _reader.ReadStartElement(element); } @@ -4792,7 +4794,7 @@ private string ReadDecodedElementString(string element) this.CheckIfStopping(); string temp = null; - if (DeserializationOptions.NoNamespace == (_context.options & DeserializationOptions.NoNamespace)) + if ((_context.options & DeserializationOptions.NoNamespace) == DeserializationOptions.NoNamespace) { temp = _reader.ReadElementContentAsString(element, string.Empty); } @@ -4969,7 +4971,7 @@ internal string SetRefId(T t) } /// - /// Gets a RefId already assigned for the given object or null if there is no associated ref id. + /// Gets a RefId already assigned for the given object or if there is no associated ref id. /// /// /// @@ -5930,7 +5932,7 @@ private PSPrimitiveDictionary(System.Runtime.Serialization.SerializationInfo inf #region Plumbing to make Hashtable reject all non-primitive types - private string VerifyKey(object key) + private static string VerifyKey(object key) { key = PSObject.Base(key); string keyAsString = key as string; @@ -6030,7 +6032,7 @@ private void VerifyValue(object value) /// public override void Add(object key, object value) { - string keyAsString = this.VerifyKey(key); + string keyAsString = VerifyKey(key); this.VerifyValue(value); base.Add(keyAsString, value); } @@ -6041,7 +6043,7 @@ public override void Add(object key, object value) /// The key whose value to get or set. /// The value associated with the specified key. /// - /// If the specified key is not found, attempting to get it returns null + /// If the specified key is not found, attempting to get it returns /// and attempting to set it creates a new element using the specified key. /// /// @@ -6058,7 +6060,7 @@ public override object this[object key] set { - string keyAsString = this.VerifyKey(key); + string keyAsString = VerifyKey(key); this.VerifyValue(value); base[keyAsString] = value; } @@ -6070,7 +6072,7 @@ public override object this[object key] /// The key whose value to get or set. /// The value associated with the specified key. /// - /// If the specified key is not found, attempting to get it returns null + /// If the specified key is not found, attempting to get it returns /// and attempting to set it creates a new element using the specified key. /// /// @@ -6532,7 +6534,7 @@ internal static PSPrimitiveDictionary CloneAndAddPSVersionTable(PSPrimitiveDicti /// The root dictionary. /// /// A chain of keys leading from the root dictionary () to the value. - /// true if the value was found and was of the correct type; false otherwise. + /// if the value was found and was of the correct type; otherwise. internal static bool TryPathGet(IDictionary data, out T result, params string[] keys) { Dbg.Assert(keys != null, "Caller should verify that keys != null"); @@ -6850,14 +6852,14 @@ internal static T GetPropertyValue(PSObject pso, string propertyName, Rehydra Dbg.Assert(!string.IsNullOrEmpty(propertyName), "Caller should verify propertyName != null"); PSPropertyInfo property = pso.Properties[propertyName]; - if ((property == null) && (RehydrationFlags.MissingPropertyOk == (flags & RehydrationFlags.MissingPropertyOk))) + if ((property == null) && ((flags & RehydrationFlags.MissingPropertyOk) == RehydrationFlags.MissingPropertyOk)) { return default(T); } else { object propertyValue = property.Value; - if ((propertyValue == null) && (RehydrationFlags.NullValueOk == (flags & RehydrationFlags.NullValueOk))) + if ((propertyValue == null) && ((flags & RehydrationFlags.NullValueOk) == RehydrationFlags.NullValueOk)) { return default(T); } @@ -6875,7 +6877,7 @@ private static ListType RehydrateList(PSObject pso, string p ArrayList deserializedList = GetPropertyValue(pso, propertyName, flags); if (deserializedList == null) { - if (RehydrationFlags.NullValueMeansEmptyList == (flags & RehydrationFlags.NullValueMeansEmptyList)) + if ((flags & RehydrationFlags.NullValueMeansEmptyList) == RehydrationFlags.NullValueMeansEmptyList) { return new ListType(); } diff --git a/src/System.Management.Automation/help/CabinetNativeApi.cs b/src/System.Management.Automation/help/CabinetNativeApi.cs index 267317b11d0..76e8fe853a4 100644 --- a/src/System.Management.Automation/help/CabinetNativeApi.cs +++ b/src/System.Management.Automation/help/CabinetNativeApi.cs @@ -84,7 +84,7 @@ protected override void Dispose(bool disposing) } /// - /// Finalizer to ensure destruction of unmanaged resources. + /// Finalizes an instance of the class. /// ~CabinetExtractor() { @@ -164,7 +164,7 @@ private void CleanUpDelegates() _fdiNotifyHandle.Free(); } } - }; + } // CabinetExtractor loader implementation internal class CabinetExtractorLoader : ICabinetExtractorLoader @@ -188,7 +188,7 @@ internal override ICabinetExtractor GetCabinetExtractor() { return s_extractorInstance; } - }; + } internal static class CabinetNativeApi { @@ -458,11 +458,11 @@ internal static FileMode ConvertOpflagToFileMode(int oflag) { // Note: This is not done in a switch because the order of tests matters. - if ((int)(OpFlags.Create | OpFlags.Excl) == (oflag & (int)(OpFlags.Create | OpFlags.Excl))) + if ((oflag & (int)(OpFlags.Create | OpFlags.Excl)) == (int)(OpFlags.Create | OpFlags.Excl)) { return FileMode.CreateNew; } - else if ((int)(OpFlags.Create | OpFlags.Truncate) == (oflag & (int)(OpFlags.Create | OpFlags.Truncate))) + else if ((oflag & (int)(OpFlags.Create | OpFlags.Truncate)) == (int)(OpFlags.Create | OpFlags.Truncate)) { return FileMode.OpenOrCreate; } @@ -497,7 +497,7 @@ internal static FileAccess ConvertPermissionModeToFileAccess(int pmode) { // Note: This is not done in a switch because the order of tests matters. - if ((int)(PermissionMode.Read | PermissionMode.Write) == (pmode & (int)(PermissionMode.Read | PermissionMode.Write))) + if ((pmode & (int)(PermissionMode.Read | PermissionMode.Write)) == (int)(PermissionMode.Read | PermissionMode.Write)) { return FileAccess.ReadWrite; } @@ -524,7 +524,7 @@ internal static FileShare ConvertPermissionModeToFileShare(int pmode) { // Note: This is not done in a switch because the order of tests matters. - if ((int)(PermissionMode.Read | PermissionMode.Write) == (pmode & (int)(PermissionMode.Read | PermissionMode.Write))) + if ((pmode & (int)(PermissionMode.Read | PermissionMode.Write)) == (int)(PermissionMode.Read | PermissionMode.Write)) { return FileShare.ReadWrite; } @@ -589,7 +589,7 @@ internal class FdiNotification internal short iCabinet; // USHORT internal short iFolder; // USHORT internal int fdie; // FDIERROR - }; + } internal enum FdiNotificationType : int { @@ -607,7 +607,7 @@ internal class FdiERF internal int erfOper; internal int erfType; internal bool fError; - }; + } internal sealed class FdiContextHandle : SafeHandleZeroOrMinusOneIsInvalid { diff --git a/src/System.Management.Automation/help/CommandHelpProvider.cs b/src/System.Management.Automation/help/CommandHelpProvider.cs index e6eafa8704f..05a4e48af70 100644 --- a/src/System.Management.Automation/help/CommandHelpProvider.cs +++ b/src/System.Management.Automation/help/CommandHelpProvider.cs @@ -84,7 +84,7 @@ internal override HelpCategory HelpCategory #region Help Provider Interface - private void GetModulePaths(CommandInfo commandInfo, out string moduleName, out string moduleDir, out string nestedModulePath) + private static void GetModulePaths(CommandInfo commandInfo, out string moduleName, out string moduleDir, out string nestedModulePath) { Dbg.Assert(commandInfo != null, "Caller should verify that commandInfo != null"); @@ -132,7 +132,7 @@ private void GetModulePaths(CommandInfo commandInfo, out string moduleName, out } } - private string GetHelpName(CommandInfo commandInfo) + private static string GetHelpName(CommandInfo commandInfo) { Dbg.Assert(commandInfo != null, "Caller should verify that commandInfo != null"); @@ -1250,7 +1250,7 @@ private static bool Match(string target, ICollection patterns) /// The result helpInfo objects after processing. internal override IEnumerable ProcessForwardedHelp(HelpInfo helpInfo, HelpRequest helpRequest) { - HelpCategory categoriesHandled = (HelpCategory.Alias + const HelpCategory categoriesHandled = (HelpCategory.Alias | HelpCategory.ExternalScript | HelpCategory.Filter | HelpCategory.Function | HelpCategory.ScriptCommand); if ((helpInfo.HelpCategory & categoriesHandled) != 0) diff --git a/src/System.Management.Automation/help/HelpCommands.cs b/src/System.Management.Automation/help/HelpCommands.cs index e67caa40db8..edf8d9e4355 100644 --- a/src/System.Management.Automation/help/HelpCommands.cs +++ b/src/System.Management.Automation/help/HelpCommands.cs @@ -516,7 +516,7 @@ private void ValidateAndThrowIfError(HelpCategory cat) } // categories that support -Parameter, -Role, -Functionality, -Component parameters - HelpCategory supportedCategories = + const HelpCategory supportedCategories = HelpCategory.Alias | HelpCategory.Cmdlet | HelpCategory.ExternalScript | HelpCategory.Filter | HelpCategory.Function | HelpCategory.ScriptCommand; diff --git a/src/System.Management.Automation/help/HelpCommentsParser.cs b/src/System.Management.Automation/help/HelpCommentsParser.cs index beda31bfd8e..21ac7b9e79d 100644 --- a/src/System.Management.Automation/help/HelpCommentsParser.cs +++ b/src/System.Management.Automation/help/HelpCommentsParser.cs @@ -496,7 +496,7 @@ private void BuildSyntaxForParameterSet(XmlElement command, XmlElement syntax, M private static void GetExampleSections(string content, out string prompt_str, out string code_str, out string remarks_str) { - string default_prompt_str = "PS > "; + const string default_prompt_str = "PS > "; var promptMatch = Regex.Match(content, "^.*?>"); prompt_str = promptMatch.Success ? promptMatch.Value : default_prompt_str; diff --git a/src/System.Management.Automation/help/HelpFileHelpProvider.cs b/src/System.Management.Automation/help/HelpFileHelpProvider.cs index 36ffeb58675..8900a7167b3 100644 --- a/src/System.Management.Automation/help/HelpFileHelpProvider.cs +++ b/src/System.Management.Automation/help/HelpFileHelpProvider.cs @@ -268,7 +268,7 @@ internal override IEnumerable SearchHelp(HelpRequest helpRequest, bool } } - private void GetModuleNameAndVersion(string psmodulePathRoot, string filePath, out string moduleName, out Version moduleVersion) + private static void GetModuleNameAndVersion(string psmodulePathRoot, string filePath, out string moduleName, out Version moduleVersion) { moduleVersion = null; moduleName = null; diff --git a/src/System.Management.Automation/help/HelpSystem.cs b/src/System.Management.Automation/help/HelpSystem.cs index bb7c1d0de9b..a7c86bd5ebd 100644 --- a/src/System.Management.Automation/help/HelpSystem.cs +++ b/src/System.Management.Automation/help/HelpSystem.cs @@ -803,7 +803,9 @@ internal void ClearScriptBlockTokenCache() internal class HelpProgressEventArgs : EventArgs { internal bool Completed { get; set; } + internal string Activity { get; set; } + internal int PercentComplete { get; set; } } diff --git a/src/System.Management.Automation/help/MUIFileSearcher.cs b/src/System.Management.Automation/help/MUIFileSearcher.cs index 301369959aa..bf6244fe3eb 100644 --- a/src/System.Management.Automation/help/MUIFileSearcher.cs +++ b/src/System.Management.Automation/help/MUIFileSearcher.cs @@ -113,7 +113,7 @@ private void SearchForFiles() } } - private string[] GetFiles(string path, string pattern) + private static string[] GetFiles(string path, string pattern) { #if UNIX // On Linux, file names are case sensitive, so we need to add diff --git a/src/System.Management.Automation/help/MamlNode.cs b/src/System.Management.Automation/help/MamlNode.cs index 4392dffd0ca..fe4e803a294 100644 --- a/src/System.Management.Automation/help/MamlNode.cs +++ b/src/System.Management.Automation/help/MamlNode.cs @@ -646,7 +646,7 @@ private PSObject[] GetMamlFormattingPSObjects(XmlNode xmlNode) /// /// /// - private int GetParaMamlNodeCount(XmlNodeList nodes) + private static int GetParaMamlNodeCount(XmlNodeList nodes) { int i = 0; diff --git a/src/System.Management.Automation/help/PSClassHelpProvider.cs b/src/System.Management.Automation/help/PSClassHelpProvider.cs index ee65529a026..e4c74c6398a 100644 --- a/src/System.Management.Automation/help/PSClassHelpProvider.cs +++ b/src/System.Management.Automation/help/PSClassHelpProvider.cs @@ -80,11 +80,9 @@ internal override IEnumerable SearchHelp(HelpRequest helpRequest, bool else patternList.Add(target); - bool useWildCards = true; - foreach (string pattern in patternList) { - PSClassSearcher searcher = new PSClassSearcher(pattern, useWildCards, _context); + PSClassSearcher searcher = new PSClassSearcher(pattern, useWildCards: true, _context); foreach (var helpInfo in GetHelpInfo(searcher)) { @@ -108,10 +106,7 @@ internal override IEnumerable ExactMatchHelp(HelpRequest helpRequest) yield return null; } - string target = helpRequest.Target; - bool useWildCards = false; - - PSClassSearcher searcher = new PSClassSearcher(target, useWildCards, _context); + PSClassSearcher searcher = new PSClassSearcher(helpRequest.Target, useWildCards: false, _context); foreach (var helpInfo in GetHelpInfo(searcher)) { diff --git a/src/System.Management.Automation/help/SaveHelpCommand.cs b/src/System.Management.Automation/help/SaveHelpCommand.cs index 3c4d18af00a..7059550730b 100644 --- a/src/System.Management.Automation/help/SaveHelpCommand.cs +++ b/src/System.Management.Automation/help/SaveHelpCommand.cs @@ -484,7 +484,7 @@ public override object Transform(EngineIntrinsics engineIntrinsics, object input return inputData; } - private bool TryConvertFromDeserializedModuleInfo(object inputData, out PSModuleInfo moduleInfo) + private static bool TryConvertFromDeserializedModuleInfo(object inputData, out PSModuleInfo moduleInfo) { moduleInfo = null; PSObject pso = inputData as PSObject; diff --git a/src/System.Management.Automation/help/UpdatableHelpCommandBase.cs b/src/System.Management.Automation/help/UpdatableHelpCommandBase.cs index 9697ffb2f25..6bd8b6e84b4 100644 --- a/src/System.Management.Automation/help/UpdatableHelpCommandBase.cs +++ b/src/System.Management.Automation/help/UpdatableHelpCommandBase.cs @@ -299,9 +299,9 @@ private Dictionary, UpdatableHelpModuleInfo> GetModuleInf } } - // Match wildcards - WildcardOptions wildcardOptions = WildcardOptions.IgnoreCase | WildcardOptions.CultureInvariant; - IEnumerable patternList = SessionStateUtilities.CreateWildcardsFromStrings(new string[1] { moduleNamePattern }, wildcardOptions); + IEnumerable patternList = SessionStateUtilities.CreateWildcardsFromStrings( + globPatterns: new[] { moduleNamePattern }, + options: WildcardOptions.IgnoreCase | WildcardOptions.CultureInvariant); foreach (KeyValuePair name in s_metadataCache) { @@ -784,7 +784,7 @@ private IEnumerable RecursiveResolvePathHelper(string path) { yield return path; - foreach (string subDirectory in Directory.GetDirectories(path)) + foreach (string subDirectory in Directory.EnumerateDirectories(path)) { foreach (string subDirectory2 in RecursiveResolvePathHelper(subDirectory)) { diff --git a/src/System.Management.Automation/help/UpdatableHelpSystem.cs b/src/System.Management.Automation/help/UpdatableHelpSystem.cs index add71bd55b5..d302f7b9cae 100644 --- a/src/System.Management.Automation/help/UpdatableHelpSystem.cs +++ b/src/System.Management.Automation/help/UpdatableHelpSystem.cs @@ -513,6 +513,9 @@ private string ResolveUri(string baseUri, bool verbose) private const string HelpInfoXmlNamespace = "http://schemas.microsoft.com/powershell/help/2010/05"; private const string HelpInfoXmlValidationFailure = "HelpInfoXmlValidationFailure"; + private const string MamlXmlNamespace = "http://schemas.microsoft.com/maml/2004/10"; + private const string CommandXmlNamespace = "http://schemas.microsoft.com/maml/dev/command/2004/10"; + private const string DscResourceXmlNamespace = "http://schemas.microsoft.com/maml/dev/dscResource/2004/10"; /// /// Creates a HelpInfo object. @@ -586,8 +589,9 @@ internal UpdatableHelpInfo CreateHelpInfo(string xml, string moduleName, Guid mo if (!string.IsNullOrEmpty(currentCulture)) { - WildcardOptions wildcardOptions = WildcardOptions.IgnoreCase | WildcardOptions.CultureInvariant; - IEnumerable patternList = SessionStateUtilities.CreateWildcardsFromStrings(new string[1] { currentCulture }, wildcardOptions); + IEnumerable patternList = SessionStateUtilities.CreateWildcardsFromStrings( + globPatterns: new[] { currentCulture }, + options: WildcardOptions.IgnoreCase | WildcardOptions.CultureInvariant); for (int i = 0; i < updatableHelpItem.Length; i++) { @@ -617,7 +621,7 @@ internal UpdatableHelpInfo CreateHelpInfo(string xml, string moduleName, Guid mo /// Xml schema. /// Validation event handler. /// HelpInfo or HelpContent? - private XmlDocument CreateValidXmlDocument(string xml, string ns, string schema, ValidationEventHandler handler, + private static XmlDocument CreateValidXmlDocument(string xml, string ns, string schema, ValidationEventHandler handler, bool helpInfo) { XmlReaderSettings settings = new XmlReaderSettings(); @@ -994,7 +998,7 @@ internal void GenerateHelpInfo(string moduleName, Guid moduleGuid, string conten /// Removes the read only attribute. /// /// - private void RemoveReadOnly(string path) + private static void RemoveReadOnly(string path) { if (File.Exists(path)) { @@ -1089,7 +1093,7 @@ internal void InstallHelpContent(UpdatableHelpCommandType commandType, Execution } #if UNIX - private bool ExpandArchive(string source, string destination) + private static bool ExpandArchive(string source, string destination) { bool sucessfulDecompression = false; @@ -1121,7 +1125,7 @@ private bool ExpandArchive(string source, string destination) /// Source path. /// Destination path. /// Is set to false if we find a single file placeholder.txt in cab. This means we no longer need to install help files. - private void UnzipHelpContent(ExecutionContext context, string srcPath, string destPath, out bool needToCopy) + private static void UnzipHelpContent(ExecutionContext context, string srcPath, string destPath, out bool needToCopy) { needToCopy = true; @@ -1305,8 +1309,6 @@ private void ValidateAndCopyHelpContent(string sourcePath, Collection de Debug.Assert(helpItemsNode != null, "helpItemsNode must not be null"); - string targetNamespace = "http://schemas.microsoft.com/maml/2004/10"; - foreach (XmlNode node in helpItemsNode.ChildNodes) { if (node.NodeType == XmlNodeType.Element) @@ -1315,11 +1317,11 @@ private void ValidateAndCopyHelpContent(string sourcePath, Collection de { if (node.LocalName.Equals("para", StringComparison.OrdinalIgnoreCase)) { - if (!node.NamespaceURI.Equals("http://schemas.microsoft.com/maml/2004/10", StringComparison.OrdinalIgnoreCase)) + if (!node.NamespaceURI.Equals(MamlXmlNamespace, StringComparison.OrdinalIgnoreCase)) { throw new UpdatableHelpSystemException("HelpContentXmlValidationFailure", StringUtil.Format(HelpDisplayStrings.HelpContentXmlValidationFailure, - StringUtil.Format(HelpDisplayStrings.HelpContentMustBeInTargetNamespace, targetNamespace)), ErrorCategory.InvalidData, null, null); + StringUtil.Format(HelpDisplayStrings.HelpContentMustBeInTargetNamespace, MamlXmlNamespace)), ErrorCategory.InvalidData, null, null); } else { @@ -1327,16 +1329,16 @@ private void ValidateAndCopyHelpContent(string sourcePath, Collection de } } - if (!node.NamespaceURI.Equals("http://schemas.microsoft.com/maml/dev/command/2004/10", StringComparison.OrdinalIgnoreCase) && - !node.NamespaceURI.Equals("http://schemas.microsoft.com/maml/dev/dscResource/2004/10", StringComparison.OrdinalIgnoreCase)) + if (!node.NamespaceURI.Equals(CommandXmlNamespace, StringComparison.OrdinalIgnoreCase) && + !node.NamespaceURI.Equals(DscResourceXmlNamespace, StringComparison.OrdinalIgnoreCase)) { throw new UpdatableHelpSystemException("HelpContentXmlValidationFailure", StringUtil.Format(HelpDisplayStrings.HelpContentXmlValidationFailure, - StringUtil.Format(HelpDisplayStrings.HelpContentMustBeInTargetNamespace, targetNamespace)), ErrorCategory.InvalidData, null, null); + StringUtil.Format(HelpDisplayStrings.HelpContentMustBeInTargetNamespace, MamlXmlNamespace)), ErrorCategory.InvalidData, null, null); } } - CreateValidXmlDocument(node.OuterXml, targetNamespace, xsd, + CreateValidXmlDocument(node.OuterXml, MamlXmlNamespace, xsd, new ValidationEventHandler(HelpContentValidationHandler), false); } diff --git a/src/System.Management.Automation/help/UpdateHelpCommand.cs b/src/System.Management.Automation/help/UpdateHelpCommand.cs index bccd7418476..01b17cbad7e 100644 --- a/src/System.Management.Automation/help/UpdateHelpCommand.cs +++ b/src/System.Management.Automation/help/UpdateHelpCommand.cs @@ -348,7 +348,7 @@ internal override bool ProcessModuleWithCulture(UpdatableHelpModuleInfo module, foreach (UpdatableHelpUri contentUri in newHelpInfo.HelpContentUriCollection) { - Version currentHelpVersion = (currentHelpInfo != null) ? currentHelpInfo.GetCultureVersion(contentUri.Culture) : null; + Version currentHelpVersion = currentHelpInfo?.GetCultureVersion(contentUri.Culture); string updateHelpShouldProcessAction = string.Format(CultureInfo.InvariantCulture, HelpDisplayStrings.UpdateHelpShouldProcessActionMessage, module.ModuleName, @@ -488,7 +488,7 @@ internal override bool ProcessModuleWithCulture(UpdatableHelpModuleInfo module, /// /// /// - private void ThrowPathMustBeValidContainersException(string path, Exception e) + private static void ThrowPathMustBeValidContainersException(string path, Exception e) { throw new UpdatableHelpSystemException("PathMustBeValidContainers", StringUtil.Format(HelpDisplayStrings.PathMustBeValidContainers, path), ErrorCategory.InvalidArgument, diff --git a/src/System.Management.Automation/logging/MshLog.cs b/src/System.Management.Automation/logging/MshLog.cs index 23c687b58ee..02a8990bc69 100644 --- a/src/System.Management.Automation/logging/MshLog.cs +++ b/src/System.Management.Automation/logging/MshLog.cs @@ -469,7 +469,8 @@ internal static void LogCommandLifecycleEvent(ExecutionContext executionContext, if (NeedToLogCommandLifecycleEvent(provider, executionContext)) { provider.LogCommandLifecycleEvent( - () => logContext ?? (logContext = GetLogContext(executionContext, invocationInfo)), commandState); + () => logContext ??= GetLogContext(executionContext, invocationInfo), + commandState); } } } @@ -1085,7 +1086,7 @@ internal enum Severity /// Informational. /// Informational - }; + } /// /// Enum for command states. @@ -1103,7 +1104,7 @@ internal enum CommandState /// /// Terminated = 2 - }; + } /// /// Enum for provider states. @@ -1117,7 +1118,7 @@ internal enum ProviderState /// /// Stopped = 1, - }; + } #endregion } diff --git a/src/System.Management.Automation/namespaces/ContainerProviderBase.cs b/src/System.Management.Automation/namespaces/ContainerProviderBase.cs index bd3e9957311..cc3e0ac83e2 100644 --- a/src/System.Management.Automation/namespaces/ContainerProviderBase.cs +++ b/src/System.Management.Automation/namespaces/ContainerProviderBase.cs @@ -999,7 +999,7 @@ protected virtual bool HasChildItems(string path) } /// - /// Copies an item at the specified path to an item at the . + /// Copies an item at the specified path to an item at the . /// /// /// The path of the item to copy. diff --git a/src/System.Management.Automation/namespaces/CoreCommandContext.cs b/src/System.Management.Automation/namespaces/CoreCommandContext.cs index 1422e256a47..5446b6b71cb 100644 --- a/src/System.Management.Automation/namespaces/CoreCommandContext.cs +++ b/src/System.Management.Automation/namespaces/CoreCommandContext.cs @@ -331,13 +331,13 @@ internal CmdletProviderContext( /// /// A collection in which objects that are written using the WriteObject(s) - /// methods are accumulated if is false. + /// methods are accumulated if is false. /// private Collection _accumulatedObjects = new Collection(); /// /// A collection in which objects that are written using the WriteError - /// method are accumulated if is false. + /// method are accumulated if is false. /// private Collection _accumulatedErrorObjects = new Collection(); diff --git a/src/System.Management.Automation/namespaces/FileSystemContentStream.cs b/src/System.Management.Automation/namespaces/FileSystemContentStream.cs index 51349970709..3c627542b4b 100644 --- a/src/System.Management.Automation/namespaces/FileSystemContentStream.cs +++ b/src/System.Management.Automation/namespaces/FileSystemContentStream.cs @@ -1515,7 +1515,7 @@ internal struct CPINFO [MarshalAs(UnmanagedType.ByValArray, SizeConst = MAX_LEADBYTES)] public byte[] LeadBytes; - }; + } /// /// Get information on a named code page. diff --git a/src/System.Management.Automation/namespaces/FileSystemProvider.cs b/src/System.Management.Automation/namespaces/FileSystemProvider.cs index d39733bed49..db619e3d15e 100644 --- a/src/System.Management.Automation/namespaces/FileSystemProvider.cs +++ b/src/System.Management.Automation/namespaces/FileSystemProvider.cs @@ -709,7 +709,7 @@ private void WinMapNetworkDrive(PSDriveInfo drive) /// /// /// - private bool IsNetworkMappedDrive(PSDriveInfo drive) + private static bool IsNetworkMappedDrive(PSDriveInfo drive) { bool shouldMapNetworkDrive = (drive != null && !string.IsNullOrEmpty(drive.Root) && PathIsNetworkPath(drive.Root)) && (drive.Persist || (drive.Credential != null && !drive.Credential.Equals(PSCredential.Empty))); @@ -789,7 +789,7 @@ private PSDriveInfo WinRemoveDrive(PSDriveInfo drive) /// PS Drive Info. /// /// True if the drive can be persisted or else false. - private bool IsSupportedDriveForPersistence(PSDriveInfo drive) + private static bool IsSupportedDriveForPersistence(PSDriveInfo drive) { bool isSupportedDriveForPersistence = false; if (drive != null && !string.IsNullOrEmpty(drive.Name) && drive.Name.Length == 1) @@ -1311,35 +1311,36 @@ protected override void GetItem(string path) // If we want to retrieve the file streams, retrieve them. if (retrieveStreams) { - if (!isContainer) + foreach (string desiredStream in dynamicParameters.Stream) { - foreach (string desiredStream in dynamicParameters.Stream) - { - // See that it matches the name specified - WildcardPattern p = WildcardPattern.Get(desiredStream, WildcardOptions.IgnoreCase | WildcardOptions.CultureInvariant); - bool foundStream = false; + // See that it matches the name specified + WildcardPattern p = WildcardPattern.Get(desiredStream, WildcardOptions.IgnoreCase | WildcardOptions.CultureInvariant); + bool foundStream = false; - foreach (AlternateStreamData stream in AlternateDataStreamUtilities.GetStreams(result.FullName)) + foreach (AlternateStreamData stream in AlternateDataStreamUtilities.GetStreams(result.FullName)) + { + if (!p.IsMatch(stream.Stream)) { - if (!p.IsMatch(stream.Stream)) { continue; } - - string outputPath = result.FullName + ":" + stream.Stream; - WriteItemObject(stream, outputPath, isContainer); - foundStream = true; + continue; } - if ((!WildcardPattern.ContainsWildcardCharacters(desiredStream)) && (!foundStream)) - { - string errorMessage = StringUtil.Format( - FileSystemProviderStrings.AlternateDataStreamNotFound, desiredStream, result.FullName); - Exception e = new FileNotFoundException(errorMessage, result.FullName); - - WriteError(new ErrorRecord( - e, - "AlternateDataStreamNotFound", - ErrorCategory.ObjectNotFound, - path)); - } + string outputPath = result.FullName + ":" + stream.Stream; + // Alternate data streams can never be containers. + WriteItemObject(stream, outputPath, isContainer: false); + foundStream = true; + } + + if ((!WildcardPattern.ContainsWildcardCharacters(desiredStream)) && (!foundStream)) + { + string errorMessage = StringUtil.Format( + FileSystemProviderStrings.AlternateDataStreamNotFound, desiredStream, result.FullName); + Exception e = new FileNotFoundException(errorMessage, result.FullName); + + WriteError(new ErrorRecord( + e, + "AlternateDataStreamNotFound", + ErrorCategory.ObjectNotFound, + path)); } } } @@ -2019,7 +2020,7 @@ string ToModeString(FileSystemInfo fileSystemInfo) FileAttributes fileAttributes = fileSystemInfo.Attributes; bool isReparsePoint = InternalSymbolicLinkLinkCodeMethods.IsReparsePoint(fileSystemInfo); - bool isLink = isReparsePoint || (excludeHardLink ? false : InternalSymbolicLinkLinkCodeMethods.IsHardLink(fileSystemInfo)); + bool isLink = isReparsePoint || (!excludeHardLink && InternalSymbolicLinkLinkCodeMethods.IsHardLink(fileSystemInfo)); if (!isLink) { // special casing for the common cases - no allocations @@ -2241,7 +2242,7 @@ protected override void RenameItem( /// Specify "directory" or "container" to create a directory. /// /// - /// If is "file" then this parameter becomes the content + /// If is "file" then this parameter becomes the content /// of the file to be created. /// /// @@ -2376,7 +2377,7 @@ protected override void NewItem( if (strTargetPath.StartsWith(".\\", StringComparison.OrdinalIgnoreCase) || strTargetPath.StartsWith("./", StringComparison.OrdinalIgnoreCase)) { - normalizedTargetPath = Path.Join(SessionState.Internal.CurrentLocation.ProviderPath, strTargetPath.AsSpan().Slice(2)); + normalizedTargetPath = Path.Join(SessionState.Internal.CurrentLocation.ProviderPath, strTargetPath.AsSpan(2)); } GetFileSystemInfo(normalizedTargetPath, out isDirectory); @@ -2721,7 +2722,7 @@ private enum ItemType SymbolicLink, Junction, HardLink - }; + } private static ItemType GetItemType(string input) { @@ -4195,7 +4196,7 @@ private void RemoveFunctionsPSCopyFileFromRemoteSession(System.Management.Automa return; } - string remoteScript = @" + const string remoteScript = @" Microsoft.PowerShell.Management\Remove-Item function:PSCopyFromSessionHelper -ea SilentlyContinue -Force Microsoft.PowerShell.Management\Remove-Item function:PSCopyRemoteUtils -ea SilentlyContinue -Force "; @@ -4203,7 +4204,7 @@ private void RemoveFunctionsPSCopyFileFromRemoteSession(System.Management.Automa SafeInvokeCommand.Invoke(ps, this, null, false); } - private bool ValidRemoteSessionForScripting(Runspace runspace) + private static bool ValidRemoteSessionForScripting(Runspace runspace) { if (runspace is not RemoteRunspace) { @@ -4373,7 +4374,7 @@ private bool PerformCopyFileFromRemoteSession(string sourceFileFullName, FileInf wStream = AlternateDataStreamUtilities.CreateFileStream(destinationFile.FullName, streamName, FileMode.Append, FileAccess.Write, FileShare.ReadWrite); } #endif - long fragmentSize = FILETRANSFERSIZE; + const long fragmentSize = FILETRANSFERSIZE; long copiedSoFar = 0; long currentIndex = 0; @@ -4506,7 +4507,7 @@ private void RemoveFunctionPSCopyFileToRemoteSession(System.Management.Automatio { if ((ps == null) || !ValidRemoteSessionForScripting(ps.Runspace)) { return; } - string remoteScript = @" + const string remoteScript = @" Microsoft.PowerShell.Management\Remove-Item function:PSCopyToSessionHelper -ea SilentlyContinue -Force Microsoft.PowerShell.Management\Remove-Item function:PSCopyRemoteUtils -ea SilentlyContinue -Force "; @@ -4624,7 +4625,7 @@ private bool CopyFileStreamToRemoteSession(FileInfo file, string destinationPath WriteProgress(progress); // 4MB gives the best results without spiking the resources on the remote connection. - int fragmentSize = FILETRANSFERSIZE; + const int fragmentSize = FILETRANSFERSIZE; byte[] fragment = null; int iteration = 0; bool success = false; @@ -4768,7 +4769,7 @@ private bool CopyFileStreamToRemoteSession(FileInfo file, string destinationPath // Returns a hash table with metadata about this file info. // - private Hashtable GetFileMetadata(FileInfo file) + private static Hashtable GetFileMetadata(FileInfo file) { Hashtable metadata = new Hashtable(); @@ -6137,7 +6138,7 @@ private void CopyAndDelete(DirectoryInfo directory, string destination, bool for } #if !UNIX - private bool IsSameWindowsVolume(string source, string destination) + private static bool IsSameWindowsVolume(string source, string destination) { FileInfo src = new FileInfo(source); FileInfo dest = new FileInfo(destination); @@ -6159,8 +6160,8 @@ private bool IsSameWindowsVolume(string source, string destination) /// /// The list of properties to get. Examples include "Attributes", "LastAccessTime," /// and other properties defined by - /// and - /// + /// and + /// /// public void GetProperty(string path, Collection providerSpecificPickList) { @@ -6663,7 +6664,14 @@ public IContentReader GetContentReader(string path) try { - if (Directory.Exists(path)) + // Get-Content will write a non-terminating error if the target is a directory. + // On Windows, the streamName must be null or empty for it to write the error. Otherwise, the + // alternate data stream is not a directory, even if it's set on a directory. + if (Directory.Exists(path) +#if !UNIX + && string.IsNullOrEmpty(streamName) +#endif + ) { string errMsg = StringUtil.Format(SessionStateStrings.GetContainerContentException, path); ErrorRecord error = new ErrorRecord(new InvalidOperationException(errMsg), "GetContainerContentException", ErrorCategory.InvalidOperation, null); @@ -6771,7 +6779,7 @@ public IContentWriter GetContentWriter(string path) bool usingByteEncoding = false; bool streamTypeSpecified = false; Encoding encoding = ClrFacade.GetDefaultEncoding(); - FileMode filemode = FileMode.OpenOrCreate; + const FileMode filemode = FileMode.OpenOrCreate; string streamName = null; bool suppressNewline = false; @@ -6818,7 +6826,14 @@ public IContentWriter GetContentWriter(string path) try { - if (Directory.Exists(path)) + // Add-Content and Set-Content will write a non-terminating error if the target is a directory. + // On Windows, the streamName must be null or empty for it to write the error. Otherwise, the + // alternate data stream is not a directory, even if it's set on a directory. + if (Directory.Exists(path) +#if !UNIX + && string.IsNullOrEmpty(streamName) +#endif + ) { string errMsg = StringUtil.Format(SessionStateStrings.WriteContainerContentException, path); ErrorRecord error = new ErrorRecord(new InvalidOperationException(errMsg), "WriteContainerContentException", ErrorCategory.InvalidOperation, null); @@ -6896,13 +6911,6 @@ public void ClearContent(string path) path = NormalizePath(path); - if (Directory.Exists(path)) - { - string errorMsg = StringUtil.Format(SessionStateStrings.ClearDirectoryContent, path); - WriteError(new ErrorRecord(new NotSupportedException(errorMsg), "ClearDirectoryContent", ErrorCategory.InvalidOperation, path)); - return; - } - try { #if !UNIX @@ -6954,6 +6962,26 @@ public void ClearContent(string path) clearStream = false; } +#endif + // On Windows, determine if our argument is a directory only after we determine if + // we're being asked to work with an alternate data stream, because directories can have + // alternate data streams on them that are not child items. These alternate data streams + // must be treated as data streams, even if they're attached to directories. However, + // if asked to work with a directory without a data stream specified, write a non-terminating + // error instead of clearing all child items of the directory. (On non-Windows, alternate + // data streams don't exist, so in that environment always write the error when addressing + // a directory.) + if (Directory.Exists(path) +#if !UNIX + && !clearStream +#endif + ) + { + string errorMsg = StringUtil.Format(SessionStateStrings.ClearDirectoryContent, path); + WriteError(new ErrorRecord(new NotSupportedException(errorMsg), "ClearDirectoryContent", ErrorCategory.InvalidOperation, path)); + return; + } +#if !UNIX if (clearStream) { FileStream fileStream = null; @@ -7837,8 +7865,6 @@ public static class InternalSymbolicLinkLinkCodeMethods // data is 16KB, plus there's a header. private const int MAX_REPARSE_SIZE = (16 * 1024) + REPARSE_GUID_DATA_BUFFER_HEADER_SIZE; - private const int ERROR_NOT_A_REPARSE_POINT = 4390; - private const int FSCTL_GET_REPARSE_POINT = 0x000900A8; private const int FSCTL_SET_REPARSE_POINT = 0x000900A4; @@ -8153,16 +8179,20 @@ private static string WinInternalGetLinkType(string filePath) // Get Buffer size IntPtr dangerousHandle = handle.DangerousGetHandle(); - bool result = DeviceIoControl(dangerousHandle, FSCTL_GET_REPARSE_POINT, - IntPtr.Zero, 0, outBuffer, outBufferSize, out bytesReturned, IntPtr.Zero); + bool result = DeviceIoControl( + dangerousHandle, + FSCTL_GET_REPARSE_POINT, + InBuffer: IntPtr.Zero, + nInBufferSize: 0, + outBuffer, + outBufferSize, + out bytesReturned, + lpOverlapped: IntPtr.Zero); if (!result) { - int lastError = Marshal.GetLastWin32Error(); - if (lastError == ERROR_NOT_A_REPARSE_POINT) - linkType = null; - else - throw new Win32Exception(lastError); + // It's not a reparse point or the file system doesn't support reparse points. + return IsHardLink(ref dangerousHandle) ? "HardLink" : null; } REPARSE_DATA_BUFFER_SYMBOLICLINK reparseDataBuffer = Marshal.PtrToStructure(outBuffer); @@ -8182,7 +8212,7 @@ private static string WinInternalGetLinkType(string filePath) break; default: - linkType = IsHardLink(ref dangerousHandle) ? "HardLink" : null; + linkType = null; break; } @@ -8287,10 +8317,10 @@ internal static bool IsSameFileSystemItem(string pathOne, string pathTwo) #if !UNIX private static bool WinIsSameFileSystemItem(string pathOne, string pathTwo) { - var access = FileAccess.Read; - var share = FileShare.Read; - var creation = FileMode.Open; - var attributes = FileAttributes.BackupSemantics | FileAttributes.PosixSemantics; + const FileAccess access = FileAccess.Read; + const FileShare share = FileShare.Read; + const FileMode creation = FileMode.Open; + const FileAttributes attributes = FileAttributes.BackupSemantics | FileAttributes.PosixSemantics; using (var sfOne = AlternateDataStreamUtilities.NativeMethods.CreateFile(pathOne, access, share, IntPtr.Zero, creation, (int)attributes, IntPtr.Zero)) using (var sfTwo = AlternateDataStreamUtilities.NativeMethods.CreateFile(pathTwo, access, share, IntPtr.Zero, creation, (int)attributes, IntPtr.Zero)) @@ -8326,10 +8356,10 @@ internal static bool GetInodeData(string path, out System.ValueTuple inodeData) { - var access = FileAccess.Read; - var share = FileShare.Read; - var creation = FileMode.Open; - var attributes = FileAttributes.BackupSemantics | FileAttributes.PosixSemantics; + const FileAccess access = FileAccess.Read; + const FileShare share = FileShare.Read; + const FileMode creation = FileMode.Open; + const FileAttributes attributes = FileAttributes.BackupSemantics | FileAttributes.PosixSemantics; using (var sf = AlternateDataStreamUtilities.NativeMethods.CreateFile(path, access, share, IntPtr.Zero, creation, (int)attributes, IntPtr.Zero)) { @@ -8399,16 +8429,20 @@ private static string WinInternalGetTarget(SafeFileHandle handle) // According to MSDN guidance DangerousAddRef() and DangerousRelease() have been used. handle.DangerousAddRef(ref success); - bool result = DeviceIoControl(handle.DangerousGetHandle(), FSCTL_GET_REPARSE_POINT, - IntPtr.Zero, 0, outBuffer, outBufferSize, out bytesReturned, IntPtr.Zero); + bool result = DeviceIoControl( + handle.DangerousGetHandle(), + FSCTL_GET_REPARSE_POINT, + InBuffer: IntPtr.Zero, + nInBufferSize: 0, + outBuffer, + outBufferSize, + out bytesReturned, + lpOverlapped: IntPtr.Zero); if (!result) { - int lastError = Marshal.GetLastWin32Error(); - if (lastError == ERROR_NOT_A_REPARSE_POINT) - return null; - - throw new Win32Exception(lastError); + // It's not a reparse point or the file system doesn't support reparse points. + return null; } string targetDir = null; @@ -8619,7 +8653,22 @@ internal static List GetStreams(string path) SafeFindHandle handle = NativeMethods.FindFirstStreamW( path, NativeMethods.StreamInfoLevels.FindStreamInfoStandard, findStreamData, 0); - if (handle.IsInvalid) throw new Win32Exception(); + + if (handle.IsInvalid) + { + int error = Marshal.GetLastWin32Error(); + + // Directories don't normally have alternate streams, so this is not an exceptional state. + // If a directory has no alternate data streams, FindFirstStreamW returns ERROR_HANDLE_EOF. + if (error == NativeMethods.ERROR_HANDLE_EOF) + { + return alternateStreams; + } + + // An unexpected error was returned, that we don't know how to interpret. The most helpful + // thing we can do at this point is simply throw the raw Win32 exception. + throw new Win32Exception(error); + } try { @@ -8629,7 +8678,7 @@ internal static List GetStreams(string path) findStreamData.Name = findStreamData.Name.Substring(1); // And trailing :$DATA (as long as it's not the default data stream) - string dataStream = ":$DATA"; + const string dataStream = ":$DATA"; if (!string.Equals(findStreamData.Name, dataStream, StringComparison.OrdinalIgnoreCase)) { findStreamData.Name = findStreamData.Name.Replace(dataStream, string.Empty); @@ -8754,6 +8803,7 @@ internal static void SetZoneOfOrigin(string path, SecurityZone securityZone) internal static class NativeMethods { internal const int ERROR_HANDLE_EOF = 38; + internal const int ERROR_INVALID_PARAMETER = 87; internal enum StreamInfoLevels { FindStreamInfoStandard = 0 } diff --git a/src/System.Management.Automation/namespaces/IContentWriter.cs b/src/System.Management.Automation/namespaces/IContentWriter.cs index eee05cacf13..621808af80c 100644 --- a/src/System.Management.Automation/namespaces/IContentWriter.cs +++ b/src/System.Management.Automation/namespaces/IContentWriter.cs @@ -4,6 +4,7 @@ using System.Collections; using System.IO; +#nullable enable namespace System.Management.Automation.Provider { #region IContentWriter diff --git a/src/System.Management.Automation/namespaces/IDynamicPropertyProvider.cs b/src/System.Management.Automation/namespaces/IDynamicPropertyProvider.cs index 6b8c69c270e..232f3f5d78b 100644 --- a/src/System.Management.Automation/namespaces/IDynamicPropertyProvider.cs +++ b/src/System.Management.Automation/namespaces/IDynamicPropertyProvider.cs @@ -1,10 +1,10 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. +#nullable enable namespace System.Management.Automation.Provider { #region IDynamicPropertyCmdletProvider - /// /// An interface that can be implemented on a Cmdlet provider to expose the dynamic /// manipulation of properties. @@ -61,7 +61,7 @@ void NewProperty( string path, string propertyName, string propertyTypeName, - object value); + object? value); /// /// Gives the provider an opportunity to attach additional parameters to the @@ -87,11 +87,11 @@ void NewProperty( /// /// The default implementation returns null. (no additional parameters) /// - object NewPropertyDynamicParameters( + object? NewPropertyDynamicParameters( string path, string propertyName, string propertyTypeName, - object value); + object? value); /// /// Removes a property on the item specified by the path. @@ -196,7 +196,7 @@ void RenameProperty( /// /// The default implementation returns null. (no additional parameters) /// - object RenamePropertyDynamicParameters( + object? RenamePropertyDynamicParameters( string path, string sourceProperty, string destinationProperty); @@ -262,7 +262,7 @@ void CopyProperty( /// /// The default implementation returns null. (no additional parameters) /// - object CopyPropertyDynamicParameters( + object? CopyPropertyDynamicParameters( string sourcePath, string sourceProperty, string destinationPath, @@ -328,7 +328,7 @@ void MoveProperty( /// /// The default implementation returns null. (no additional parameters) /// - object MovePropertyDynamicParameters( + object? MovePropertyDynamicParameters( string sourcePath, string sourceProperty, string destinationPath, diff --git a/src/System.Management.Automation/namespaces/IPropertiesProvider.cs b/src/System.Management.Automation/namespaces/IPropertiesProvider.cs index 555037635ef..1f4a6c168fe 100644 --- a/src/System.Management.Automation/namespaces/IPropertiesProvider.cs +++ b/src/System.Management.Automation/namespaces/IPropertiesProvider.cs @@ -3,6 +3,7 @@ using System.Collections.ObjectModel; +#nullable enable namespace System.Management.Automation.Provider { #region IPropertyCmdletProvider @@ -58,7 +59,7 @@ public interface IPropertyCmdletProvider /// void GetProperty( string path, - Collection providerSpecificPickList); + Collection? providerSpecificPickList); /// /// Gives the provider an opportunity to attach additional parameters to the @@ -79,9 +80,9 @@ void GetProperty( /// /// The default implementation returns null. (no additional parameters) /// - object GetPropertyDynamicParameters( + object? GetPropertyDynamicParameters( string path, - Collection providerSpecificPickList); + Collection? providerSpecificPickList); /// /// Sets the specified properties of the item at the specified path. @@ -137,7 +138,7 @@ void SetProperty( /// /// The default implementation returns null. (no additional parameters) /// - object SetPropertyDynamicParameters( + object? SetPropertyDynamicParameters( string path, PSObject propertyValue); @@ -191,7 +192,7 @@ void ClearProperty( /// /// The default implementation returns null. (no additional parameters) /// - object ClearPropertyDynamicParameters( + object? ClearPropertyDynamicParameters( string path, Collection propertyToClear); } diff --git a/src/System.Management.Automation/namespaces/LocationGlobber.cs b/src/System.Management.Automation/namespaces/LocationGlobber.cs index 4aaa3549d65..e4ab1f3cfc5 100644 --- a/src/System.Management.Automation/namespaces/LocationGlobber.cs +++ b/src/System.Management.Automation/namespaces/LocationGlobber.cs @@ -52,7 +52,7 @@ internal sealed class LocationGlobber /// The instance of session state on which this location globber acts. /// /// - /// If is null. + /// If is null. /// internal LocationGlobber(SessionState sessionState) { @@ -1666,7 +1666,7 @@ internal bool IsAbsolutePath(string path, out string driveName) /// The path with the glob characters unescaped. /// /// - /// If is null. + /// If is null. /// private static string RemoveGlobEscaping(string path) { @@ -1699,7 +1699,7 @@ private static string RemoveGlobEscaping(string path) /// false otherwise. /// /// - /// If is null. + /// If is null. /// /// /// The comparison is done using a case-insensitive comparison using the @@ -1763,7 +1763,7 @@ internal bool IsShellVirtualDrive(string driveName, out SessionStateScope scope) /// /// /// This out parameter returns the drive that was specified - /// by the . If is + /// by the . If is /// an absolute path this value may be something other than /// the current working drive. /// @@ -1789,7 +1789,7 @@ internal bool IsShellVirtualDrive(string driveName, out SessionStateScope scope) /// This is internal so that it can be called from SessionState /// /// - /// If is null. + /// If is null. /// /// /// If the refers to a drive that could not be found. @@ -2272,7 +2272,7 @@ internal string GenerateRelativePath( return driveRootRelativeWorkingPath; } - private bool HasRelativePathTokens(string path) + private static bool HasRelativePathTokens(string path) { string comparePath = path.Replace('/', '\\'); @@ -2417,7 +2417,7 @@ private static string ParseProviderPath(string path, out string providerId) /// paths. Instead an appropriate path will be returned as if it did exist. /// /// - /// The provider that will be used to glob the . + /// The provider that will be used to glob the . /// /// /// The context under which the command is occurring. @@ -3273,27 +3273,27 @@ internal static string RemoveProviderQualifier(string path) /// /// Generates a collection of containers and/or leaves that are children of the containers /// in the currentDirs parameter and match the glob expression in the - /// parameter. + /// parameter. /// /// /// A collection of paths that should be searched for leaves that match the - /// expression. + /// expression. /// /// /// The drive the Msh path is relative to. /// /// /// A single element of a path that may or may not contain a glob expression. This parameter - /// is used to search the containers in for children that + /// is used to search the containers in for children that /// match the glob expression. /// /// - /// True if the is the last element to glob over. If false, we + /// True if the is the last element to glob over. If false, we /// need to get all container names from the provider even if they don't match the filter. /// /// /// The provider associated with the paths that are being passed in the - /// and parameters. + /// and parameters. /// The provider must derive from ContainerCmdletProvider or NavigationCmdletProvider /// in order to get globbing. /// @@ -3302,10 +3302,10 @@ internal static string RemoveProviderQualifier(string path) /// /// /// A collection of fully qualified namespace paths whose leaf element matches the - /// expression. + /// expression. /// /// - /// If or + /// If or /// is null. /// /// @@ -3892,24 +3892,24 @@ internal Collection ExpandGlobPath( /// /// Generates a collection of containers and/or leaves that are children of the containers /// in the currentDirs parameter and match the glob expression in the - /// parameter. + /// parameter. /// /// /// A collection of paths that should be searched for leaves that match the - /// expression. + /// expression. /// /// /// A single element of a path that may or may not contain a glob expression. This parameter - /// is used to search the containers in for children that + /// is used to search the containers in for children that /// match the glob expression. /// /// - /// True if the is the last element to glob over. If false, we + /// True if the is the last element to glob over. If false, we /// need to get all container names from the provider even if they don't match the filter. /// /// /// The provider associated with the paths that are being passed in the - /// and parameters. + /// and parameters. /// The provider must derive from ContainerCmdletProvider or NavigationCmdletProvider /// in order to get globbing. /// @@ -3918,10 +3918,10 @@ internal Collection ExpandGlobPath( /// /// /// A collection of fully qualified namespace paths whose leaf element matches the - /// expression. + /// expression. /// /// - /// If or + /// If or /// is null. /// /// diff --git a/src/System.Management.Automation/namespaces/RegistryProvider.cs b/src/System.Management.Automation/namespaces/RegistryProvider.cs index 23160e63897..1898c960620 100644 --- a/src/System.Management.Automation/namespaces/RegistryProvider.cs +++ b/src/System.Management.Automation/namespaces/RegistryProvider.cs @@ -1819,7 +1819,7 @@ public void GetProperty( // as the property name when adding the note, as // PSObject does not allow an empty propertyName - notePropertyName = GetLocalizedDefaultToken(); + notePropertyName = LocalizedDefaultToken; } propertyResults.Properties.Add(new PSNoteProperty(notePropertyName, key.GetValue(valueName))); @@ -2024,7 +2024,7 @@ public void ClearProperty( string propertyNameToAdd = valueName; if (string.IsNullOrEmpty(valueName)) { - propertyNameToAdd = GetLocalizedDefaultToken(); + propertyNameToAdd = LocalizedDefaultToken; } result.Properties.Add(new PSNoteProperty(propertyNameToAdd, defaultValue)); @@ -2956,7 +2956,7 @@ private string NormalizePath(string path) return result; } - private bool HasRelativePathTokens(string path) + private static bool HasRelativePathTokens(string path) { return ( path.StartsWith('\\') || @@ -3056,7 +3056,7 @@ private void GetFilteredRegistryKeyProperties(string path, if (!string.IsNullOrEmpty(requestedValueName)) { - valueNameToMatch = GetLocalizedDefaultToken(); + valueNameToMatch = LocalizedDefaultToken; } } @@ -3071,7 +3071,7 @@ private void GetFilteredRegistryKeyProperties(string path, // as the property name when adding the note, as // PSObject does not allow an empty propertyName - valueNameToMatch = GetLocalizedDefaultToken(); + valueNameToMatch = LocalizedDefaultToken; } hadAMatch = true; @@ -3195,7 +3195,7 @@ private object ResetRegistryKeyValue(IRegistryWrapper key, string valueName) /// /// true if the path is empty, a \ or a /, else false /// - private bool IsHiveContainer(string path) + private static bool IsHiveContainer(string path) { bool result = false; if (path == null) @@ -3783,7 +3783,7 @@ private void WriteWrappedPropertyObject(object value, string propertyName, strin string propertyNameToAdd = propertyName; if (string.IsNullOrEmpty(propertyName)) { - propertyNameToAdd = GetLocalizedDefaultToken(); + propertyNameToAdd = LocalizedDefaultToken; } result.Properties.Add(new PSNoteProperty(propertyNameToAdd, value)); @@ -3835,7 +3835,7 @@ private static object ConvertValueToKind(object value, RegistryValueKind kind) value = 0; } } - + break; case RegistryValueKind.ExpandString: @@ -4033,7 +4033,7 @@ private void WriteRegistryItemObject( if (string.IsNullOrEmpty(valueNames[index])) { // The first unnamed value becomes the default value - valueNames[index] = GetLocalizedDefaultToken(); + valueNames[index] = LocalizedDefaultToken; break; } } @@ -4108,16 +4108,13 @@ private bool ParseKind(string type, out RegistryValueKind kind) /// Gets the default value name token from the resource. /// In English that token is "(default)" without the quotes. /// + /// + /// This should not be localized as it will break scripts. + /// /// /// A string containing the default value name. /// - private string GetLocalizedDefaultToken() - { - // This shouldn't be localized as it will break scripts - - string defaultValueName = "(default)"; - return defaultValueName; - } + private static string LocalizedDefaultToken => "(default)"; /// /// Converts an empty or null userEnteredPropertyName to the localized @@ -4140,7 +4137,7 @@ private string GetPropertyName(string userEnteredPropertyName) if (stringComparer.Compare( userEnteredPropertyName, - GetLocalizedDefaultToken(), + LocalizedDefaultToken, CompareOptions.IgnoreCase) == 0) { result = null; diff --git a/src/System.Management.Automation/namespaces/RegistrySecurity.cs b/src/System.Management.Automation/namespaces/RegistrySecurity.cs index ad355ac6638..9308c50dddc 100644 --- a/src/System.Management.Automation/namespaces/RegistrySecurity.cs +++ b/src/System.Management.Automation/namespaces/RegistrySecurity.cs @@ -164,7 +164,7 @@ public void SetSecurityDescriptor( /// Specifies the parts of a security descriptor to create. /// /// - /// An instance of object. + /// An instance of object. /// /// and are not used by this method. public ObjectSecurity NewSecurityDescriptorFromPath( @@ -191,7 +191,7 @@ public ObjectSecurity NewSecurityDescriptorFromPath( /// Specifies the parts of a security descriptor to create. /// /// - /// An instance of object. + /// An instance of object. /// public ObjectSecurity NewSecurityDescriptorOfType( string type, diff --git a/src/System.Management.Automation/namespaces/RegistryWrapper.cs b/src/System.Management.Automation/namespaces/RegistryWrapper.cs index d3a44564dba..0e8e0558312 100644 --- a/src/System.Management.Automation/namespaces/RegistryWrapper.cs +++ b/src/System.Management.Automation/namespaces/RegistryWrapper.cs @@ -20,21 +20,33 @@ namespace Microsoft.PowerShell.Commands internal interface IRegistryWrapper { void SetValue(string name, object value); + void SetValue(string name, object value, RegistryValueKind valueKind); + string[] GetValueNames(); + void DeleteValue(string name); + string[] GetSubKeyNames(); + IRegistryWrapper CreateSubKey(string subkey); + IRegistryWrapper OpenSubKey(string name, bool writable); + void DeleteSubKeyTree(string subkey); + object GetValue(string name); + object GetValue(string name, object defaultValue, RegistryValueOptions options); + RegistryValueKind GetValueKind(string name); object RegistryKey { get; } void SetAccessControl(ObjectSecurity securityDescriptor); + ObjectSecurity GetAccessControl(AccessControlSections includeSections); + void Close(); string Name { get; } diff --git a/src/System.Management.Automation/resources/PSConfigurationStrings.resx b/src/System.Management.Automation/resources/PSConfigurationStrings.resx new file mode 100644 index 00000000000..a1671d7f9e8 --- /dev/null +++ b/src/System.Management.Automation/resources/PSConfigurationStrings.resx @@ -0,0 +1,123 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + PowerShell has stopped working because of a security issue: Cannot read the configuration file: {0} + + diff --git a/src/System.Management.Automation/resources/RunspaceInit.resx b/src/System.Management.Automation/resources/RunspaceInit.resx index c4a485121c7..ac900465d7d 100644 --- a/src/System.Management.Automation/resources/RunspaceInit.resx +++ b/src/System.Management.Automation/resources/RunspaceInit.resx @@ -153,6 +153,9 @@ The text encoding used when piping text to a native executable file + + Configuration controlling how text is rendered. + Variable to contain the name of the email server. This can be used instead of the HostName parameter in the Send-MailMessage cmdlet. diff --git a/src/System.Management.Automation/security/Authenticode.cs b/src/System.Management.Automation/security/Authenticode.cs index 584087a6e69..0abdafa956c 100644 --- a/src/System.Management.Automation/security/Authenticode.cs +++ b/src/System.Management.Automation/security/Authenticode.cs @@ -292,7 +292,7 @@ internal static Signature GetSignature(string fileName, string fileContent) [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2001:AvoidCallingProblematicMethods")] private static Signature GetSignatureFromCatalog(string filename) { - if (Signature.CatalogApiAvailable.HasValue && !Signature.CatalogApiAvailable.GetValueOrDefault()) + if (Signature.CatalogApiAvailable.HasValue && !Signature.CatalogApiAvailable.Value) { // Signature.CatalogApiAvailable would be set to false the first time it is detected that // WTGetSignatureInfo API does not exist on the platform, or if the API is not functional on the target platform. diff --git a/src/System.Management.Automation/security/CatalogHelper.cs b/src/System.Management.Automation/security/CatalogHelper.cs index f984976b33d..0c1c76b63e4 100644 --- a/src/System.Management.Automation/security/CatalogHelper.cs +++ b/src/System.Management.Automation/security/CatalogHelper.cs @@ -409,8 +409,8 @@ internal static string CalculateFileHash(string filePath, string hashAlgorithm) _cmdlet.ThrowTerminatingError(errorRecord); } - DWORD GENERIC_READ = 0x80000000; - DWORD OPEN_EXISTING = 3; + const DWORD GENERIC_READ = 0x80000000; + const DWORD OPEN_EXISTING = 3; IntPtr INVALID_HANDLE_VALUE = new IntPtr(-1); // Open the file that is to be hashed for reading and get its handle diff --git a/src/System.Management.Automation/security/MshSignature.cs b/src/System.Management.Automation/security/MshSignature.cs index 221472a12d2..96ff8a9638a 100644 --- a/src/System.Management.Automation/security/MshSignature.cs +++ b/src/System.Management.Automation/security/MshSignature.cs @@ -71,7 +71,7 @@ public enum SignatureStatus /// with the current system. /// Incompatible - }; + } /// /// Defines the valid types of signatures. @@ -92,7 +92,7 @@ public enum SignatureType /// The signature is a catalog signature. /// Catalog = 2 - }; + } /// /// Represents a digital signature on a signed @@ -389,5 +389,5 @@ private static string GetSignatureStatusMessage(SignatureStatus status, return message; } - }; + } } diff --git a/src/System.Management.Automation/security/SecurityManager.cs b/src/System.Management.Automation/security/SecurityManager.cs index b3967bcb834..1b554ad3940 100644 --- a/src/System.Management.Automation/security/SecurityManager.cs +++ b/src/System.Management.Automation/security/SecurityManager.cs @@ -368,7 +368,7 @@ private bool CheckPolicy(ExternalScriptInfo script, PSHost host, out Exception r return policyCheckPassed; } - private bool SetPolicyFromAuthenticodePrompt(string path, PSHost host, ref Exception reason, Signature signature) + private static bool SetPolicyFromAuthenticodePrompt(string path, PSHost host, ref Exception reason, Signature signature) { bool policyCheckPassed = false; @@ -398,14 +398,14 @@ private bool SetPolicyFromAuthenticodePrompt(string path, PSHost host, ref Excep reason = new UnauthorizedAccessException(reasonMessage); policyCheckPassed = false; } - + break; } return policyCheckPassed; } - private bool IsLocalFile(string filename) + private static bool IsLocalFile(string filename) { #if UNIX return true; @@ -425,7 +425,7 @@ private bool IsLocalFile(string filename) // Checks that a publisher is trusted by the system or is one of // the signed product binaries - private bool IsTrustedPublisher(Signature signature, string file) + private static bool IsTrustedPublisher(Signature signature, string file) { // Get the thumbprint of the current signature X509Certificate2 signerCertificate = signature.SignerCertificate; @@ -444,7 +444,7 @@ private bool IsTrustedPublisher(Signature signature, string file) return false; } - private bool IsUntrustedPublisher(Signature signature, string file) + private static bool IsUntrustedPublisher(Signature signature, string file) { // Get the thumbprint of the current signature X509Certificate2 signerCertificate = signature.SignerCertificate; @@ -467,7 +467,7 @@ private bool IsUntrustedPublisher(Signature signature, string file) /// Trust a publisher by adding it to the "Trusted Publishers" store. /// /// - private void TrustPublisher(Signature signature) + private static void TrustPublisher(Signature signature) { // Get the certificate of the signer X509Certificate2 signerCertificate = signature.SignerCertificate; @@ -485,7 +485,7 @@ private void TrustPublisher(Signature signature) } } - private void UntrustPublisher(Signature signature) + private static void UntrustPublisher(Signature signature) { // Get the certificate of the signer X509Certificate2 signerCertificate = signature.SignerCertificate; @@ -516,7 +516,7 @@ private void UntrustPublisher(Signature signature) } } - private Signature GetSignatureWithEncodingRetry(string path, ExternalScriptInfo script) + private static Signature GetSignatureWithEncodingRetry(string path, ExternalScriptInfo script) { string verificationContents = System.Text.Encoding.Unicode.GetString(script.OriginalEncoding.GetPreamble()) + script.ScriptContents; Signature signature = SignatureHelper.GetSignature(path, verificationContents); @@ -640,7 +640,7 @@ protected internal override bool ShouldRun(CommandInfo commandInfo, return allowRun; } - private RunPromptDecision AuthenticodePrompt(string path, + private static RunPromptDecision AuthenticodePrompt(string path, Signature signature, PSHost host) { @@ -713,7 +713,7 @@ private RunPromptDecision AuthenticodePrompt(string path, return decision; } - private RunPromptDecision RemoteFilePrompt(string path, PSHost host) + private static RunPromptDecision RemoteFilePrompt(string path, PSHost host) { if ((host == null) || (host.UI == null)) { @@ -743,7 +743,7 @@ private RunPromptDecision RemoteFilePrompt(string path, PSHost host) } } - private Collection GetAuthenticodePromptChoices() + private static Collection GetAuthenticodePromptChoices() { Collection choices = new Collection(); @@ -764,7 +764,7 @@ private Collection GetAuthenticodePromptChoices() return choices; } - private Collection GetRemoteFilePromptChoices() + private static Collection GetRemoteFilePromptChoices() { Collection choices = new Collection(); diff --git a/src/System.Management.Automation/security/SecuritySupport.cs b/src/System.Management.Automation/security/SecuritySupport.cs index 4303075d8eb..809c13efb3f 100644 --- a/src/System.Management.Automation/security/SecuritySupport.cs +++ b/src/System.Management.Automation/security/SecuritySupport.cs @@ -63,7 +63,7 @@ public enum ExecutionPolicy /// Default - The most restrictive policy available. /// Default = Restricted - }; + } /// /// Defines the available configuration scopes for an execution diff --git a/src/System.Management.Automation/security/nativeMethods.cs b/src/System.Management.Automation/security/nativeMethods.cs index e6ca212c274..37e29c1f7cb 100644 --- a/src/System.Management.Automation/security/nativeMethods.cs +++ b/src/System.Management.Automation/security/nativeMethods.cs @@ -556,7 +556,7 @@ internal enum CryptUIFlags { CRYPTUI_WIZ_NO_UI = 0x0001 // other flags not used - }; + } [StructLayout(LayoutKind.Sequential)] internal struct CRYPTUI_WIZ_DIGITAL_SIGN_INFO @@ -575,14 +575,14 @@ internal struct CRYPTUI_WIZ_DIGITAL_SIGN_INFO internal DWORD dwAdditionalCertChoice; internal IntPtr pSignExtInfo; // PCCRYPTUI_WIZ_DIGITAL_SIGN_EXTENDED_INFO - }; + } [Flags] internal enum SignInfoSubjectChoice { CRYPTUI_WIZ_DIGITAL_SIGN_SUBJECT_FILE = 0x01 // CRYPTUI_WIZ_DIGITAL_SIGN_SUBJECT_BLOB = 0x02 NotUsed - }; + } [Flags] internal enum SignInfoCertChoice @@ -590,14 +590,14 @@ internal enum SignInfoCertChoice CRYPTUI_WIZ_DIGITAL_SIGN_CERT = 0x01 // CRYPTUI_WIZ_DIGITAL_SIGN_STORE = 0x02, NotUsed // CRYPTUI_WIZ_DIGITAL_SIGN_PVK = 0x03, NotUsed - }; + } [Flags] internal enum SignInfoAdditionalCertChoice { CRYPTUI_WIZ_DIGITAL_SIGN_ADD_CHAIN = 1, CRYPTUI_WIZ_DIGITAL_SIGN_ADD_CHAIN_NO_ROOT = 2 - }; + } [StructLayout(LayoutKind.Sequential)] internal struct CRYPTUI_WIZ_DIGITAL_SIGN_EXTENDED_INFO @@ -618,7 +618,7 @@ internal struct CRYPTUI_WIZ_DIGITAL_SIGN_EXTENDED_INFO internal IntPtr hAdditionalCertStoreNotUsed; // HCERTSTORE internal IntPtr psAuthenticatedNotUsed; // PCRYPT_ATTRIBUTES internal IntPtr psUnauthenticatedNotUsed; // PCRYPT_ATTRIBUTES - }; + } [ArchitectureSensitive] internal static CRYPTUI_WIZ_DIGITAL_SIGN_EXTENDED_INFO @@ -806,7 +806,7 @@ internal struct WINTRUST_FILE_INFO internal IntPtr hFileNotUsed; // optional, HANDLE to pcwszFilePath internal IntPtr pgKnownSubjectNotUsed; // optional: GUID* : fill if the // subject type is known - }; + } [StructLayoutAttribute(LayoutKind.Sequential)] internal struct WINTRUST_BLOB_INFO @@ -871,7 +871,7 @@ internal enum WintrustUIChoice WTD_UI_NONE = 2, WTD_UI_NOBAD = 3, WTD_UI_NOGOOD = 4 - }; + } [Flags] internal enum WintrustUnionChoice @@ -881,7 +881,7 @@ internal enum WintrustUnionChoice WTD_CHOICE_BLOB = 3, // WTD_CHOICE_SIGNER = 4, // WTD_CHOICE_CERT = 5, - }; + } [Flags] internal enum WintrustProviderFlags @@ -899,7 +899,7 @@ internal enum WintrustProviderFlags WTD_USE_DEFAULT_OSVER_CHECK = 0x00000400, WTD_LIFETIME_SIGNING_FLAG = 0x00000800, WTD_CACHE_ONLY_URL_RETRIEVAL = 0x00001000 - }; + } [Flags] internal enum WintrustAction @@ -909,7 +909,7 @@ internal enum WintrustAction WTD_STATEACTION_CLOSE = 0x00000002, WTD_STATEACTION_AUTO_CACHE = 0x00000003, WTD_STATEACTION_AUTO_CACHE_FLUSH = 0x00000004 - }; + } [StructLayoutAttribute(LayoutKind.Explicit)] internal struct WinTrust_Choice @@ -1103,7 +1103,7 @@ internal struct CRYPT_PROVIDER_CERT private DWORD _dwCtlError; private BOOL _fIsCyclic; private IntPtr _pChainElement; // PCERT_CHAIN_ELEMENT - }; + } [StructLayout(LayoutKind.Sequential)] internal struct CRYPT_PROVIDER_SGNR @@ -1118,7 +1118,7 @@ internal struct CRYPT_PROVIDER_SGNR internal DWORD csCounterSigners; internal IntPtr pasCounterSigners; // CRYPT_PROVIDER_SGNR* private IntPtr _pChainContext; // PCCERT_CHAIN_CONTEXT - }; + } [DllImport("wintrust.dll", SetLastError = true, CharSet = CharSet.Unicode)] internal static extern @@ -1210,7 +1210,7 @@ internal struct CERT_ENHKEY_USAGE // [MarshalAs(UnmanagedType.LPArray, ArraySubType=UnmanagedType.LPStr, SizeParamIndex=0)] // internal string[] rgpszUsageIdentifier; // LPSTR* internal IntPtr rgpszUsageIdentifier; - }; + } internal enum SIGNATURE_STATE { @@ -1877,7 +1877,7 @@ internal static bool IsSystem32DllPresent(string DllName) NativeMethods.LOAD_LIBRARY_AS_DATAFILE | NativeMethods.LOAD_LIBRARY_AS_IMAGE_RESOURCE | NativeMethods.LOAD_LIBRARY_SEARCH_SYSTEM32); - if (IntPtr.Zero != module) + if (module != IntPtr.Zero) { FreeLibrary(module); DllExists = true; @@ -1955,19 +1955,19 @@ internal struct SIP_INDIRECT_DATA } [StructLayout(LayoutKind.Sequential)] - internal struct CRYPTCATCDF + internal readonly struct CRYPTCATCDF { - private DWORD _cbStruct; - private IntPtr _hFile; - private DWORD _dwCurFilePos; - private DWORD _dwLastMemberOffset; - private BOOL _fEOF; + private readonly DWORD _cbStruct; + private readonly IntPtr _hFile; + private readonly DWORD _dwCurFilePos; + private readonly DWORD _dwLastMemberOffset; + private readonly BOOL _fEOF; [MarshalAs(UnmanagedType.LPWStr)] - private string _pwszResultDir; + private readonly string _pwszResultDir; - private IntPtr _hCATStore; - }; + private readonly IntPtr _hCATStore; + } [StructLayout(LayoutKind.Sequential)] internal struct CRYPTCATMEMBER @@ -1988,7 +1988,7 @@ internal struct CRYPTCATMEMBER internal IntPtr hReserved; internal CRYPT_ATTR_BLOB sEncodedIndirectData; internal CRYPT_ATTR_BLOB sEncodedMemberInfo; - }; + } [StructLayout(LayoutKind.Sequential)] internal struct CRYPTCATATTRIBUTE @@ -2002,7 +2002,7 @@ internal struct CRYPTCATATTRIBUTE internal DWORD cbValue; internal System.IntPtr pbValue; private DWORD _dwReserved; - }; + } [StructLayout(LayoutKind.Sequential)] internal struct CRYPTCATSTORE @@ -2020,7 +2020,7 @@ internal struct CRYPTCATSTORE private IntPtr _hAttrs; private IntPtr _hCryptMsg; private IntPtr _hSorted; - }; + } [DllImport("wintrust.dll", CharSet = CharSet.Unicode)] internal static extern IntPtr CryptCATCDFOpen( diff --git a/src/System.Management.Automation/security/wldpNativeMethods.cs b/src/System.Management.Automation/security/wldpNativeMethods.cs index 5d4b49270c3..0eb53dbcb3a 100644 --- a/src/System.Management.Automation/security/wldpNativeMethods.cs +++ b/src/System.Management.Automation/security/wldpNativeMethods.cs @@ -78,28 +78,31 @@ public static SystemEnforcementMode GetSystemLockdownPolicy() /// An EnforcementMode that describes policy. public static SystemEnforcementMode GetLockdownPolicy(string path, SafeHandle handle) { - // Check the WLDP API - SystemEnforcementMode lockdownPolicy = GetWldpPolicy(path, handle); - if (lockdownPolicy == SystemEnforcementMode.Enforce) + // Check the WLDP File policy via API + var wldpFilePolicy = GetWldpPolicy(path, handle); + if (wldpFilePolicy == SystemEnforcementMode.Enforce) { - return lockdownPolicy; + return wldpFilePolicy; + } + + // Check the AppLocker File policy via API + // This needs to be checked before WLDP audit policy + // So, that we don't end up in Audit mode, + // when we should be enforce mode. + var appLockerFilePolicy = GetAppLockerPolicy(path, handle); + if (appLockerFilePolicy == SystemEnforcementMode.Enforce) + { + return appLockerFilePolicy; } // At this point, LockdownPolicy = Audit or Allowed. // If there was a WLDP policy, but WLDP didn't block it, // then it was explicitly allowed. Therefore, return the result for the file. SystemEnforcementMode systemWldpPolicy = s_cachedWldpSystemPolicy.GetValueOrDefault(SystemEnforcementMode.None); - if ((systemWldpPolicy == SystemEnforcementMode.Enforce) || - (systemWldpPolicy == SystemEnforcementMode.Audit)) - { - return lockdownPolicy; - } - - // Check the AppLocker API - lockdownPolicy = GetAppLockerPolicy(path, handle); - if (lockdownPolicy == SystemEnforcementMode.Enforce) + if ((systemWldpPolicy == SystemEnforcementMode.Audit) || + (systemWldpPolicy == SystemEnforcementMode.Enforce)) { - return lockdownPolicy; + return wldpFilePolicy; } // If there was a system-wide AppLocker policy, but AppLocker didn't block it, @@ -107,7 +110,7 @@ public static SystemEnforcementMode GetLockdownPolicy(string path, SafeHandle ha if (s_cachedSaferSystemPolicy.GetValueOrDefault(SaferPolicy.Allowed) == SaferPolicy.Disallowed) { - return lockdownPolicy; + return appLockerFilePolicy; } // If it's not set to 'Enforce' by the platform, allow debug overrides @@ -230,7 +233,7 @@ private static SystemEnforcementMode GetAppLockerPolicy(string path, SafeHandle // AppLocker fails when you try to check a policy on a file // with no content. So create a scratch file and test on that. - string dtAppLockerTestFileContents = AppLockerTestFileContents + DateTime.Now; + string dtAppLockerTestFileContents = AppLockerTestFileContents + Environment.TickCount64; IO.File.WriteAllText(testPathScript, dtAppLockerTestFileContents); IO.File.WriteAllText(testPathModule, dtAppLockerTestFileContents); } diff --git a/src/System.Management.Automation/utils/CommandDiscoveryExceptions.cs b/src/System.Management.Automation/utils/CommandDiscoveryExceptions.cs index 81b011d389a..e08d8e1a65c 100644 --- a/src/System.Management.Automation/utils/CommandDiscoveryExceptions.cs +++ b/src/System.Management.Automation/utils/CommandDiscoveryExceptions.cs @@ -161,7 +161,7 @@ params object[] messageArgs ) { object[] a; - if (messageArgs != null && 0 < messageArgs.Length) + if (messageArgs != null && messageArgs.Length > 0) { a = new object[messageArgs.Length + 1]; a[0] = commandName; diff --git a/src/System.Management.Automation/utils/CryptoUtils.cs b/src/System.Management.Automation/utils/CryptoUtils.cs index c75acdf1aff..96877437da2 100644 --- a/src/System.Management.Automation/utils/CryptoUtils.cs +++ b/src/System.Management.Automation/utils/CryptoUtils.cs @@ -627,18 +627,6 @@ protected void Dispose(bool disposing) } } - /// - /// Destructor. - /// - ~PSRSACryptoServiceProvider() - { - // When Dispose() is called, GC.SuppressFinalize() - // is called and therefore this finalizer will not - // be invoked. Hence this is run only on process - // shutdown - Dispose(true); - } - #endregion IDisposable } diff --git a/src/System.Management.Automation/utils/EncodingUtils.cs b/src/System.Management.Automation/utils/EncodingUtils.cs index 33ff3c7f598..e9802488006 100644 --- a/src/System.Management.Automation/utils/EncodingUtils.cs +++ b/src/System.Management.Automation/utils/EncodingUtils.cs @@ -64,7 +64,7 @@ internal static Encoding Convert(Cmdlet cmdlet, string encoding) if (encodingMap.TryGetValue(encoding, out foundEncoding)) { // Write a warning if using utf7 as it is obsolete in .NET5 - if (string.Compare(encoding, Utf7, StringComparison.OrdinalIgnoreCase) == 0) + if (string.Equals(encoding, Utf7, StringComparison.OrdinalIgnoreCase)) { cmdlet.WriteWarning(PathUtilsStrings.Utf7EncodingObsolete); } diff --git a/src/System.Management.Automation/utils/ExecutionExceptions.cs b/src/System.Management.Automation/utils/ExecutionExceptions.cs index eb392f7536a..226a9cb8cdd 100644 --- a/src/System.Management.Automation/utils/ExecutionExceptions.cs +++ b/src/System.Management.Automation/utils/ExecutionExceptions.cs @@ -285,9 +285,7 @@ public ProviderInfo ProviderInfo { get { - return (_providerInvocationException == null) - ? null - : _providerInvocationException.ProviderInfo; + return _providerInvocationException?.ProviderInfo; } } @@ -296,7 +294,7 @@ public ProviderInfo ProviderInfo #region Internal private static Exception GetInnerException(Exception e) { - return (e == null) ? null : e.InnerException; + return e?.InnerException; } #endregion Internal } @@ -709,7 +707,7 @@ public override string Message { get { - return _message ?? (_message = (_wrapperException != null) ? _wrapperException.Message : string.Empty); + return _message ??= (_wrapperException != null) ? _wrapperException.Message : string.Empty; } } diff --git a/src/System.Management.Automation/utils/HostInterfacesExceptions.cs b/src/System.Management.Automation/utils/HostInterfacesExceptions.cs index dab2568a2f7..c70a007d0f1 100644 --- a/src/System.Management.Automation/utils/HostInterfacesExceptions.cs +++ b/src/System.Management.Automation/utils/HostInterfacesExceptions.cs @@ -101,6 +101,7 @@ class HostException : RuntimeException : base(info, context) { } + #endregion #region private private void SetDefaultErrorRecord() diff --git a/src/System.Management.Automation/utils/IObjectWriter.cs b/src/System.Management.Automation/utils/IObjectWriter.cs index 226082be67e..49181e34584 100644 --- a/src/System.Management.Automation/utils/IObjectWriter.cs +++ b/src/System.Management.Automation/utils/IObjectWriter.cs @@ -160,7 +160,7 @@ public override void Flush() public override int Write(object obj) { - int numberOfObjectsWritten = 1; + const int numberOfObjectsWritten = 1; _count += numberOfObjectsWritten; return numberOfObjectsWritten; } diff --git a/src/System.Management.Automation/utils/ObjectReader.cs b/src/System.Management.Automation/utils/ObjectReader.cs index 5b5e588f6e6..f06243ddd5b 100644 --- a/src/System.Management.Automation/utils/ObjectReader.cs +++ b/src/System.Management.Automation/utils/ObjectReader.cs @@ -21,7 +21,7 @@ internal abstract class ObjectReaderBase : PipelineReader, IDisposable /// /// The stream to read. /// Thrown if the specified stream is null. - public ObjectReaderBase([In, Out] ObjectStreamBase stream) + protected ObjectReaderBase([In, Out] ObjectStreamBase stream) { if (stream == null) { @@ -617,7 +617,7 @@ protected override void Dispose(bool disposing) } } - private ReturnType ConvertToReturnType(object inputObject) + private static ReturnType ConvertToReturnType(object inputObject) { Type resultType = typeof(ReturnType); if (typeof(PSObject) == resultType || typeof(object) == resultType) @@ -793,7 +793,7 @@ public override ReturnType Peek() /// /// Input object to convert. /// Input object converted to the specified return type. - private ReturnType ConvertToReturnType(object inputObject) + private static ReturnType ConvertToReturnType(object inputObject) { Type resultType = typeof(ReturnType); if (typeof(PSObject) == resultType || typeof(object) == resultType) diff --git a/src/System.Management.Automation/utils/ObjectStream.cs b/src/System.Management.Automation/utils/ObjectStream.cs index 807292fd3d8..2f4cbef8a08 100644 --- a/src/System.Management.Automation/utils/ObjectStream.cs +++ b/src/System.Management.Automation/utils/ObjectStream.cs @@ -1403,7 +1403,7 @@ internal override int Write(object obj, bool enumerateCollection) // subtraction to ensure we don't have an // overflow exception int freeSpace = _capacity - _objects.Count; - if (0 >= freeSpace) + if (freeSpace <= 0) { // NOTE: lock is released in finally continue; diff --git a/src/System.Management.Automation/utils/ParameterBinderExceptions.cs b/src/System.Management.Automation/utils/ParameterBinderExceptions.cs index baee153558d..841523f6bdb 100644 --- a/src/System.Management.Automation/utils/ParameterBinderExceptions.cs +++ b/src/System.Management.Automation/utils/ParameterBinderExceptions.cs @@ -384,7 +384,7 @@ public ParameterBindingException( /// public override string Message { - get { return _message ?? (_message = BuildMessage()); } + get { return _message ??= BuildMessage(); } } private string _message; diff --git a/src/System.Management.Automation/utils/PathUtils.cs b/src/System.Management.Automation/utils/PathUtils.cs index ad92bc37fff..991e3fa63b6 100644 --- a/src/System.Management.Automation/utils/PathUtils.cs +++ b/src/System.Management.Automation/utils/PathUtils.cs @@ -23,13 +23,13 @@ internal static class PathUtils /// Cmdlet that is opening the file (used mainly for error reporting). /// Path to the file (as specified on the command line - this method will resolve the path). /// Encoding (this method will convert the command line string to an Encoding instance). - /// If true, then we will use default .NET encoding instead of the encoding specified in parameter. + /// If , then we will use default .NET encoding instead of the encoding specified in parameter. /// /// /// /// Result1: opened for writing. /// Result2: (inherits from ) opened for writing. - /// Result3: file info that should be used to restore file attributes after done with the file (null is this is not needed). + /// Result3: file info that should be used to restore file attributes after done with the file ( is this is not needed). /// True if wildcard expansion should be bypassed. internal static void MasterStreamOpen( PSCmdlet cmdlet, @@ -57,13 +57,13 @@ bool isLiteralPath /// Cmdlet that is opening the file (used mainly for error reporting). /// Path to the file (as specified on the command line - this method will resolve the path). /// Encoding (this method will convert the command line string to an Encoding instance). - /// If true, then we will use default .NET encoding instead of the encoding specified in parameter. + /// If , then we will use default .NET encoding instead of the encoding specified in parameter. /// /// /// /// Result1: opened for writing. /// Result2: (inherits from ) opened for writing. - /// Result3: file info that should be used to restore file attributes after done with the file (null is this is not needed). + /// Result3: file info that should be used to restore file attributes after done with the file ( is this is not needed). /// True if wildcard expansion should be bypassed. internal static void MasterStreamOpen( PSCmdlet cmdlet, diff --git a/src/System.Management.Automation/utils/PlatformInvokes.cs b/src/System.Management.Automation/utils/PlatformInvokes.cs index 6d76f8feb1a..c8dc6290511 100644 --- a/src/System.Management.Automation/utils/PlatformInvokes.cs +++ b/src/System.Management.Automation/utils/PlatformInvokes.cs @@ -32,7 +32,7 @@ public long ToTicks() { return ((long)dwHighDateTime << 32) + dwLowDateTime; } - }; + } [Flags] // dwDesiredAccess of CreateFile diff --git a/src/System.Management.Automation/utils/PowerShellETWTracer.cs b/src/System.Management.Automation/utils/PowerShellETWTracer.cs index 7631d760b2d..9c5e2046c87 100644 --- a/src/System.Management.Automation/utils/PowerShellETWTracer.cs +++ b/src/System.Management.Automation/utils/PowerShellETWTracer.cs @@ -866,7 +866,7 @@ private bool Trace(PowerShellTraceEvent traceEvent, PowerShellTraceLevel level, } } - return _provider.WriteEvent(ref ed, args); + return _provider.WriteEvent(in ed, args); } /// @@ -988,7 +988,7 @@ public void Dispose() /// public PowerShellTraceTask Task { get; set; } = PowerShellTraceTask.None; - private bool IsEtwSupported + private static bool IsEtwSupported { get { diff --git a/src/System.Management.Automation/utils/SessionStateExceptions.cs b/src/System.Management.Automation/utils/SessionStateExceptions.cs index b8b79af68a6..a08e7615dc5 100644 --- a/src/System.Management.Automation/utils/SessionStateExceptions.cs +++ b/src/System.Management.Automation/utils/SessionStateExceptions.cs @@ -543,7 +543,7 @@ private static string BuildMessage( params object[] messageArgs) { object[] a; - if (messageArgs != null && 0 < messageArgs.Length) + if (messageArgs != null && messageArgs.Length > 0) { a = new object[messageArgs.Length + 1]; a[0] = itemName; diff --git a/src/System.Management.Automation/utils/StructuredTraceSource.cs b/src/System.Management.Automation/utils/StructuredTraceSource.cs index 84eb6fa40ef..47b6e1b4e1d 100644 --- a/src/System.Management.Automation/utils/StructuredTraceSource.cs +++ b/src/System.Management.Automation/utils/StructuredTraceSource.cs @@ -1443,7 +1443,7 @@ internal static int ThreadIndentLevel /// internal TraceSource TraceSource { - get { return _traceSource ?? (_traceSource = new MonadTraceSource(_name)); } + get { return _traceSource ??= new MonadTraceSource(_name); } } private TraceSource _traceSource; diff --git a/src/System.Management.Automation/utils/tracing/EtwActivity.cs b/src/System.Management.Automation/utils/tracing/EtwActivity.cs index 54e1034b1ac..b50f68e699d 100644 --- a/src/System.Management.Automation/utils/tracing/EtwActivity.cs +++ b/src/System.Management.Automation/utils/tracing/EtwActivity.cs @@ -255,7 +255,7 @@ public void Callback(IAsyncResult asyncResult) private static readonly Dictionary providers = new Dictionary(); private static readonly object syncLock = new object(); - private static EventDescriptor _WriteTransferEvent = new EventDescriptor(0x1f05, 0x1, 0x11, 0x5, 0x14, 0x0, (long)0x4000000000000000); + private static readonly EventDescriptor _WriteTransferEvent = new EventDescriptor(0x1f05, 0x1, 0x11, 0x5, 0x14, 0x0, (long)0x4000000000000000); private EventProvider currentProvider; @@ -328,7 +328,7 @@ public void CorrelateWithActivity(Guid parentActivityId) if (parentActivityId != Guid.Empty) { EventDescriptor transferEvent = TransferEvent; - provider.WriteTransferEvent(ref transferEvent, parentActivityId, activityId, parentActivityId); + provider.WriteTransferEvent(in transferEvent, parentActivityId, activityId, parentActivityId); } } @@ -473,7 +473,7 @@ protected void WriteEvent(EventDescriptor ed, params object[] payload) } } - bool success = provider.WriteEvent(ref ed, payload); + bool success = provider.WriteEvent(in ed, payload); if (EventWritten != null) { EventWritten.Invoke(this, new EtwEventArgs(ed, success, payload)); diff --git a/src/System.Management.Automation/utils/tracing/EtwActivityReverter.cs b/src/System.Management.Automation/utils/tracing/EtwActivityReverter.cs index a7a257ceb21..5154f637283 100644 --- a/src/System.Management.Automation/utils/tracing/EtwActivityReverter.cs +++ b/src/System.Management.Automation/utils/tracing/EtwActivityReverter.cs @@ -20,7 +20,7 @@ public interface IEtwActivityReverter : /// Reverts the ETW activity ID of the current thread to its original value. /// /// - /// Calling has the same effect as + /// Calling has the same effect as /// calling this method and is useful in the C# "using" syntax. /// void RevertCurrentActivityId(); diff --git a/src/System.Management.Automation/utils/tracing/EtwEventCorrelator.cs b/src/System.Management.Automation/utils/tracing/EtwEventCorrelator.cs index 4895a582223..a421b918eb8 100644 --- a/src/System.Management.Automation/utils/tracing/EtwEventCorrelator.cs +++ b/src/System.Management.Automation/utils/tracing/EtwEventCorrelator.cs @@ -12,6 +12,7 @@ namespace System.Management.Automation.Tracing /// An object that can be used to manage the ETW activity ID of the current thread. /// [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Etw")] +#nullable enable public interface IEtwEventCorrelator { /// @@ -19,8 +20,8 @@ public interface IEtwEventCorrelator /// /// /// This method should only be used for advanced scenarios - /// or diagnostics. Prefer using - /// or instead. + /// or diagnostics. Prefer using + /// or instead. /// Guid CurrentActivityId { get; set; } @@ -29,7 +30,7 @@ public interface IEtwEventCorrelator /// the new activity with another activity. /// /// The ID of an existing activity to be correlated with the - /// new activity or if correlation is not desired. + /// new activity or if correlation is not desired. /// An object which can be used to revert the activity ID of the current thread once /// the new activity yields control of the current thread. IEtwActivityReverter StartActivity(Guid relatedActivityId); @@ -42,9 +43,10 @@ public interface IEtwEventCorrelator /// the new activity yields control of the current thread. IEtwActivityReverter StartActivity(); } +#nullable restore /// - /// A simple implementation of . + /// A simple implementation of . /// [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Etw")] public class EtwEventCorrelator : @@ -54,11 +56,11 @@ public class EtwEventCorrelator : private readonly EventDescriptor _transferEvent; /// - /// Creates an . + /// Creates an . /// - /// The to use when logging transfer events + /// The to use when logging transfer events /// during activity correlation. - /// The to use when logging transfer events + /// The to use when logging transfer events /// during activity correlation. public EtwEventCorrelator(EventProvider transferProvider, EventDescriptor transferEvent) { @@ -72,7 +74,7 @@ public EtwEventCorrelator(EventProvider transferProvider, EventDescriptor transf } /// - /// Implements . + /// Implements . /// public Guid CurrentActivityId { @@ -88,7 +90,7 @@ public Guid CurrentActivityId } /// - /// Implements . + /// Implements . /// public IEtwActivityReverter StartActivity(Guid relatedActivityId) { @@ -98,14 +100,14 @@ public IEtwActivityReverter StartActivity(Guid relatedActivityId) if (relatedActivityId != Guid.Empty) { var tempTransferEvent = _transferEvent; - _transferProvider.WriteTransferEvent(ref tempTransferEvent, relatedActivityId); + _transferProvider.WriteTransferEvent(in tempTransferEvent, relatedActivityId); } return retActivity; } /// - /// Implements . + /// Implements . /// public IEtwActivityReverter StartActivity() { diff --git a/src/System.Management.Automation/utils/tracing/PSEtwLogProvider.cs b/src/System.Management.Automation/utils/tracing/PSEtwLogProvider.cs index b511a037294..03b6c9a558b 100755 --- a/src/System.Management.Automation/utils/tracing/PSEtwLogProvider.cs +++ b/src/System.Management.Automation/utils/tracing/PSEtwLogProvider.cs @@ -284,7 +284,7 @@ internal void WriteEvent(PSEventId id, PSChannel channel, PSOpcode opcode, PSLev EventDescriptor desc = new EventDescriptor((int)id, (byte)PSEventVersion.One, (byte)channel, (byte)level, (byte)opcode, (int)task, longKeyword); - etwProvider.WriteEvent(ref desc, args); + etwProvider.WriteEvent(in desc, args); } /// @@ -292,7 +292,7 @@ internal void WriteEvent(PSEventId id, PSChannel channel, PSOpcode opcode, PSLev /// internal void WriteTransferEvent(Guid parentActivityId) { - etwProvider.WriteTransferEvent(ref _xferEventDescriptor, parentActivityId, EtwActivity.GetActivityId(), parentActivityId); + etwProvider.WriteTransferEvent(in _xferEventDescriptor, parentActivityId, EtwActivity.GetActivityId(), parentActivityId); } /// diff --git a/src/System.Management.Automation/utils/tracing/TracingGen.cs b/src/System.Management.Automation/utils/tracing/TracingGen.cs index ea369e4513a..d6d5f5070bb 100644 --- a/src/System.Management.Automation/utils/tracing/TracingGen.cs +++ b/src/System.Management.Automation/utils/tracing/TracingGen.cs @@ -38,88 +38,88 @@ public sealed partial class Tracer : System.Management.Automation.Tracing.EtwAct public const long KeywordAll = 0xFFFFFFFF; private static Guid providerId = Guid.Parse("a0c1853b-5c40-4b15-8766-3cf1c58f985a"); - private static EventDescriptor WriteTransferEventEvent; - private static EventDescriptor DebugMessageEvent; - private static EventDescriptor M3PAbortingWorkflowExecutionEvent; - private static EventDescriptor M3PActivityExecutionFinishedEvent; - private static EventDescriptor M3PActivityExecutionQueuedEvent; - private static EventDescriptor M3PActivityExecutionStartedEvent; - private static EventDescriptor M3PBeginContainerParentJobExecutionEvent; - private static EventDescriptor M3PBeginCreateNewJobEvent; - private static EventDescriptor M3PBeginJobLogicEvent; - private static EventDescriptor M3PBeginProxyChildJobEventHandlerEvent; - private static EventDescriptor M3PBeginProxyJobEventHandlerEvent; - private static EventDescriptor M3PBeginProxyJobExecutionEvent; - private static EventDescriptor M3PBeginRunGarbageCollectionEvent; - private static EventDescriptor M3PBeginStartWorkflowApplicationEvent; - private static EventDescriptor M3PBeginWorkflowExecutionEvent; - private static EventDescriptor M3PCancellingWorkflowExecutionEvent; - private static EventDescriptor M3PChildWorkflowJobAdditionEvent; - private static EventDescriptor M3PEndContainerParentJobExecutionEvent; - private static EventDescriptor M3PEndCreateNewJobEvent; - private static EventDescriptor M3PEndJobLogicEvent; - private static EventDescriptor M3PEndpointDisabledEvent; - private static EventDescriptor M3PEndpointEnabledEvent; - private static EventDescriptor M3PEndpointModifiedEvent; - private static EventDescriptor M3PEndpointRegisteredEvent; - private static EventDescriptor M3PEndpointUnregisteredEvent; - private static EventDescriptor M3PEndProxyChildJobEventHandlerEvent; - private static EventDescriptor M3PEndProxyJobEventHandlerEvent; - private static EventDescriptor M3PEndProxyJobExecutionEvent; - private static EventDescriptor M3PEndRunGarbageCollectionEvent; - private static EventDescriptor M3PEndStartWorkflowApplicationEvent; - private static EventDescriptor M3PEndWorkflowExecutionEvent; - private static EventDescriptor M3PErrorImportingWorkflowFromXamlEvent; - private static EventDescriptor M3PForcedWorkflowShutdownErrorEvent; - private static EventDescriptor M3PForcedWorkflowShutdownFinishedEvent; - private static EventDescriptor M3PForcedWorkflowShutdownStartedEvent; - private static EventDescriptor M3PImportedWorkflowFromXamlEvent; - private static EventDescriptor M3PImportingWorkflowFromXamlEvent; - private static EventDescriptor M3PJobCreationCompleteEvent; - private static EventDescriptor M3PJobErrorEvent; - private static EventDescriptor M3PJobRemovedEvent; - private static EventDescriptor M3PJobRemoveErrorEvent; - private static EventDescriptor M3PJobStateChangedEvent; - private static EventDescriptor M3PLoadingWorkflowForExecutionEvent; - private static EventDescriptor M3POutOfProcessRunspaceStartedEvent; - private static EventDescriptor M3PParameterSplattingWasPerformedEvent; - private static EventDescriptor M3PParentJobCreatedEvent; - private static EventDescriptor M3PPersistenceStoreMaxSizeReachedEvent; - private static EventDescriptor M3PPersistingWorkflowEvent; - private static EventDescriptor M3PProxyJobRemoteJobAssociationEvent; - private static EventDescriptor M3PRemoveJobStartedEvent; - private static EventDescriptor M3PRunspaceAvailabilityChangedEvent; - private static EventDescriptor M3PRunspaceStateChangedEvent; - private static EventDescriptor M3PTrackingGuidContainerParentJobCorrelationEvent; - private static EventDescriptor M3PUnloadingWorkflowEvent; - private static EventDescriptor M3PWorkflowActivityExecutionFailedEvent; - private static EventDescriptor M3PWorkflowActivityValidatedEvent; - private static EventDescriptor M3PWorkflowActivityValidationFailedEvent; - private static EventDescriptor M3PWorkflowCleanupPerformedEvent; - private static EventDescriptor M3PWorkflowDeletedFromDiskEvent; - private static EventDescriptor M3PWorkflowEngineStartedEvent; - private static EventDescriptor M3PWorkflowExecutionAbortedEvent; - private static EventDescriptor M3PWorkflowExecutionCancelledEvent; - private static EventDescriptor M3PWorkflowExecutionErrorEvent; - private static EventDescriptor M3PWorkflowExecutionFinishedEvent; - private static EventDescriptor M3PWorkflowExecutionStartedEvent; - private static EventDescriptor M3PWorkflowJobCreatedEvent; - private static EventDescriptor M3PWorkflowLoadedForExecutionEvent; - private static EventDescriptor M3PWorkflowLoadedFromDiskEvent; - private static EventDescriptor M3PWorkflowManagerCheckpointEvent; - private static EventDescriptor M3PWorkflowPersistedEvent; - private static EventDescriptor M3PWorkflowPluginRequestedToShutdownEvent; - private static EventDescriptor M3PWorkflowPluginRestartedEvent; - private static EventDescriptor M3PWorkflowPluginStartedEvent; - private static EventDescriptor M3PWorkflowQuotaViolatedEvent; - private static EventDescriptor M3PWorkflowResumedEvent; - private static EventDescriptor M3PWorkflowResumingEvent; - private static EventDescriptor M3PWorkflowRunspacePoolCreatedEvent; - private static EventDescriptor M3PWorkflowStateChangedEvent; - private static EventDescriptor M3PWorkflowUnloadedEvent; - private static EventDescriptor M3PWorkflowValidationErrorEvent; - private static EventDescriptor M3PWorkflowValidationFinishedEvent; - private static EventDescriptor M3PWorkflowValidationStartedEvent; + private static readonly EventDescriptor WriteTransferEventEvent; + private static readonly EventDescriptor DebugMessageEvent; + private static readonly EventDescriptor M3PAbortingWorkflowExecutionEvent; + private static readonly EventDescriptor M3PActivityExecutionFinishedEvent; + private static readonly EventDescriptor M3PActivityExecutionQueuedEvent; + private static readonly EventDescriptor M3PActivityExecutionStartedEvent; + private static readonly EventDescriptor M3PBeginContainerParentJobExecutionEvent; + private static readonly EventDescriptor M3PBeginCreateNewJobEvent; + private static readonly EventDescriptor M3PBeginJobLogicEvent; + private static readonly EventDescriptor M3PBeginProxyChildJobEventHandlerEvent; + private static readonly EventDescriptor M3PBeginProxyJobEventHandlerEvent; + private static readonly EventDescriptor M3PBeginProxyJobExecutionEvent; + private static readonly EventDescriptor M3PBeginRunGarbageCollectionEvent; + private static readonly EventDescriptor M3PBeginStartWorkflowApplicationEvent; + private static readonly EventDescriptor M3PBeginWorkflowExecutionEvent; + private static readonly EventDescriptor M3PCancellingWorkflowExecutionEvent; + private static readonly EventDescriptor M3PChildWorkflowJobAdditionEvent; + private static readonly EventDescriptor M3PEndContainerParentJobExecutionEvent; + private static readonly EventDescriptor M3PEndCreateNewJobEvent; + private static readonly EventDescriptor M3PEndJobLogicEvent; + private static readonly EventDescriptor M3PEndpointDisabledEvent; + private static readonly EventDescriptor M3PEndpointEnabledEvent; + private static readonly EventDescriptor M3PEndpointModifiedEvent; + private static readonly EventDescriptor M3PEndpointRegisteredEvent; + private static readonly EventDescriptor M3PEndpointUnregisteredEvent; + private static readonly EventDescriptor M3PEndProxyChildJobEventHandlerEvent; + private static readonly EventDescriptor M3PEndProxyJobEventHandlerEvent; + private static readonly EventDescriptor M3PEndProxyJobExecutionEvent; + private static readonly EventDescriptor M3PEndRunGarbageCollectionEvent; + private static readonly EventDescriptor M3PEndStartWorkflowApplicationEvent; + private static readonly EventDescriptor M3PEndWorkflowExecutionEvent; + private static readonly EventDescriptor M3PErrorImportingWorkflowFromXamlEvent; + private static readonly EventDescriptor M3PForcedWorkflowShutdownErrorEvent; + private static readonly EventDescriptor M3PForcedWorkflowShutdownFinishedEvent; + private static readonly EventDescriptor M3PForcedWorkflowShutdownStartedEvent; + private static readonly EventDescriptor M3PImportedWorkflowFromXamlEvent; + private static readonly EventDescriptor M3PImportingWorkflowFromXamlEvent; + private static readonly EventDescriptor M3PJobCreationCompleteEvent; + private static readonly EventDescriptor M3PJobErrorEvent; + private static readonly EventDescriptor M3PJobRemovedEvent; + private static readonly EventDescriptor M3PJobRemoveErrorEvent; + private static readonly EventDescriptor M3PJobStateChangedEvent; + private static readonly EventDescriptor M3PLoadingWorkflowForExecutionEvent; + private static readonly EventDescriptor M3POutOfProcessRunspaceStartedEvent; + private static readonly EventDescriptor M3PParameterSplattingWasPerformedEvent; + private static readonly EventDescriptor M3PParentJobCreatedEvent; + private static readonly EventDescriptor M3PPersistenceStoreMaxSizeReachedEvent; + private static readonly EventDescriptor M3PPersistingWorkflowEvent; + private static readonly EventDescriptor M3PProxyJobRemoteJobAssociationEvent; + private static readonly EventDescriptor M3PRemoveJobStartedEvent; + private static readonly EventDescriptor M3PRunspaceAvailabilityChangedEvent; + private static readonly EventDescriptor M3PRunspaceStateChangedEvent; + private static readonly EventDescriptor M3PTrackingGuidContainerParentJobCorrelationEvent; + private static readonly EventDescriptor M3PUnloadingWorkflowEvent; + private static readonly EventDescriptor M3PWorkflowActivityExecutionFailedEvent; + private static readonly EventDescriptor M3PWorkflowActivityValidatedEvent; + private static readonly EventDescriptor M3PWorkflowActivityValidationFailedEvent; + private static readonly EventDescriptor M3PWorkflowCleanupPerformedEvent; + private static readonly EventDescriptor M3PWorkflowDeletedFromDiskEvent; + private static readonly EventDescriptor M3PWorkflowEngineStartedEvent; + private static readonly EventDescriptor M3PWorkflowExecutionAbortedEvent; + private static readonly EventDescriptor M3PWorkflowExecutionCancelledEvent; + private static readonly EventDescriptor M3PWorkflowExecutionErrorEvent; + private static readonly EventDescriptor M3PWorkflowExecutionFinishedEvent; + private static readonly EventDescriptor M3PWorkflowExecutionStartedEvent; + private static readonly EventDescriptor M3PWorkflowJobCreatedEvent; + private static readonly EventDescriptor M3PWorkflowLoadedForExecutionEvent; + private static readonly EventDescriptor M3PWorkflowLoadedFromDiskEvent; + private static readonly EventDescriptor M3PWorkflowManagerCheckpointEvent; + private static readonly EventDescriptor M3PWorkflowPersistedEvent; + private static readonly EventDescriptor M3PWorkflowPluginRequestedToShutdownEvent; + private static readonly EventDescriptor M3PWorkflowPluginRestartedEvent; + private static readonly EventDescriptor M3PWorkflowPluginStartedEvent; + private static readonly EventDescriptor M3PWorkflowQuotaViolatedEvent; + private static readonly EventDescriptor M3PWorkflowResumedEvent; + private static readonly EventDescriptor M3PWorkflowResumingEvent; + private static readonly EventDescriptor M3PWorkflowRunspacePoolCreatedEvent; + private static readonly EventDescriptor M3PWorkflowStateChangedEvent; + private static readonly EventDescriptor M3PWorkflowUnloadedEvent; + private static readonly EventDescriptor M3PWorkflowValidationErrorEvent; + private static readonly EventDescriptor M3PWorkflowValidationFinishedEvent; + private static readonly EventDescriptor M3PWorkflowValidationStartedEvent; /// /// Static constructor. diff --git a/src/TypeCatalogGen/TypeCatalogGen.cs b/src/TypeCatalogGen/TypeCatalogGen.cs index e05f8b63e13..993413bc59a 100644 --- a/src/TypeCatalogGen/TypeCatalogGen.cs +++ b/src/TypeCatalogGen/TypeCatalogGen.cs @@ -431,7 +431,7 @@ namespace System.Management.Automation {{ internal partial class PowerShellAssemblyLoadContext {{ - private Dictionary InitializeTypeCatalog() + private static Dictionary InitializeTypeCatalog() {{ return new Dictionary({0}, StringComparer.OrdinalIgnoreCase) {{"; const string SourceEnd = @" diff --git a/src/powershell/Program.cs b/src/powershell/Program.cs index 9f2af53e758..c885fa7fd2e 100644 --- a/src/powershell/Program.cs +++ b/src/powershell/Program.cs @@ -185,7 +185,6 @@ private static void AttemptExecPwshLogin(string[] args) // We can reuse this value later to prevent needing to call a .NET API // to generate our exec invocation. - // We don't care about argc's value, since argv[0] must always exist. // Skip over argc, but remember where exec_path is for later executablePathPtr = IntPtr.Add(procargs, sizeof(int)); @@ -321,7 +320,7 @@ private static int ExecPwshLogin(string[] args, string pwshPath, bool isMacOS) // // Since command_name is ignored and we can't use null (it's the terminator) // we use empty string - execArgs[4] = ""; + execArgs[4] = string.Empty; // Add the arguments passed to pwsh on the end. args.CopyTo(execArgs, 5); @@ -371,7 +370,7 @@ private static void CreatePwshInvocation( (string path, int quotedLength) invocationInfo) { // "exec " - string prefix = "exec "; + const string prefix = "exec "; prefix.AsSpan().CopyTo(strBuf); // The quoted path to pwsh, like "'/opt/microsoft/powershell/7/pwsh'" @@ -381,7 +380,7 @@ private static void CreatePwshInvocation( i += invocationInfo.quotedLength; // ' "$@"' the argument vector splat to pass pwsh arguments through - string suffix = " \"$@\""; + const string suffix = " \"$@\""; Span bufSuffix = strBuf.Slice(i); suffix.AsSpan().CopyTo(bufSuffix); } diff --git a/test/Test.Common.props b/test/Test.Common.props index 998cb665464..02ac0912eb9 100644 --- a/test/Test.Common.props +++ b/test/Test.Common.props @@ -1,4 +1,6 @@ + + PowerShell Test Microsoft Corporation diff --git a/test/common/markdown/package.json b/test/common/markdown/package.json index 99462871b52..cefe4fd4b90 100644 --- a/test/common/markdown/package.json +++ b/test/common/markdown/package.json @@ -7,8 +7,11 @@ "dependencies": { "gulp": "^4.0.2", "markdownlint": "^0.21.0", - "through2": "^4.0.2", - "yargs-parser": "13.1.2" + "through2": "^4.0.2" + }, + "resolutions": { + "yargs-parser": "^13.1.2" , + "y18n": "^5.0.5" }, "devDependencies": { "gulp-concat": "^2.6.1", diff --git a/test/common/markdown/yarn.lock b/test/common/markdown/yarn.lock index 9b80e9de744..1d86b0465ce 100644 --- a/test/common/markdown/yarn.lock +++ b/test/common/markdown/yarn.lock @@ -4,38 +4,38 @@ ansi-colors@^1.0.1: version "1.1.0" - resolved "https://registry.yarnpkg.com/ansi-colors/-/ansi-colors-1.1.0.tgz#6374b4dd5d4718ff3ce27a671a3b1cad077132a9" + resolved "https://registry.yarnpkg.com/ansi-colors/-/ansi-colors-1.1.0.tgz" integrity sha512-SFKX67auSNoVR38N3L+nvsPjOE0bybKTYbkf5tRvushrAPQ9V75huw0ZxBkKVeRU9kqH3d6HA4xTckbwZ4ixmA== dependencies: ansi-wrap "^0.1.0" ansi-gray@^0.1.1: version "0.1.1" - resolved "https://registry.yarnpkg.com/ansi-gray/-/ansi-gray-0.1.1.tgz#2962cf54ec9792c48510a3deb524436861ef7251" + resolved "https://registry.yarnpkg.com/ansi-gray/-/ansi-gray-0.1.1.tgz" integrity sha1-KWLPVOyXksSFEKPetSRDaGHvclE= dependencies: ansi-wrap "0.1.0" ansi-regex@^2.0.0: version "2.1.1" - resolved "https://registry.yarnpkg.com/ansi-regex/-/ansi-regex-2.1.1.tgz#c3b33ab5ee360d86e0e628f0468ae7ef27d654df" + resolved "https://registry.yarnpkg.com/ansi-regex/-/ansi-regex-2.1.1.tgz" integrity sha1-w7M6te42DYbg5ijwRorn7yfWVN8= ansi-styles@^3.2.1: version "3.2.1" - resolved "https://registry.yarnpkg.com/ansi-styles/-/ansi-styles-3.2.1.tgz#41fbb20243e50b12be0f04b8dedbf07520ce841d" + resolved "https://registry.yarnpkg.com/ansi-styles/-/ansi-styles-3.2.1.tgz" integrity sha512-VT0ZI6kZRdTh8YyJw3SMbYm/u+NqfsAxEpWO0Pf9sq8/e94WxxOpPKx9FR1FlyCtOVDNOQ+8ntlqFxiRc+r5qA== dependencies: color-convert "^1.9.0" ansi-wrap@0.1.0, ansi-wrap@^0.1.0: version "0.1.0" - resolved "https://registry.yarnpkg.com/ansi-wrap/-/ansi-wrap-0.1.0.tgz#a82250ddb0015e9a27ca82e82ea603bbfa45efaf" + resolved "https://registry.yarnpkg.com/ansi-wrap/-/ansi-wrap-0.1.0.tgz" integrity sha1-qCJQ3bABXponyoLoLqYDu/pF768= anymatch@^2.0.0: version "2.0.0" - resolved "https://registry.yarnpkg.com/anymatch/-/anymatch-2.0.0.tgz#bcb24b4f37934d9aa7ac17b4adaf89e7c76ef2eb" + resolved "https://registry.yarnpkg.com/anymatch/-/anymatch-2.0.0.tgz" integrity sha512-5teOsQWABXHHBFP9y3skS5P3d/WfWXpv3FUpy+LorMrNYaT9pI4oLMQX7jzQ2KklNpGpWHzdCXTDT2Y3XGlZBw== dependencies: micromatch "^3.1.4" @@ -43,60 +43,60 @@ anymatch@^2.0.0: append-buffer@^1.0.2: version "1.0.2" - resolved "https://registry.yarnpkg.com/append-buffer/-/append-buffer-1.0.2.tgz#d8220cf466081525efea50614f3de6514dfa58f1" + resolved "https://registry.yarnpkg.com/append-buffer/-/append-buffer-1.0.2.tgz" integrity sha1-2CIM9GYIFSXv6lBhTz3mUU36WPE= dependencies: buffer-equal "^1.0.0" archy@^1.0.0: version "1.0.0" - resolved "https://registry.yarnpkg.com/archy/-/archy-1.0.0.tgz#f9c8c13757cc1dd7bc379ac77b2c62a5c2868c40" + resolved "https://registry.yarnpkg.com/archy/-/archy-1.0.0.tgz" integrity sha1-+cjBN1fMHde8N5rHeyxipcKGjEA= argparse@^1.0.7: version "1.0.10" - resolved "https://registry.yarnpkg.com/argparse/-/argparse-1.0.10.tgz#bcd6791ea5ae09725e17e5ad988134cd40b3d911" + resolved "https://registry.yarnpkg.com/argparse/-/argparse-1.0.10.tgz" integrity sha512-o5Roy6tNG4SL/FOkCAN6RzjiakZS25RLYFrcMttJqbdd8BWrnA+fGz57iN5Pb06pvBGvl5gQ0B48dJlslXvoTg== dependencies: sprintf-js "~1.0.2" arr-diff@^4.0.0: version "4.0.0" - resolved "https://registry.yarnpkg.com/arr-diff/-/arr-diff-4.0.0.tgz#d6461074febfec71e7e15235761a329a5dc7c520" + resolved "https://registry.yarnpkg.com/arr-diff/-/arr-diff-4.0.0.tgz" integrity sha1-1kYQdP6/7HHn4VI1dhoyml3HxSA= arr-filter@^1.1.1: version "1.1.2" - resolved "https://registry.yarnpkg.com/arr-filter/-/arr-filter-1.1.2.tgz#43fdddd091e8ef11aa4c45d9cdc18e2dff1711ee" + resolved "https://registry.yarnpkg.com/arr-filter/-/arr-filter-1.1.2.tgz" integrity sha1-Q/3d0JHo7xGqTEXZzcGOLf8XEe4= dependencies: make-iterator "^1.0.0" arr-flatten@^1.0.1, arr-flatten@^1.1.0: version "1.1.0" - resolved "https://registry.yarnpkg.com/arr-flatten/-/arr-flatten-1.1.0.tgz#36048bbff4e7b47e136644316c99669ea5ae91f1" + resolved "https://registry.yarnpkg.com/arr-flatten/-/arr-flatten-1.1.0.tgz" integrity sha512-L3hKV5R/p5o81R7O02IGnwpDmkp6E982XhtbuwSe3O4qOtMMMtodicASA1Cny2U+aCXcNpml+m4dPsvsJ3jatg== arr-map@^2.0.0, arr-map@^2.0.2: version "2.0.2" - resolved "https://registry.yarnpkg.com/arr-map/-/arr-map-2.0.2.tgz#3a77345ffc1cf35e2a91825601f9e58f2e24cac4" + resolved "https://registry.yarnpkg.com/arr-map/-/arr-map-2.0.2.tgz" integrity sha1-Onc0X/wc814qkYJWAfnljy4kysQ= dependencies: make-iterator "^1.0.0" arr-union@^3.1.0: version "3.1.0" - resolved "https://registry.yarnpkg.com/arr-union/-/arr-union-3.1.0.tgz#e39b09aea9def866a8f206e288af63919bae39c4" + resolved "https://registry.yarnpkg.com/arr-union/-/arr-union-3.1.0.tgz" integrity sha1-45sJrqne+Gao8gbiiK9jkZuuOcQ= array-each@^1.0.0, array-each@^1.0.1: version "1.0.1" - resolved "https://registry.yarnpkg.com/array-each/-/array-each-1.0.1.tgz#a794af0c05ab1752846ee753a1f211a05ba0c44f" + resolved "https://registry.yarnpkg.com/array-each/-/array-each-1.0.1.tgz" integrity sha1-p5SvDAWrF1KEbudTofIRoFugxE8= array-initial@^1.0.0: version "1.1.0" - resolved "https://registry.yarnpkg.com/array-initial/-/array-initial-1.1.0.tgz#2fa74b26739371c3947bd7a7adc73be334b3d795" + resolved "https://registry.yarnpkg.com/array-initial/-/array-initial-1.1.0.tgz" integrity sha1-L6dLJnOTccOUe9enrcc74zSz15U= dependencies: array-slice "^1.0.0" @@ -104,19 +104,19 @@ array-initial@^1.0.0: array-last@^1.1.1: version "1.3.0" - resolved "https://registry.yarnpkg.com/array-last/-/array-last-1.3.0.tgz#7aa77073fec565ddab2493f5f88185f404a9d336" + resolved "https://registry.yarnpkg.com/array-last/-/array-last-1.3.0.tgz" integrity sha512-eOCut5rXlI6aCOS7Z7kCplKRKyiFQ6dHFBem4PwlwKeNFk2/XxTrhRh5T9PyaEWGy/NHTZWbY+nsZlNFJu9rYg== dependencies: is-number "^4.0.0" array-slice@^1.0.0: version "1.1.0" - resolved "https://registry.yarnpkg.com/array-slice/-/array-slice-1.1.0.tgz#e368ea15f89bc7069f7ffb89aec3a6c7d4ac22d4" + resolved "https://registry.yarnpkg.com/array-slice/-/array-slice-1.1.0.tgz" integrity sha512-B1qMD3RBP7O8o0H2KbrXDyB0IccejMF15+87Lvlor12ONPRHP6gTjXMNkt/d3ZuOGbAe66hFmaCfECI24Ufp6w== array-sort@^1.0.0: version "1.0.0" - resolved "https://registry.yarnpkg.com/array-sort/-/array-sort-1.0.0.tgz#e4c05356453f56f53512a7d1d6123f2c54c0a88a" + resolved "https://registry.yarnpkg.com/array-sort/-/array-sort-1.0.0.tgz" integrity sha512-ihLeJkonmdiAsD7vpgN3CRcx2J2S0TiYW+IS/5zHBI7mKUq3ySvBdzzBfD236ubDBQFiiyG3SWCPc+msQ9KoYg== dependencies: default-compare "^1.0.0" @@ -125,17 +125,17 @@ array-sort@^1.0.0: array-unique@^0.3.2: version "0.3.2" - resolved "https://registry.yarnpkg.com/array-unique/-/array-unique-0.3.2.tgz#a894b75d4bc4f6cd679ef3244a9fd8f46ae2d428" + resolved "https://registry.yarnpkg.com/array-unique/-/array-unique-0.3.2.tgz" integrity sha1-qJS3XUvE9s1nnvMkSp/Y9Gri1Cg= assign-symbols@^1.0.0: version "1.0.0" - resolved "https://registry.yarnpkg.com/assign-symbols/-/assign-symbols-1.0.0.tgz#59667f41fadd4f20ccbc2bb96b8d4f7f78ec0367" + resolved "https://registry.yarnpkg.com/assign-symbols/-/assign-symbols-1.0.0.tgz" integrity sha1-WWZ/QfrdTyDMvCu5a41Pf3jsA2c= async-done@^1.2.0, async-done@^1.2.2: version "1.3.2" - resolved "https://registry.yarnpkg.com/async-done/-/async-done-1.3.2.tgz#5e15aa729962a4b07414f528a88cdf18e0b290a2" + resolved "https://registry.yarnpkg.com/async-done/-/async-done-1.3.2.tgz" integrity sha512-uYkTP8dw2og1tu1nmza1n1CMW0qb8gWWlwqMmLb7MhBVs4BXrFziT6HXUd+/RlRA/i4H9AkofYloUbs1fwMqlw== dependencies: end-of-stream "^1.1.0" @@ -145,24 +145,24 @@ async-done@^1.2.0, async-done@^1.2.2: async-each@^1.0.1: version "1.0.3" - resolved "https://registry.yarnpkg.com/async-each/-/async-each-1.0.3.tgz#b727dbf87d7651602f06f4d4ac387f47d91b0cbf" + resolved "https://registry.yarnpkg.com/async-each/-/async-each-1.0.3.tgz" integrity sha512-z/WhQ5FPySLdvREByI2vZiTWwCnF0moMJ1hK9YQwDTHKh6I7/uSckMetoRGb5UBZPC1z0jlw+n/XCgjeH7y1AQ== async-settle@^1.0.0: version "1.0.0" - resolved "https://registry.yarnpkg.com/async-settle/-/async-settle-1.0.0.tgz#1d0a914bb02575bec8a8f3a74e5080f72b2c0c6b" + resolved "https://registry.yarnpkg.com/async-settle/-/async-settle-1.0.0.tgz" integrity sha1-HQqRS7Aldb7IqPOnTlCA9yssDGs= dependencies: async-done "^1.2.2" atob@^2.1.2: version "2.1.2" - resolved "https://registry.yarnpkg.com/atob/-/atob-2.1.2.tgz#6d9517eb9e030d2436666651e86bd9f6f13533c9" + resolved "https://registry.yarnpkg.com/atob/-/atob-2.1.2.tgz" integrity sha512-Wm6ukoaOGJi/73p/cl2GvLjTI5JM1k/O14isD73YML8StrH/7/lRFgmg8nICZgD3bZZvjwCGxtMOD3wWNAu8cg== bach@^1.0.0: version "1.2.0" - resolved "https://registry.yarnpkg.com/bach/-/bach-1.2.0.tgz#4b3ce96bf27134f79a1b414a51c14e34c3bd9880" + resolved "https://registry.yarnpkg.com/bach/-/bach-1.2.0.tgz" integrity sha1-Szzpa/JxNPeaG0FKUcFONMO9mIA= dependencies: arr-filter "^1.1.1" @@ -177,12 +177,12 @@ bach@^1.0.0: balanced-match@^1.0.0: version "1.0.0" - resolved "https://registry.yarnpkg.com/balanced-match/-/balanced-match-1.0.0.tgz#89b4d199ab2bee49de164ea02b89ce462d71b767" + resolved "https://registry.yarnpkg.com/balanced-match/-/balanced-match-1.0.0.tgz" integrity sha1-ibTRmasr7kneFk6gK4nORi1xt2c= base@^0.11.1: version "0.11.2" - resolved "https://registry.yarnpkg.com/base/-/base-0.11.2.tgz#7bde5ced145b6d551a90db87f83c558b4eb48a8f" + resolved "https://registry.yarnpkg.com/base/-/base-0.11.2.tgz" integrity sha512-5T6P4xPgpp0YDFvSWwEZ4NoE3aM4QBQXDzmVbraCkFj8zHM+mba8SyqB5DbZWyR7mYHo6Y7BdQo3MoA4m0TeQg== dependencies: cache-base "^1.0.1" @@ -195,19 +195,19 @@ base@^0.11.1: binary-extensions@^1.0.0: version "1.13.1" - resolved "https://registry.yarnpkg.com/binary-extensions/-/binary-extensions-1.13.1.tgz#598afe54755b2868a5330d2aff9d4ebb53209b65" + resolved "https://registry.yarnpkg.com/binary-extensions/-/binary-extensions-1.13.1.tgz" integrity sha512-Un7MIEDdUC5gNpcGDV97op1Ywk748MpHcFTHoYs6qnj1Z3j7I53VG3nwZhKzoBZmbdRNnb6WRdFlwl7tSDuZGw== bindings@^1.5.0: version "1.5.0" - resolved "https://registry.yarnpkg.com/bindings/-/bindings-1.5.0.tgz#10353c9e945334bc0511a6d90b38fbc7c9c504df" + resolved "https://registry.yarnpkg.com/bindings/-/bindings-1.5.0.tgz" integrity sha512-p2q/t/mhvuOj/UeLlV6566GD/guowlr0hHxClI0W9m7MWYkL1F0hLo+0Aexs9HSPCtR1SXQ0TD3MMKrXZajbiQ== dependencies: file-uri-to-path "1.0.0" brace-expansion@^1.1.7: version "1.1.11" - resolved "https://registry.yarnpkg.com/brace-expansion/-/brace-expansion-1.1.11.tgz#3c7fcbf529d87226f3d2f52b966ff5271eb441dd" + resolved "https://registry.yarnpkg.com/brace-expansion/-/brace-expansion-1.1.11.tgz" integrity sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA== dependencies: balanced-match "^1.0.0" @@ -215,7 +215,7 @@ brace-expansion@^1.1.7: braces@^2.3.1, braces@^2.3.2: version "2.3.2" - resolved "https://registry.yarnpkg.com/braces/-/braces-2.3.2.tgz#5979fd3f14cd531565e5fa2df1abfff1dfaee729" + resolved "https://registry.yarnpkg.com/braces/-/braces-2.3.2.tgz" integrity sha512-aNdbnj9P8PjdXU4ybaWLK2IF3jc/EoDYbC7AazW6to3TRsfXxscC9UXOB5iDiEQrkyIbWp2SLQda4+QAa7nc3w== dependencies: arr-flatten "^1.1.0" @@ -231,17 +231,17 @@ braces@^2.3.1, braces@^2.3.2: buffer-equal@^1.0.0: version "1.0.0" - resolved "https://registry.yarnpkg.com/buffer-equal/-/buffer-equal-1.0.0.tgz#59616b498304d556abd466966b22eeda3eca5fbe" + resolved "https://registry.yarnpkg.com/buffer-equal/-/buffer-equal-1.0.0.tgz" integrity sha1-WWFrSYME1Var1GaWayLu2j7KX74= buffer-from@^1.0.0: version "1.1.1" - resolved "https://registry.yarnpkg.com/buffer-from/-/buffer-from-1.1.1.tgz#32713bc028f75c02fdb710d7c7bcec1f2c6070ef" + resolved "https://registry.yarnpkg.com/buffer-from/-/buffer-from-1.1.1.tgz" integrity sha512-MQcXEUbCKtEo7bhqEs6560Hyd4XaovZlO/k9V3hjVUF/zwW7KBVdSK4gIt/bzwS9MbR5qob+F5jusZsb0YQK2A== cache-base@^1.0.1: version "1.0.1" - resolved "https://registry.yarnpkg.com/cache-base/-/cache-base-1.0.1.tgz#0a7f46416831c8b662ee36fe4e7c59d76f666ab2" + resolved "https://registry.yarnpkg.com/cache-base/-/cache-base-1.0.1.tgz" integrity sha512-AKcdTnFSWATd5/GCPRxr2ChwIJ85CeyrEyjRHlKxQ56d4XJMGym0uAiKn0xbLOGOl3+yRpOTi484dVCEc5AUzQ== dependencies: collection-visit "^1.0.0" @@ -254,9 +254,17 @@ cache-base@^1.0.1: union-value "^1.0.0" unset-value "^1.0.0" +call-bind@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/call-bind/-/call-bind-1.0.0.tgz" + integrity sha512-AEXsYIyyDY3MCzbwdhzG3Jx1R0J2wetQyUynn6dYHAO+bg8l1k7jwZtRv4ryryFs7EP+NDlikJlVe59jr0cM2w== + dependencies: + function-bind "^1.1.1" + get-intrinsic "^1.0.0" + camelcase@^3.0.0: version "3.0.0" - resolved "https://registry.yarnpkg.com/camelcase/-/camelcase-3.0.0.tgz#32fc4b9fcdaf845fcdf7e73bb97cac2261f0ab0a" + resolved "https://registry.yarnpkg.com/camelcase/-/camelcase-3.0.0.tgz" integrity sha1-MvxLn82vhF/N9+c7uXysImHwqwo= camelcase@^5.0.0: @@ -266,7 +274,7 @@ camelcase@^5.0.0: chalk@^2.3.0: version "2.4.2" - resolved "https://registry.yarnpkg.com/chalk/-/chalk-2.4.2.tgz#cd42541677a54333cf541a49108c1432b44c9424" + resolved "https://registry.yarnpkg.com/chalk/-/chalk-2.4.2.tgz" integrity sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ== dependencies: ansi-styles "^3.2.1" @@ -275,7 +283,7 @@ chalk@^2.3.0: chokidar@^2.0.0: version "2.1.8" - resolved "https://registry.yarnpkg.com/chokidar/-/chokidar-2.1.8.tgz#804b3a7b6a99358c3c5c61e71d8728f041cff917" + resolved "https://registry.yarnpkg.com/chokidar/-/chokidar-2.1.8.tgz" integrity sha512-ZmZUazfOzf0Nve7duiCKD23PFSCs4JPoYyccjUFF3aQkQadqBhfzhjkwBH2mNOG9cTBwhamM37EIsIkZw3nRgg== dependencies: anymatch "^2.0.0" @@ -294,7 +302,7 @@ chokidar@^2.0.0: class-utils@^0.3.5: version "0.3.6" - resolved "https://registry.yarnpkg.com/class-utils/-/class-utils-0.3.6.tgz#f93369ae8b9a7ce02fd41faad0ca83033190c463" + resolved "https://registry.yarnpkg.com/class-utils/-/class-utils-0.3.6.tgz" integrity sha512-qOhPa/Fj7s6TY8H8esGu5QNpMMQxz79h+urzrNYN6mn+9BnxlDGf5QZ+XeCDsxSjPqsSR56XOZOJmpeurnLMeg== dependencies: arr-union "^3.1.0" @@ -304,7 +312,7 @@ class-utils@^0.3.5: cliui@^3.2.0: version "3.2.0" - resolved "https://registry.yarnpkg.com/cliui/-/cliui-3.2.0.tgz#120601537a916d29940f934da3b48d585a39213d" + resolved "https://registry.yarnpkg.com/cliui/-/cliui-3.2.0.tgz" integrity sha1-EgYBU3qRbSmUD5NNo7SNWFo5IT0= dependencies: string-width "^1.0.1" @@ -313,22 +321,22 @@ cliui@^3.2.0: clone-buffer@^1.0.0: version "1.0.0" - resolved "https://registry.yarnpkg.com/clone-buffer/-/clone-buffer-1.0.0.tgz#e3e25b207ac4e701af721e2cb5a16792cac3dc58" + resolved "https://registry.yarnpkg.com/clone-buffer/-/clone-buffer-1.0.0.tgz" integrity sha1-4+JbIHrE5wGvch4staFnksrD3Fg= clone-stats@^1.0.0: version "1.0.0" - resolved "https://registry.yarnpkg.com/clone-stats/-/clone-stats-1.0.0.tgz#b3782dff8bb5474e18b9b6bf0fdfe782f8777680" + resolved "https://registry.yarnpkg.com/clone-stats/-/clone-stats-1.0.0.tgz" integrity sha1-s3gt/4u1R04Yuba/D9/ngvh3doA= clone@^2.1.1: version "2.1.2" - resolved "https://registry.yarnpkg.com/clone/-/clone-2.1.2.tgz#1b7f4b9f591f1e8f83670401600345a02887435f" + resolved "https://registry.yarnpkg.com/clone/-/clone-2.1.2.tgz" integrity sha1-G39Ln1kfHo+DZwQBYANFoCiHQ18= cloneable-readable@^1.0.0: version "1.1.3" - resolved "https://registry.yarnpkg.com/cloneable-readable/-/cloneable-readable-1.1.3.tgz#120a00cb053bfb63a222e709f9683ea2e11d8cec" + resolved "https://registry.yarnpkg.com/cloneable-readable/-/cloneable-readable-1.1.3.tgz" integrity sha512-2EF8zTQOxYq70Y4XKtorQupqF0m49MBz2/yf5Bj+MHjvpG3Hy7sImifnqD6UA+TKYxeSV+u6qqQPawN5UvnpKQ== dependencies: inherits "^2.0.1" @@ -337,12 +345,12 @@ cloneable-readable@^1.0.0: code-point-at@^1.0.0: version "1.1.0" - resolved "https://registry.yarnpkg.com/code-point-at/-/code-point-at-1.1.0.tgz#0d070b4d043a5bea33a2f1a40e2edb3d9a4ccf77" + resolved "https://registry.yarnpkg.com/code-point-at/-/code-point-at-1.1.0.tgz" integrity sha1-DQcLTQQ6W+ozovGkDi7bPZpMz3c= collection-map@^1.0.0: version "1.0.0" - resolved "https://registry.yarnpkg.com/collection-map/-/collection-map-1.0.0.tgz#aea0f06f8d26c780c2b75494385544b2255af18c" + resolved "https://registry.yarnpkg.com/collection-map/-/collection-map-1.0.0.tgz" integrity sha1-rqDwb40mx4DCt1SUOFVEsiVa8Yw= dependencies: arr-map "^2.0.2" @@ -351,7 +359,7 @@ collection-map@^1.0.0: collection-visit@^1.0.0: version "1.0.0" - resolved "https://registry.yarnpkg.com/collection-visit/-/collection-visit-1.0.0.tgz#4bc0373c164bc3291b4d368c829cf1a80a59dca0" + resolved "https://registry.yarnpkg.com/collection-visit/-/collection-visit-1.0.0.tgz" integrity sha1-S8A3PBZLwykbTTaMgpzxqApZ3KA= dependencies: map-visit "^1.0.0" @@ -359,34 +367,34 @@ collection-visit@^1.0.0: color-convert@^1.9.0: version "1.9.3" - resolved "https://registry.yarnpkg.com/color-convert/-/color-convert-1.9.3.tgz#bb71850690e1f136567de629d2d5471deda4c1e8" + resolved "https://registry.yarnpkg.com/color-convert/-/color-convert-1.9.3.tgz" integrity sha512-QfAUtd+vFdAtFQcC8CCyYt1fYWxSqAiK2cSD6zDB8N3cpsEBAvRxp9zOGg6G/SHHJYAT88/az/IuDGALsNVbGg== dependencies: color-name "1.1.3" color-name@1.1.3: version "1.1.3" - resolved "https://registry.yarnpkg.com/color-name/-/color-name-1.1.3.tgz#a7d0558bd89c42f795dd42328f740831ca53bc25" + resolved "https://registry.yarnpkg.com/color-name/-/color-name-1.1.3.tgz" integrity sha1-p9BVi9icQveV3UIyj3QIMcpTvCU= color-support@^1.1.3: version "1.1.3" - resolved "https://registry.yarnpkg.com/color-support/-/color-support-1.1.3.tgz#93834379a1cc9a0c61f82f52f0d04322251bd5a2" + resolved "https://registry.yarnpkg.com/color-support/-/color-support-1.1.3.tgz" integrity sha512-qiBjkpbMLO/HL68y+lh4q0/O1MZFj2RX6X/KmMa3+gJD3z+WwI1ZzDHysvqHGS3mP6mznPckpXmw1nI9cJjyRg== component-emitter@^1.2.1: version "1.3.0" - resolved "https://registry.yarnpkg.com/component-emitter/-/component-emitter-1.3.0.tgz#16e4070fba8ae29b679f2215853ee181ab2eabc0" + resolved "https://registry.yarnpkg.com/component-emitter/-/component-emitter-1.3.0.tgz" integrity sha512-Rd3se6QB+sO1TwqZjscQrurpEPIfO0/yYnSin6Q/rD3mOutHvUrCAhJub3r90uNb+SESBuE0QYoB90YdfatsRg== concat-map@0.0.1: version "0.0.1" - resolved "https://registry.yarnpkg.com/concat-map/-/concat-map-0.0.1.tgz#d8a96bd77fd68df7793a73036a3ba0d5405d477b" + resolved "https://registry.yarnpkg.com/concat-map/-/concat-map-0.0.1.tgz" integrity sha1-2Klr13/Wjfd5OnMDajug1UBdR3s= concat-stream@^1.6.0: version "1.6.2" - resolved "https://registry.yarnpkg.com/concat-stream/-/concat-stream-1.6.2.tgz#904bdf194cd3122fc675c77fc4ac3d4ff0fd1a34" + resolved "https://registry.yarnpkg.com/concat-stream/-/concat-stream-1.6.2.tgz" integrity sha512-27HBghJxjiZtIk3Ycvn/4kbJk/1uZuJFfuPEns6LaEvpvG1f0hTea8lilrouyo9mVc2GWdcEZ8OLoGmSADlrCw== dependencies: buffer-from "^1.0.0" @@ -396,26 +404,26 @@ concat-stream@^1.6.0: concat-with-sourcemaps@^1.0.0: version "1.1.0" - resolved "https://registry.yarnpkg.com/concat-with-sourcemaps/-/concat-with-sourcemaps-1.1.0.tgz#d4ea93f05ae25790951b99e7b3b09e3908a4082e" + resolved "https://registry.yarnpkg.com/concat-with-sourcemaps/-/concat-with-sourcemaps-1.1.0.tgz" integrity sha512-4gEjHJFT9e+2W/77h/DS5SGUgwDaOwprX8L/gl5+3ixnzkVJJsZWDSelmN3Oilw3LNDZjZV0yqH1hLG3k6nghg== dependencies: source-map "^0.6.1" convert-source-map@^1.5.0: version "1.7.0" - resolved "https://registry.yarnpkg.com/convert-source-map/-/convert-source-map-1.7.0.tgz#17a2cb882d7f77d3490585e2ce6c524424a3a442" + resolved "https://registry.yarnpkg.com/convert-source-map/-/convert-source-map-1.7.0.tgz" integrity sha512-4FJkXzKXEDB1snCFZlLP4gpC3JILicCpGbzG9f9G7tGqGCzETQ2hWPrcinA9oU4wtf2biUaEH5065UnMeR33oA== dependencies: safe-buffer "~5.1.1" copy-descriptor@^0.1.0: version "0.1.1" - resolved "https://registry.yarnpkg.com/copy-descriptor/-/copy-descriptor-0.1.1.tgz#676f6eb3c39997c2ee1ac3a924fd6124748f578d" + resolved "https://registry.yarnpkg.com/copy-descriptor/-/copy-descriptor-0.1.1.tgz" integrity sha1-Z29us8OZl8LuGsOpJP1hJHSPV40= copy-props@^2.0.1: version "2.0.4" - resolved "https://registry.yarnpkg.com/copy-props/-/copy-props-2.0.4.tgz#93bb1cadfafd31da5bb8a9d4b41f471ec3a72dfe" + resolved "https://registry.yarnpkg.com/copy-props/-/copy-props-2.0.4.tgz" integrity sha512-7cjuUME+p+S3HZlbllgsn2CDwS+5eCCX16qBgNC4jgSTf49qR1VKy/Zhl400m0IQXl/bPGEVqncgUUMjrr4s8A== dependencies: each-props "^1.3.0" @@ -423,12 +431,12 @@ copy-props@^2.0.1: core-util-is@~1.0.0: version "1.0.2" - resolved "https://registry.yarnpkg.com/core-util-is/-/core-util-is-1.0.2.tgz#b5fd54220aa2bc5ab57aab7140c940754503c1a7" + resolved "https://registry.yarnpkg.com/core-util-is/-/core-util-is-1.0.2.tgz" integrity sha1-tf1UIgqivFq1eqtxQMlAdUUDwac= d@1, d@^1.0.1: version "1.0.1" - resolved "https://registry.yarnpkg.com/d/-/d-1.0.1.tgz#8698095372d58dbee346ffd0c7093f99f8f9eb5a" + resolved "https://registry.yarnpkg.com/d/-/d-1.0.1.tgz" integrity sha512-m62ShEObQ39CfralilEQRjH6oAMtNCV1xJyEx5LpRYUVN+EviphDgUc/F3hnYbADmkiNs67Y+3ylmlG7Lnu+FA== dependencies: es5-ext "^0.10.50" @@ -436,7 +444,7 @@ d@1, d@^1.0.1: debug@^2.2.0, debug@^2.3.3: version "2.6.9" - resolved "https://registry.yarnpkg.com/debug/-/debug-2.6.9.tgz#5d128515df134ff327e90a4c93f4e077a536341f" + resolved "https://registry.yarnpkg.com/debug/-/debug-2.6.9.tgz" integrity sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA== dependencies: ms "2.0.0" @@ -448,45 +456,45 @@ decamelize@^1.1.1, decamelize@^1.2.0: decode-uri-component@^0.2.0: version "0.2.0" - resolved "https://registry.yarnpkg.com/decode-uri-component/-/decode-uri-component-0.2.0.tgz#eb3913333458775cb84cd1a1fae062106bb87545" + resolved "https://registry.yarnpkg.com/decode-uri-component/-/decode-uri-component-0.2.0.tgz" integrity sha1-6zkTMzRYd1y4TNGh+uBiEGu4dUU= default-compare@^1.0.0: version "1.0.0" - resolved "https://registry.yarnpkg.com/default-compare/-/default-compare-1.0.0.tgz#cb61131844ad84d84788fb68fd01681ca7781a2f" + resolved "https://registry.yarnpkg.com/default-compare/-/default-compare-1.0.0.tgz" integrity sha512-QWfXlM0EkAbqOCbD/6HjdwT19j7WCkMyiRhWilc4H9/5h/RzTF9gv5LYh1+CmDV5d1rki6KAWLtQale0xt20eQ== dependencies: kind-of "^5.0.2" default-resolution@^2.0.0: version "2.0.0" - resolved "https://registry.yarnpkg.com/default-resolution/-/default-resolution-2.0.0.tgz#bcb82baa72ad79b426a76732f1a81ad6df26d684" + resolved "https://registry.yarnpkg.com/default-resolution/-/default-resolution-2.0.0.tgz" integrity sha1-vLgrqnKtebQmp2cy8aga1t8m1oQ= -define-properties@^1.1.2: +define-properties@^1.1.3: version "1.1.3" - resolved "https://registry.yarnpkg.com/define-properties/-/define-properties-1.1.3.tgz#cf88da6cbee26fe6db7094f61d870cbd84cee9f1" + resolved "https://registry.yarnpkg.com/define-properties/-/define-properties-1.1.3.tgz" integrity sha512-3MqfYKj2lLzdMSf8ZIZE/V+Zuy+BgD6f164e8K2w7dgnpKArBDerGYpM46IYYcjnkdPNMjPk9A6VFB8+3SKlXQ== dependencies: object-keys "^1.0.12" define-property@^0.2.5: version "0.2.5" - resolved "https://registry.yarnpkg.com/define-property/-/define-property-0.2.5.tgz#c35b1ef918ec3c990f9a5bc57be04aacec5c8116" + resolved "https://registry.yarnpkg.com/define-property/-/define-property-0.2.5.tgz" integrity sha1-w1se+RjsPJkPmlvFe+BKrOxcgRY= dependencies: is-descriptor "^0.1.0" define-property@^1.0.0: version "1.0.0" - resolved "https://registry.yarnpkg.com/define-property/-/define-property-1.0.0.tgz#769ebaaf3f4a63aad3af9e8d304c9bbe79bfb0e6" + resolved "https://registry.yarnpkg.com/define-property/-/define-property-1.0.0.tgz" integrity sha1-dp66rz9KY6rTr56NMEybvnm/sOY= dependencies: is-descriptor "^1.0.0" define-property@^2.0.2: version "2.0.2" - resolved "https://registry.yarnpkg.com/define-property/-/define-property-2.0.2.tgz#d459689e8d654ba77e02a817f8710d702cb16e9d" + resolved "https://registry.yarnpkg.com/define-property/-/define-property-2.0.2.tgz" integrity sha512-jwK2UV4cnPpbcG7+VRARKTZPUWowwXA8bzH5NP6ud0oeAxyYPuGZUAC7hMugpCdz4BeSZl2Dl9k66CHJ/46ZYQ== dependencies: is-descriptor "^1.0.2" @@ -494,12 +502,12 @@ define-property@^2.0.2: detect-file@^1.0.0: version "1.0.0" - resolved "https://registry.yarnpkg.com/detect-file/-/detect-file-1.0.0.tgz#f0d66d03672a825cb1b73bdb3fe62310c8e552b7" + resolved "https://registry.yarnpkg.com/detect-file/-/detect-file-1.0.0.tgz" integrity sha1-8NZtA2cqglyxtzvbP+YjEMjlUrc= duplexify@^3.6.0: version "3.7.1" - resolved "https://registry.yarnpkg.com/duplexify/-/duplexify-3.7.1.tgz#2a4df5317f6ccfd91f86d6fd25d8d8a103b88309" + resolved "https://registry.yarnpkg.com/duplexify/-/duplexify-3.7.1.tgz" integrity sha512-07z8uv2wMyS51kKhD1KsdXJg5WQ6t93RneqRxUHnskXVtlYYkLqM0gqStQZ3pj073g687jPCHrqNfCzawLYh5g== dependencies: end-of-stream "^1.0.0" @@ -509,7 +517,7 @@ duplexify@^3.6.0: each-props@^1.3.0: version "1.3.2" - resolved "https://registry.yarnpkg.com/each-props/-/each-props-1.3.2.tgz#ea45a414d16dd5cfa419b1a81720d5ca06892333" + resolved "https://registry.yarnpkg.com/each-props/-/each-props-1.3.2.tgz" integrity sha512-vV0Hem3zAGkJAyU7JSjixeU66rwdynTAa1vofCrSA5fEln+m67Az9CcnkVD776/fsN/UjIWmBDoNRS6t6G9RfA== dependencies: is-plain-object "^2.0.1" @@ -517,26 +525,26 @@ each-props@^1.3.0: end-of-stream@^1.0.0, end-of-stream@^1.1.0: version "1.4.4" - resolved "https://registry.yarnpkg.com/end-of-stream/-/end-of-stream-1.4.4.tgz#5ae64a5f45057baf3626ec14da0ca5e4b2431eb0" + resolved "https://registry.yarnpkg.com/end-of-stream/-/end-of-stream-1.4.4.tgz" integrity sha512-+uw1inIHVPQoaVuHzRyXd21icM+cnt4CzD5rW+NC1wjOUSTOs+Te7FOv7AhN7vS9x/oIyhLP5PR1H+phQAHu5Q== dependencies: once "^1.4.0" entities@~2.0.0: version "2.0.3" - resolved "https://registry.yarnpkg.com/entities/-/entities-2.0.3.tgz#5c487e5742ab93c15abb5da22759b8590ec03b7f" + resolved "https://registry.yarnpkg.com/entities/-/entities-2.0.3.tgz" integrity sha512-MyoZ0jgnLvB2X3Lg5HqpFmn1kybDiIfEQmKzTb5apr51Rb+T3KdmMiqa70T+bhGnyv7bQ6WMj2QMHpGMmlrUYQ== error-ex@^1.2.0: version "1.3.2" - resolved "https://registry.yarnpkg.com/error-ex/-/error-ex-1.3.2.tgz#b4ac40648107fdcdcfae242f428bea8a14d4f1bf" + resolved "https://registry.yarnpkg.com/error-ex/-/error-ex-1.3.2.tgz" integrity sha512-7dFHNmqeFSEt2ZBsCriorKnn3Z2pj+fd9kmI6QoWw4//DL+icEBfc0U7qJCisqrTsKTjw4fNFy2pW9OqStD84g== dependencies: is-arrayish "^0.2.1" es5-ext@^0.10.35, es5-ext@^0.10.46, es5-ext@^0.10.50: version "0.10.53" - resolved "https://registry.yarnpkg.com/es5-ext/-/es5-ext-0.10.53.tgz#93c5a3acfdbef275220ad72644ad02ee18368de1" + resolved "https://registry.yarnpkg.com/es5-ext/-/es5-ext-0.10.53.tgz" integrity sha512-Xs2Stw6NiNHWypzRTY1MtaG/uJlwCk8kH81920ma8mvN8Xq1gsfhZvpkImLQArw8AHnv8MT2I45J3c0R8slE+Q== dependencies: es6-iterator "~2.0.3" @@ -545,7 +553,7 @@ es5-ext@^0.10.35, es5-ext@^0.10.46, es5-ext@^0.10.50: es6-iterator@^2.0.1, es6-iterator@^2.0.3, es6-iterator@~2.0.3: version "2.0.3" - resolved "https://registry.yarnpkg.com/es6-iterator/-/es6-iterator-2.0.3.tgz#a7de889141a05a94b0854403b2d0a0fbfa98f3b7" + resolved "https://registry.yarnpkg.com/es6-iterator/-/es6-iterator-2.0.3.tgz" integrity sha1-p96IkUGgWpSwhUQDstCg+/qY87c= dependencies: d "1" @@ -554,7 +562,7 @@ es6-iterator@^2.0.1, es6-iterator@^2.0.3, es6-iterator@~2.0.3: es6-symbol@^3.1.1, es6-symbol@~3.1.3: version "3.1.3" - resolved "https://registry.yarnpkg.com/es6-symbol/-/es6-symbol-3.1.3.tgz#bad5d3c1bcdac28269f4cb331e431c78ac705d18" + resolved "https://registry.yarnpkg.com/es6-symbol/-/es6-symbol-3.1.3.tgz" integrity sha512-NJ6Yn3FuDinBaBRWl/q5X/s4koRHBrgKAu+yGI6JCBeiu3qrcbJhwT2GeR/EXVfylRk8dpQVJoLEFhK+Mu31NA== dependencies: d "^1.0.1" @@ -562,7 +570,7 @@ es6-symbol@^3.1.1, es6-symbol@~3.1.3: es6-weak-map@^2.0.1: version "2.0.3" - resolved "https://registry.yarnpkg.com/es6-weak-map/-/es6-weak-map-2.0.3.tgz#b6da1f16cc2cc0d9be43e6bdbfc5e7dfcdf31d53" + resolved "https://registry.yarnpkg.com/es6-weak-map/-/es6-weak-map-2.0.3.tgz" integrity sha512-p5um32HOTO1kP+w7PRnB+5lQ43Z6muuMuIMffvDN8ZB4GcnjLBV6zGStpbASIMk4DCAvEaamhe2zhyCb/QXXsA== dependencies: d "1" @@ -572,12 +580,12 @@ es6-weak-map@^2.0.1: escape-string-regexp@^1.0.5: version "1.0.5" - resolved "https://registry.yarnpkg.com/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz#1b61c0562190a8dff6ae3bb2cf0200ca130b86d4" + resolved "https://registry.yarnpkg.com/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz" integrity sha1-G2HAViGQqN/2rjuyzwIAyhMLhtQ= expand-brackets@^2.1.4: version "2.1.4" - resolved "https://registry.yarnpkg.com/expand-brackets/-/expand-brackets-2.1.4.tgz#b77735e315ce30f6b6eff0f83b04151a22449622" + resolved "https://registry.yarnpkg.com/expand-brackets/-/expand-brackets-2.1.4.tgz" integrity sha1-t3c14xXOMPa27/D4OwQVGiJEliI= dependencies: debug "^2.3.3" @@ -590,28 +598,28 @@ expand-brackets@^2.1.4: expand-tilde@^2.0.0, expand-tilde@^2.0.2: version "2.0.2" - resolved "https://registry.yarnpkg.com/expand-tilde/-/expand-tilde-2.0.2.tgz#97e801aa052df02454de46b02bf621642cdc8502" + resolved "https://registry.yarnpkg.com/expand-tilde/-/expand-tilde-2.0.2.tgz" integrity sha1-l+gBqgUt8CRU3kawK/YhZCzchQI= dependencies: homedir-polyfill "^1.0.1" ext@^1.1.2: version "1.4.0" - resolved "https://registry.yarnpkg.com/ext/-/ext-1.4.0.tgz#89ae7a07158f79d35517882904324077e4379244" + resolved "https://registry.yarnpkg.com/ext/-/ext-1.4.0.tgz" integrity sha512-Key5NIsUxdqKg3vIsdw9dSuXpPCQ297y6wBjL30edxwPgt2E44WcWBZey/ZvUc6sERLTxKdyCu4gZFmUbk1Q7A== dependencies: type "^2.0.0" extend-shallow@^2.0.1: version "2.0.1" - resolved "https://registry.yarnpkg.com/extend-shallow/-/extend-shallow-2.0.1.tgz#51af7d614ad9a9f610ea1bafbb989d6b1c56890f" + resolved "https://registry.yarnpkg.com/extend-shallow/-/extend-shallow-2.0.1.tgz" integrity sha1-Ua99YUrZqfYQ6huvu5idaxxWiQ8= dependencies: is-extendable "^0.1.0" extend-shallow@^3.0.0, extend-shallow@^3.0.2: version "3.0.2" - resolved "https://registry.yarnpkg.com/extend-shallow/-/extend-shallow-3.0.2.tgz#26a71aaf073b39fb2127172746131c2704028db8" + resolved "https://registry.yarnpkg.com/extend-shallow/-/extend-shallow-3.0.2.tgz" integrity sha1-Jqcarwc7OfshJxcnRhMcJwQCjbg= dependencies: assign-symbols "^1.0.0" @@ -619,12 +627,12 @@ extend-shallow@^3.0.0, extend-shallow@^3.0.2: extend@^3.0.0: version "3.0.2" - resolved "https://registry.yarnpkg.com/extend/-/extend-3.0.2.tgz#f8b1136b4071fbd8eb140aff858b1019ec2915fa" + resolved "https://registry.yarnpkg.com/extend/-/extend-3.0.2.tgz" integrity sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g== extglob@^2.0.4: version "2.0.4" - resolved "https://registry.yarnpkg.com/extglob/-/extglob-2.0.4.tgz#ad00fe4dc612a9232e8718711dc5cb5ab0285543" + resolved "https://registry.yarnpkg.com/extglob/-/extglob-2.0.4.tgz" integrity sha512-Nmb6QXkELsuBr24CJSkilo6UHHgbekK5UiZgfE6UHD3Eb27YC6oD+bhcT+tJ6cl8dmsgdQxnWlcry8ksBIBLpw== dependencies: array-unique "^0.3.2" @@ -638,7 +646,7 @@ extglob@^2.0.4: fancy-log@^1.3.2: version "1.3.3" - resolved "https://registry.yarnpkg.com/fancy-log/-/fancy-log-1.3.3.tgz#dbc19154f558690150a23953a0adbd035be45fc7" + resolved "https://registry.yarnpkg.com/fancy-log/-/fancy-log-1.3.3.tgz" integrity sha512-k9oEhlyc0FrVh25qYuSELjr8oxsCoc4/LEZfg2iJJrfEk/tZL9bCoJE47gqAvI2m/AUjluCS4+3I0eTx8n3AEw== dependencies: ansi-gray "^0.1.1" @@ -646,14 +654,19 @@ fancy-log@^1.3.2: parse-node-version "^1.0.0" time-stamp "^1.0.0" +fast-levenshtein@^1.0.0: + version "1.1.4" + resolved "https://registry.yarnpkg.com/fast-levenshtein/-/fast-levenshtein-1.1.4.tgz" + integrity sha1-5qdUzI8V5YmHqpy9J69m/W9OWvk= + file-uri-to-path@1.0.0: version "1.0.0" - resolved "https://registry.yarnpkg.com/file-uri-to-path/-/file-uri-to-path-1.0.0.tgz#553a7b8446ff6f684359c445f1e37a05dacc33dd" + resolved "https://registry.yarnpkg.com/file-uri-to-path/-/file-uri-to-path-1.0.0.tgz" integrity sha512-0Zt+s3L7Vf1biwWZ29aARiVYLx7iMGnEUl9x33fbB/j3jR81u/O2LbqK+Bm1CDSNDKVtJ/YjwY7TUd5SkeLQLw== fill-range@^4.0.0: version "4.0.0" - resolved "https://registry.yarnpkg.com/fill-range/-/fill-range-4.0.0.tgz#d544811d428f98eb06a63dc402d2403c328c38f7" + resolved "https://registry.yarnpkg.com/fill-range/-/fill-range-4.0.0.tgz" integrity sha1-1USBHUKPmOsGpj3EAtJAPDKMOPc= dependencies: extend-shallow "^2.0.1" @@ -663,7 +676,7 @@ fill-range@^4.0.0: find-up@^1.0.0: version "1.1.2" - resolved "https://registry.yarnpkg.com/find-up/-/find-up-1.1.2.tgz#6b2e9822b1a2ce0a60ab64d610eccad53cb24d0f" + resolved "https://registry.yarnpkg.com/find-up/-/find-up-1.1.2.tgz" integrity sha1-ay6YIrGizgpgq2TWEOzK1TyyTQ8= dependencies: path-exists "^2.0.0" @@ -671,7 +684,7 @@ find-up@^1.0.0: findup-sync@^2.0.0: version "2.0.0" - resolved "https://registry.yarnpkg.com/findup-sync/-/findup-sync-2.0.0.tgz#9326b1488c22d1a6088650a86901b2d9a90a2cbc" + resolved "https://registry.yarnpkg.com/findup-sync/-/findup-sync-2.0.0.tgz" integrity sha1-kyaxSIwi0aYIhlCoaQGy2akKLLw= dependencies: detect-file "^1.0.0" @@ -681,7 +694,7 @@ findup-sync@^2.0.0: findup-sync@^3.0.0: version "3.0.0" - resolved "https://registry.yarnpkg.com/findup-sync/-/findup-sync-3.0.0.tgz#17b108f9ee512dfb7a5c7f3c8b27ea9e1a9c08d1" + resolved "https://registry.yarnpkg.com/findup-sync/-/findup-sync-3.0.0.tgz" integrity sha512-YbffarhcicEhOrm4CtrwdKBdCuz576RLdhJDsIfvNtxUuhdRet1qZcsMjqbePtAseKdAnDyM/IyXbu7PRPRLYg== dependencies: detect-file "^1.0.0" @@ -691,7 +704,7 @@ findup-sync@^3.0.0: fined@^1.0.1: version "1.2.0" - resolved "https://registry.yarnpkg.com/fined/-/fined-1.2.0.tgz#d00beccf1aa2b475d16d423b0238b713a2c4a37b" + resolved "https://registry.yarnpkg.com/fined/-/fined-1.2.0.tgz" integrity sha512-ZYDqPLGxDkDhDZBjZBb+oD1+j0rA4E0pXY50eplAAOPg2N/gUBSSk5IM1/QhPfyVo19lJ+CvXpqfvk+b2p/8Ng== dependencies: expand-tilde "^2.0.2" @@ -702,12 +715,12 @@ fined@^1.0.1: flagged-respawn@^1.0.0: version "1.0.1" - resolved "https://registry.yarnpkg.com/flagged-respawn/-/flagged-respawn-1.0.1.tgz#e7de6f1279ddd9ca9aac8a5971d618606b3aab41" + resolved "https://registry.yarnpkg.com/flagged-respawn/-/flagged-respawn-1.0.1.tgz" integrity sha512-lNaHNVymajmk0OJMBn8fVUAU1BtDeKIqKoVhk4xAALB57aALg6b4W0MfJ/cUE0g9YBXy5XhSlPIpYIJ7HaY/3Q== flush-write-stream@^1.0.2: version "1.1.1" - resolved "https://registry.yarnpkg.com/flush-write-stream/-/flush-write-stream-1.1.1.tgz#8dd7d873a1babc207d94ead0c2e0e44276ebf2e8" + resolved "https://registry.yarnpkg.com/flush-write-stream/-/flush-write-stream-1.1.1.tgz" integrity sha512-3Z4XhFZ3992uIq0XOqb9AreonueSYphE6oYbpt5+3u06JWklbsPkNv3ZKkP9Bz/r+1MWCaMoSQ28P85+1Yc77w== dependencies: inherits "^2.0.3" @@ -715,26 +728,26 @@ flush-write-stream@^1.0.2: for-in@^1.0.1, for-in@^1.0.2: version "1.0.2" - resolved "https://registry.yarnpkg.com/for-in/-/for-in-1.0.2.tgz#81068d295a8142ec0ac726c6e2200c30fb6d5e80" + resolved "https://registry.yarnpkg.com/for-in/-/for-in-1.0.2.tgz" integrity sha1-gQaNKVqBQuwKxybG4iAMMPttXoA= for-own@^1.0.0: version "1.0.0" - resolved "https://registry.yarnpkg.com/for-own/-/for-own-1.0.0.tgz#c63332f415cedc4b04dbfe70cf836494c53cb44b" + resolved "https://registry.yarnpkg.com/for-own/-/for-own-1.0.0.tgz" integrity sha1-xjMy9BXO3EsE2/5wz4NklMU8tEs= dependencies: for-in "^1.0.1" fragment-cache@^0.2.1: version "0.2.1" - resolved "https://registry.yarnpkg.com/fragment-cache/-/fragment-cache-0.2.1.tgz#4290fad27f13e89be7f33799c6bc5a0abfff0d19" + resolved "https://registry.yarnpkg.com/fragment-cache/-/fragment-cache-0.2.1.tgz" integrity sha1-QpD60n8T6Jvn8zeZxrxaCr//DRk= dependencies: map-cache "^0.2.2" fs-mkdirp-stream@^1.0.0: version "1.0.0" - resolved "https://registry.yarnpkg.com/fs-mkdirp-stream/-/fs-mkdirp-stream-1.0.0.tgz#0b7815fc3201c6a69e14db98ce098c16935259eb" + resolved "https://registry.yarnpkg.com/fs-mkdirp-stream/-/fs-mkdirp-stream-1.0.0.tgz" integrity sha1-C3gV/DIBxqaeFNuYzgmMFpNSWes= dependencies: graceful-fs "^4.1.11" @@ -742,12 +755,12 @@ fs-mkdirp-stream@^1.0.0: fs.realpath@^1.0.0: version "1.0.0" - resolved "https://registry.yarnpkg.com/fs.realpath/-/fs.realpath-1.0.0.tgz#1504ad2523158caa40db4a2787cb01411994ea4f" + resolved "https://registry.yarnpkg.com/fs.realpath/-/fs.realpath-1.0.0.tgz" integrity sha1-FQStJSMVjKpA20onh8sBQRmU6k8= fsevents@^1.2.7: version "1.2.13" - resolved "https://registry.yarnpkg.com/fsevents/-/fsevents-1.2.13.tgz#f325cb0455592428bcf11b383370ef70e3bfcc38" + resolved "https://registry.yarnpkg.com/fsevents/-/fsevents-1.2.13.tgz" integrity sha512-oWb1Z6mkHIskLzEJ/XWX0srkpkTQ7vaopMQkyaEIoq0fmtFVxOthb8cCxeT+p3ynTdkk/RZwbgG4brR5BeWECw== dependencies: bindings "^1.5.0" @@ -755,27 +768,36 @@ fsevents@^1.2.7: function-bind@^1.1.1: version "1.1.1" - resolved "https://registry.yarnpkg.com/function-bind/-/function-bind-1.1.1.tgz#a56899d3ea3c9bab874bb9773b7c5ede92f4895d" + resolved "https://registry.yarnpkg.com/function-bind/-/function-bind-1.1.1.tgz" integrity sha512-yIovAzMX49sF8Yl58fSCWJ5svSLuaibPxXQJFLmBObTuCr0Mf1KiPopGM9NiFjiYBCbfaa2Fh6breQ6ANVTI0A== get-caller-file@^1.0.1: version "1.0.3" - resolved "https://registry.yarnpkg.com/get-caller-file/-/get-caller-file-1.0.3.tgz#f978fa4c90d1dfe7ff2d6beda2a515e713bdcf4a" + resolved "https://registry.yarnpkg.com/get-caller-file/-/get-caller-file-1.0.3.tgz" integrity sha512-3t6rVToeoZfYSGd8YoLFR2DJkiQrIiUrGcjvFX2mDw3bn6k2OtwHN0TNCLbBO+w8qTvimhDkv+LSscbJY1vE6w== +get-intrinsic@^1.0.0: + version "1.0.1" + resolved "https://registry.yarnpkg.com/get-intrinsic/-/get-intrinsic-1.0.1.tgz" + integrity sha512-ZnWP+AmS1VUaLgTRy47+zKtjTxz+0xMpx3I52i+aalBK1QP19ggLF3Db89KJX7kjfOfP2eoa01qc++GwPgufPg== + dependencies: + function-bind "^1.1.1" + has "^1.0.3" + has-symbols "^1.0.1" + get-own-enumerable-property-symbols@^3.0.0: version "3.0.2" - resolved "https://registry.yarnpkg.com/get-own-enumerable-property-symbols/-/get-own-enumerable-property-symbols-3.0.2.tgz#b5fde77f22cbe35f390b4e089922c50bce6ef664" + resolved "https://registry.yarnpkg.com/get-own-enumerable-property-symbols/-/get-own-enumerable-property-symbols-3.0.2.tgz" integrity sha512-I0UBV/XOz1XkIJHEUDMZAbzCThU/H8DxmSfmdGcKPnVhu2VfFqr34jr9777IyaTYvxjedWhqVIilEDsCdP5G6g== get-value@^2.0.3, get-value@^2.0.6: version "2.0.6" - resolved "https://registry.yarnpkg.com/get-value/-/get-value-2.0.6.tgz#dc15ca1c672387ca76bd37ac0a395ba2042a2c28" + resolved "https://registry.yarnpkg.com/get-value/-/get-value-2.0.6.tgz" integrity sha1-3BXKHGcjh8p2vTesCjlbogQqLCg= glob-parent@^3.1.0: version "3.1.0" - resolved "https://registry.yarnpkg.com/glob-parent/-/glob-parent-3.1.0.tgz#9e6af6299d8d3bd2bd40430832bd113df906c5ae" + resolved "https://registry.yarnpkg.com/glob-parent/-/glob-parent-3.1.0.tgz" integrity sha1-nmr2KZ2NO9K9QEMIMr0RPfkGxa4= dependencies: is-glob "^3.1.0" @@ -783,7 +805,7 @@ glob-parent@^3.1.0: glob-stream@^6.1.0: version "6.1.0" - resolved "https://registry.yarnpkg.com/glob-stream/-/glob-stream-6.1.0.tgz#7045c99413b3eb94888d83ab46d0b404cc7bdde4" + resolved "https://registry.yarnpkg.com/glob-stream/-/glob-stream-6.1.0.tgz" integrity sha1-cEXJlBOz65SIjYOrRtC0BMx73eQ= dependencies: extend "^3.0.0" @@ -798,20 +820,21 @@ glob-stream@^6.1.0: unique-stream "^2.0.2" glob-watcher@^5.0.3: - version "5.0.3" - resolved "https://registry.yarnpkg.com/glob-watcher/-/glob-watcher-5.0.3.tgz#88a8abf1c4d131eb93928994bc4a593c2e5dd626" - integrity sha512-8tWsULNEPHKQ2MR4zXuzSmqbdyV5PtwwCaWSGQ1WwHsJ07ilNeN1JB8ntxhckbnpSHaf9dXFUHzIWvm1I13dsg== + version "5.0.5" + resolved "https://registry.yarnpkg.com/glob-watcher/-/glob-watcher-5.0.5.tgz" + integrity sha512-zOZgGGEHPklZNjZQaZ9f41i7F2YwE+tS5ZHrDhbBCk3stwahn5vQxnFmBJZHoYdusR6R1bLSXeGUy/BhctwKzw== dependencies: anymatch "^2.0.0" async-done "^1.2.0" chokidar "^2.0.0" is-negated-glob "^1.0.0" just-debounce "^1.0.0" + normalize-path "^3.0.0" object.defaults "^1.1.0" glob@^7.1.1: version "7.1.6" - resolved "https://registry.yarnpkg.com/glob/-/glob-7.1.6.tgz#141f33b81a7c2492e125594307480c46679278a6" + resolved "https://registry.yarnpkg.com/glob/-/glob-7.1.6.tgz" integrity sha512-LwaxwyZ72Lk7vZINtNNrywX0ZuLyStrdDtabefZKAY5ZGJhVtgdznluResxNmPitE0SAO+O26sWTHeKSI2wMBA== dependencies: fs.realpath "^1.0.0" @@ -823,7 +846,7 @@ glob@^7.1.1: global-modules@^1.0.0: version "1.0.0" - resolved "https://registry.yarnpkg.com/global-modules/-/global-modules-1.0.0.tgz#6d770f0eb523ac78164d72b5e71a8877265cc3ea" + resolved "https://registry.yarnpkg.com/global-modules/-/global-modules-1.0.0.tgz" integrity sha512-sKzpEkf11GpOFuw0Zzjzmt4B4UZwjOcG757PPvrfhxcLFbq0wpsgpOqxpxtxFiCG4DtG93M6XRVbF2oGdev7bg== dependencies: global-prefix "^1.0.1" @@ -832,7 +855,7 @@ global-modules@^1.0.0: global-prefix@^1.0.1: version "1.0.2" - resolved "https://registry.yarnpkg.com/global-prefix/-/global-prefix-1.0.2.tgz#dbf743c6c14992593c655568cb66ed32c0122ebe" + resolved "https://registry.yarnpkg.com/global-prefix/-/global-prefix-1.0.2.tgz" integrity sha1-2/dDxsFJklk8ZVVoy2btMsASLr4= dependencies: expand-tilde "^2.0.2" @@ -843,20 +866,20 @@ global-prefix@^1.0.1: glogg@^1.0.0: version "1.0.2" - resolved "https://registry.yarnpkg.com/glogg/-/glogg-1.0.2.tgz#2d7dd702beda22eb3bffadf880696da6d846313f" + resolved "https://registry.yarnpkg.com/glogg/-/glogg-1.0.2.tgz" integrity sha512-5mwUoSuBk44Y4EshyiqcH95ZntbDdTQqA3QYSrxmzj28Ai0vXBGMH1ApSANH14j2sIRtqCEyg6PfsuP7ElOEDA== dependencies: sparkles "^1.0.0" graceful-fs@^4.0.0, graceful-fs@^4.1.11, graceful-fs@^4.1.2, graceful-fs@^4.1.6: version "4.2.4" - resolved "https://registry.yarnpkg.com/graceful-fs/-/graceful-fs-4.2.4.tgz#2256bde14d3632958c465ebc96dc467ca07a29fb" + resolved "https://registry.yarnpkg.com/graceful-fs/-/graceful-fs-4.2.4.tgz" integrity sha512-WjKPNJF79dtJAVniUlGGWHYGz2jWxT6VhN/4m1NdkbZ2nOsEF+cI1Edgql5zCRhs/VsQYRvrXctxktVXZUkixw== gulp-cli@^2.2.0: - version "2.2.1" - resolved "https://registry.yarnpkg.com/gulp-cli/-/gulp-cli-2.2.1.tgz#376e427661b7996430a89d71c15df75defa3360a" - integrity sha512-yEMxrXqY8mJFlaauFQxNrCpzWJThu0sH1sqlToaTOT063Hub9s/Nt2C+GSLe6feQ/IMWrHvGOOsyES7CQc9O+A== + version "2.3.0" + resolved "https://registry.yarnpkg.com/gulp-cli/-/gulp-cli-2.3.0.tgz" + integrity sha512-zzGBl5fHo0EKSXsHzjspp3y5CONegCm8ErO5Qh0UzFzk2y4tMvzLWhoDokADbarfZRL2pGpRp7yt6gfJX4ph7A== dependencies: ansi-colors "^1.0.1" archy "^1.0.0" @@ -866,7 +889,7 @@ gulp-cli@^2.2.0: copy-props "^2.0.1" fancy-log "^1.3.2" gulplog "^1.0.0" - interpret "^1.1.0" + interpret "^1.4.0" isobject "^3.0.1" liftoff "^3.1.0" matchdep "^2.0.0" @@ -874,12 +897,12 @@ gulp-cli@^2.2.0: pretty-hrtime "^1.0.0" replace-homedir "^1.0.0" semver-greatest-satisfied-range "^1.1.0" - v8flags "^3.0.1" + v8flags "^3.2.0" yargs "^7.1.0" gulp-concat@^2.6.1: version "2.6.1" - resolved "https://registry.yarnpkg.com/gulp-concat/-/gulp-concat-2.6.1.tgz#633d16c95d88504628ad02665663cee5a4793353" + resolved "https://registry.yarnpkg.com/gulp-concat/-/gulp-concat-2.6.1.tgz" integrity sha1-Yz0WyV2IUEYorQJmVmPO5aR5M1M= dependencies: concat-with-sourcemaps "^1.0.0" @@ -888,7 +911,7 @@ gulp-concat@^2.6.1: gulp-debug@^4.0.0: version "4.0.0" - resolved "https://registry.yarnpkg.com/gulp-debug/-/gulp-debug-4.0.0.tgz#036f9539c3fb6af720e01a9ea5c195fc73f29d5b" + resolved "https://registry.yarnpkg.com/gulp-debug/-/gulp-debug-4.0.0.tgz" integrity sha512-cn/GhMD2nVZCVxAl5vWao4/dcoZ8wUJ8w3oqTvQaGDmC1vT7swNOEbhQTWJp+/otKePT64aENcqAQXDcdj5H1g== dependencies: chalk "^2.3.0" @@ -900,7 +923,7 @@ gulp-debug@^4.0.0: gulp@^4.0.2: version "4.0.2" - resolved "https://registry.yarnpkg.com/gulp/-/gulp-4.0.2.tgz#543651070fd0f6ab0a0650c6a3e6ff5a7cb09caa" + resolved "https://registry.yarnpkg.com/gulp/-/gulp-4.0.2.tgz" integrity sha512-dvEs27SCZt2ibF29xYgmnwwCYZxdxhQ/+LFWlbAW8y7jt68L/65402Lz3+CKy0Ov4rOs+NERmDq7YlZaDqUIfA== dependencies: glob-watcher "^5.0.3" @@ -910,24 +933,24 @@ gulp@^4.0.2: gulplog@^1.0.0: version "1.0.0" - resolved "https://registry.yarnpkg.com/gulplog/-/gulplog-1.0.0.tgz#e28c4d45d05ecbbed818363ce8f9c5926229ffe5" + resolved "https://registry.yarnpkg.com/gulplog/-/gulplog-1.0.0.tgz" integrity sha1-4oxNRdBey77YGDY86PnFkmIp/+U= dependencies: glogg "^1.0.0" has-flag@^3.0.0: version "3.0.0" - resolved "https://registry.yarnpkg.com/has-flag/-/has-flag-3.0.0.tgz#b5d454dc2199ae225699f3467e5a07f3b955bafd" + resolved "https://registry.yarnpkg.com/has-flag/-/has-flag-3.0.0.tgz" integrity sha1-tdRU3CGZriJWmfNGfloH87lVuv0= -has-symbols@^1.0.0: +has-symbols@^1.0.1: version "1.0.1" - resolved "https://registry.yarnpkg.com/has-symbols/-/has-symbols-1.0.1.tgz#9f5214758a44196c406d9bd76cebf81ec2dd31e8" + resolved "https://registry.yarnpkg.com/has-symbols/-/has-symbols-1.0.1.tgz" integrity sha512-PLcsoqu++dmEIZB+6totNFKq/7Do+Z0u4oT0zKOJNl3lYK6vGwwu2hjHs+68OEZbTjiUE9bgOABXbP/GvrS0Kg== has-value@^0.3.1: version "0.3.1" - resolved "https://registry.yarnpkg.com/has-value/-/has-value-0.3.1.tgz#7b1f58bada62ca827ec0a2078025654845995e1f" + resolved "https://registry.yarnpkg.com/has-value/-/has-value-0.3.1.tgz" integrity sha1-ex9YutpiyoJ+wKIHgCVlSEWZXh8= dependencies: get-value "^2.0.3" @@ -936,7 +959,7 @@ has-value@^0.3.1: has-value@^1.0.0: version "1.0.0" - resolved "https://registry.yarnpkg.com/has-value/-/has-value-1.0.0.tgz#18b281da585b1c5c51def24c930ed29a0be6b177" + resolved "https://registry.yarnpkg.com/has-value/-/has-value-1.0.0.tgz" integrity sha1-GLKB2lhbHFxR3vJMkw7SmgvmsXc= dependencies: get-value "^2.0.6" @@ -945,32 +968,39 @@ has-value@^1.0.0: has-values@^0.1.4: version "0.1.4" - resolved "https://registry.yarnpkg.com/has-values/-/has-values-0.1.4.tgz#6d61de95d91dfca9b9a02089ad384bff8f62b771" + resolved "https://registry.yarnpkg.com/has-values/-/has-values-0.1.4.tgz" integrity sha1-bWHeldkd/Km5oCCJrThL/49it3E= has-values@^1.0.0: version "1.0.0" - resolved "https://registry.yarnpkg.com/has-values/-/has-values-1.0.0.tgz#95b0b63fec2146619a6fe57fe75628d5a39efe4f" + resolved "https://registry.yarnpkg.com/has-values/-/has-values-1.0.0.tgz" integrity sha1-lbC2P+whRmGab+V/51Yo1aOe/k8= dependencies: is-number "^3.0.0" kind-of "^4.0.0" +has@^1.0.3: + version "1.0.3" + resolved "https://registry.yarnpkg.com/has/-/has-1.0.3.tgz" + integrity sha512-f2dvO0VU6Oej7RkWJGrehjbzMAjFp5/VKPp5tTpWIV4JHHZK1/BxbFRtf/siA2SWTe09caDmVtYYzWEIbBS4zw== + dependencies: + function-bind "^1.1.1" + homedir-polyfill@^1.0.1: version "1.0.3" - resolved "https://registry.yarnpkg.com/homedir-polyfill/-/homedir-polyfill-1.0.3.tgz#743298cef4e5af3e194161fbadcc2151d3a058e8" + resolved "https://registry.yarnpkg.com/homedir-polyfill/-/homedir-polyfill-1.0.3.tgz" integrity sha512-eSmmWE5bZTK2Nou4g0AI3zZ9rswp7GRKoKXS1BLUkvPviOqs4YTN1djQIqrXy9k5gEtdLPy86JjRwsNM9tnDcA== dependencies: parse-passwd "^1.0.0" hosted-git-info@^2.1.4: version "2.8.8" - resolved "https://registry.yarnpkg.com/hosted-git-info/-/hosted-git-info-2.8.8.tgz#7539bd4bc1e0e0a895815a2e0262420b12858488" + resolved "https://registry.yarnpkg.com/hosted-git-info/-/hosted-git-info-2.8.8.tgz" integrity sha512-f/wzC2QaWBs7t9IYqB4T3sR1xviIViXJRJTWBlx2Gf3g0Xi5vI7Yy4koXQ1c9OYDGHN9sBy1DQ2AB8fqZBWhUg== inflight@^1.0.4: version "1.0.6" - resolved "https://registry.yarnpkg.com/inflight/-/inflight-1.0.6.tgz#49bd6331d7d02d0c09bc910a1075ba8165b56df9" + resolved "https://registry.yarnpkg.com/inflight/-/inflight-1.0.6.tgz" integrity sha1-Sb1jMdfQLQwJvJEKEHW6gWW1bfk= dependencies: once "^1.3.0" @@ -978,32 +1008,32 @@ inflight@^1.0.4: inherits@2, inherits@^2.0.1, inherits@^2.0.3, inherits@~2.0.3: version "2.0.4" - resolved "https://registry.yarnpkg.com/inherits/-/inherits-2.0.4.tgz#0fa2c64f932917c3433a0ded55363aae37416b7c" + resolved "https://registry.yarnpkg.com/inherits/-/inherits-2.0.4.tgz" integrity sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ== ini@^1.3.4: version "1.3.5" - resolved "https://registry.yarnpkg.com/ini/-/ini-1.3.5.tgz#eee25f56db1c9ec6085e0c22778083f596abf927" + resolved "https://registry.yarnpkg.com/ini/-/ini-1.3.5.tgz" integrity sha512-RZY5huIKCMRWDUqZlEi72f/lmXKMvuszcMBduliQ3nnWbx9X/ZBQO7DijMEYS9EhHBb2qacRUMtC7svLwe0lcw== -interpret@^1.1.0: - version "1.2.0" - resolved "https://registry.yarnpkg.com/interpret/-/interpret-1.2.0.tgz#d5061a6224be58e8083985f5014d844359576296" - integrity sha512-mT34yGKMNceBQUoVn7iCDKDntA7SC6gycMAWzGx1z/CMCTV7b2AAtXlo3nRyHZ1FelRkQbQjprHSYGwzLtkVbw== +interpret@^1.4.0: + version "1.4.0" + resolved "https://registry.yarnpkg.com/interpret/-/interpret-1.4.0.tgz" + integrity sha512-agE4QfB2Lkp9uICn7BAqoscw4SZP9kTE2hxiFI3jBPmXJfdqiahTbUuKGsMoN2GtqL9AxhYioAcVvgsb1HvRbA== invert-kv@^1.0.0: version "1.0.0" - resolved "https://registry.yarnpkg.com/invert-kv/-/invert-kv-1.0.0.tgz#104a8e4aaca6d3d8cd157a8ef8bfab2d7a3ffdb6" + resolved "https://registry.yarnpkg.com/invert-kv/-/invert-kv-1.0.0.tgz" integrity sha1-EEqOSqym09jNFXqO+L+rLXo//bY= irregular-plurals@^2.0.0: version "2.0.0" - resolved "https://registry.yarnpkg.com/irregular-plurals/-/irregular-plurals-2.0.0.tgz#39d40f05b00f656d0b7fa471230dd3b714af2872" + resolved "https://registry.yarnpkg.com/irregular-plurals/-/irregular-plurals-2.0.0.tgz" integrity sha512-Y75zBYLkh0lJ9qxeHlMjQ7bSbyiSqNW/UOPWDmzC7cXskL1hekSITh1Oc6JV0XCWWZ9DE8VYSB71xocLk3gmGw== is-absolute@^1.0.0: version "1.0.0" - resolved "https://registry.yarnpkg.com/is-absolute/-/is-absolute-1.0.0.tgz#395e1ae84b11f26ad1795e73c17378e48a301576" + resolved "https://registry.yarnpkg.com/is-absolute/-/is-absolute-1.0.0.tgz" integrity sha512-dOWoqflvcydARa360Gvv18DZ/gRuHKi2NU/wU5X1ZFzdYfH29nkiNZsF3mp4OJ3H4yo9Mx8A/uAGNzpzPN3yBA== dependencies: is-relative "^1.0.0" @@ -1011,52 +1041,59 @@ is-absolute@^1.0.0: is-accessor-descriptor@^0.1.6: version "0.1.6" - resolved "https://registry.yarnpkg.com/is-accessor-descriptor/-/is-accessor-descriptor-0.1.6.tgz#a9e12cb3ae8d876727eeef3843f8a0897b5c98d6" + resolved "https://registry.yarnpkg.com/is-accessor-descriptor/-/is-accessor-descriptor-0.1.6.tgz" integrity sha1-qeEss66Nh2cn7u84Q/igiXtcmNY= dependencies: kind-of "^3.0.2" is-accessor-descriptor@^1.0.0: version "1.0.0" - resolved "https://registry.yarnpkg.com/is-accessor-descriptor/-/is-accessor-descriptor-1.0.0.tgz#169c2f6d3df1f992618072365c9b0ea1f6878656" + resolved "https://registry.yarnpkg.com/is-accessor-descriptor/-/is-accessor-descriptor-1.0.0.tgz" integrity sha512-m5hnHTkcVsPfqx3AKlyttIPb7J+XykHvJP2B9bZDjlhLIoEq4XoK64Vg7boZlVWYK6LUY94dYPEE7Lh0ZkZKcQ== dependencies: kind-of "^6.0.0" is-arrayish@^0.2.1: version "0.2.1" - resolved "https://registry.yarnpkg.com/is-arrayish/-/is-arrayish-0.2.1.tgz#77c99840527aa8ecb1a8ba697b80645a7a926a9d" + resolved "https://registry.yarnpkg.com/is-arrayish/-/is-arrayish-0.2.1.tgz" integrity sha1-d8mYQFJ6qOyxqLppe4BkWnqSap0= is-binary-path@^1.0.0: version "1.0.1" - resolved "https://registry.yarnpkg.com/is-binary-path/-/is-binary-path-1.0.1.tgz#75f16642b480f187a711c814161fd3a4a7655898" + resolved "https://registry.yarnpkg.com/is-binary-path/-/is-binary-path-1.0.1.tgz" integrity sha1-dfFmQrSA8YenEcgUFh/TpKdlWJg= dependencies: binary-extensions "^1.0.0" is-buffer@^1.1.5: version "1.1.6" - resolved "https://registry.yarnpkg.com/is-buffer/-/is-buffer-1.1.6.tgz#efaa2ea9daa0d7ab2ea13a97b2b8ad51fefbe8be" + resolved "https://registry.yarnpkg.com/is-buffer/-/is-buffer-1.1.6.tgz" integrity sha512-NcdALwpXkTm5Zvvbk7owOUSvVvBKDgKP5/ewfXEznmQFfs4ZRmanOeKBTjRVjka3QFoN6XJ+9F3USqfHqTaU5w== +is-core-module@^2.1.0: + version "2.1.0" + resolved "https://registry.yarnpkg.com/is-core-module/-/is-core-module-2.1.0.tgz" + integrity sha512-YcV7BgVMRFRua2FqQzKtTDMz8iCuLEyGKjr70q8Zm1yy2qKcurbFEd79PAdHV77oL3NrAaOVQIbMmiHQCHB7ZA== + dependencies: + has "^1.0.3" + is-data-descriptor@^0.1.4: version "0.1.4" - resolved "https://registry.yarnpkg.com/is-data-descriptor/-/is-data-descriptor-0.1.4.tgz#0b5ee648388e2c860282e793f1856fec3f301b56" + resolved "https://registry.yarnpkg.com/is-data-descriptor/-/is-data-descriptor-0.1.4.tgz" integrity sha1-C17mSDiOLIYCgueT8YVv7D8wG1Y= dependencies: kind-of "^3.0.2" is-data-descriptor@^1.0.0: version "1.0.0" - resolved "https://registry.yarnpkg.com/is-data-descriptor/-/is-data-descriptor-1.0.0.tgz#d84876321d0e7add03990406abbbbd36ba9268c7" + resolved "https://registry.yarnpkg.com/is-data-descriptor/-/is-data-descriptor-1.0.0.tgz" integrity sha512-jbRXy1FmtAoCjQkVmIVYwuuqDFUbaOeDjmed1tOGPrsMhtJA4rD9tkgA0F1qJ3gRFRXcHYVkdeaP50Q5rE/jLQ== dependencies: kind-of "^6.0.0" is-descriptor@^0.1.0: version "0.1.6" - resolved "https://registry.yarnpkg.com/is-descriptor/-/is-descriptor-0.1.6.tgz#366d8240dde487ca51823b1ab9f07a10a78251ca" + resolved "https://registry.yarnpkg.com/is-descriptor/-/is-descriptor-0.1.6.tgz" integrity sha512-avDYr0SB3DwO9zsMov0gKCESFYqCnE4hq/4z3TdUlukEy5t9C0YRq7HLrsN52NAcqXKaepeCD0n+B0arnVG3Hg== dependencies: is-accessor-descriptor "^0.1.6" @@ -1065,7 +1102,7 @@ is-descriptor@^0.1.0: is-descriptor@^1.0.0, is-descriptor@^1.0.2: version "1.0.2" - resolved "https://registry.yarnpkg.com/is-descriptor/-/is-descriptor-1.0.2.tgz#3b159746a66604b04f8c81524ba365c5f14d86ec" + resolved "https://registry.yarnpkg.com/is-descriptor/-/is-descriptor-1.0.2.tgz" integrity sha512-2eis5WqQGV7peooDyLmNEPUrps9+SXX5c9pL3xEB+4e9HnGuDa7mB7kHxHw4CbqS9k1T2hOH3miL8n8WtiYVtg== dependencies: is-accessor-descriptor "^1.0.0" @@ -1074,164 +1111,164 @@ is-descriptor@^1.0.0, is-descriptor@^1.0.2: is-extendable@^0.1.0, is-extendable@^0.1.1: version "0.1.1" - resolved "https://registry.yarnpkg.com/is-extendable/-/is-extendable-0.1.1.tgz#62b110e289a471418e3ec36a617d472e301dfc89" + resolved "https://registry.yarnpkg.com/is-extendable/-/is-extendable-0.1.1.tgz" integrity sha1-YrEQ4omkcUGOPsNqYX1HLjAd/Ik= is-extendable@^1.0.1: version "1.0.1" - resolved "https://registry.yarnpkg.com/is-extendable/-/is-extendable-1.0.1.tgz#a7470f9e426733d81bd81e1155264e3a3507cab4" + resolved "https://registry.yarnpkg.com/is-extendable/-/is-extendable-1.0.1.tgz" integrity sha512-arnXMxT1hhoKo9k1LZdmlNyJdDDfy2v0fXjFlmok4+i8ul/6WlbVge9bhM74OpNPQPMGUToDtz+KXa1PneJxOA== dependencies: is-plain-object "^2.0.4" is-extglob@^2.1.0, is-extglob@^2.1.1: version "2.1.1" - resolved "https://registry.yarnpkg.com/is-extglob/-/is-extglob-2.1.1.tgz#a88c02535791f02ed37c76a1b9ea9773c833f8c2" + resolved "https://registry.yarnpkg.com/is-extglob/-/is-extglob-2.1.1.tgz" integrity sha1-qIwCU1eR8C7TfHahueqXc8gz+MI= is-fullwidth-code-point@^1.0.0: version "1.0.0" - resolved "https://registry.yarnpkg.com/is-fullwidth-code-point/-/is-fullwidth-code-point-1.0.0.tgz#ef9e31386f031a7f0d643af82fde50c457ef00cb" + resolved "https://registry.yarnpkg.com/is-fullwidth-code-point/-/is-fullwidth-code-point-1.0.0.tgz" integrity sha1-754xOG8DGn8NZDr4L95QxFfvAMs= dependencies: number-is-nan "^1.0.0" is-glob@^3.1.0: version "3.1.0" - resolved "https://registry.yarnpkg.com/is-glob/-/is-glob-3.1.0.tgz#7ba5ae24217804ac70707b96922567486cc3e84a" + resolved "https://registry.yarnpkg.com/is-glob/-/is-glob-3.1.0.tgz" integrity sha1-e6WuJCF4BKxwcHuWkiVnSGzD6Eo= dependencies: is-extglob "^2.1.0" is-glob@^4.0.0: version "4.0.1" - resolved "https://registry.yarnpkg.com/is-glob/-/is-glob-4.0.1.tgz#7567dbe9f2f5e2467bc77ab83c4a29482407a5dc" + resolved "https://registry.yarnpkg.com/is-glob/-/is-glob-4.0.1.tgz" integrity sha512-5G0tKtBTFImOqDnLB2hG6Bp2qcKEFduo4tZu9MT/H6NQv/ghhy30o55ufafxJ/LdH79LLs2Kfrn85TLKyA7BUg== dependencies: is-extglob "^2.1.1" is-negated-glob@^1.0.0: version "1.0.0" - resolved "https://registry.yarnpkg.com/is-negated-glob/-/is-negated-glob-1.0.0.tgz#6910bca5da8c95e784b5751b976cf5a10fee36d2" + resolved "https://registry.yarnpkg.com/is-negated-glob/-/is-negated-glob-1.0.0.tgz" integrity sha1-aRC8pdqMleeEtXUbl2z1oQ/uNtI= is-number@^3.0.0: version "3.0.0" - resolved "https://registry.yarnpkg.com/is-number/-/is-number-3.0.0.tgz#24fd6201a4782cf50561c810276afc7d12d71195" + resolved "https://registry.yarnpkg.com/is-number/-/is-number-3.0.0.tgz" integrity sha1-JP1iAaR4LPUFYcgQJ2r8fRLXEZU= dependencies: kind-of "^3.0.2" is-number@^4.0.0: version "4.0.0" - resolved "https://registry.yarnpkg.com/is-number/-/is-number-4.0.0.tgz#0026e37f5454d73e356dfe6564699867c6a7f0ff" + resolved "https://registry.yarnpkg.com/is-number/-/is-number-4.0.0.tgz" integrity sha512-rSklcAIlf1OmFdyAqbnWTLVelsQ58uvZ66S/ZyawjWqIviTWCjg2PzVGw8WUA+nNuPTqb4wgA+NszrJ+08LlgQ== is-obj@^1.0.1: version "1.0.1" - resolved "https://registry.yarnpkg.com/is-obj/-/is-obj-1.0.1.tgz#3e4729ac1f5fde025cd7d83a896dab9f4f67db0f" + resolved "https://registry.yarnpkg.com/is-obj/-/is-obj-1.0.1.tgz" integrity sha1-PkcprB9f3gJc19g6iW2rn09n2w8= is-plain-object@^2.0.1, is-plain-object@^2.0.3, is-plain-object@^2.0.4: version "2.0.4" - resolved "https://registry.yarnpkg.com/is-plain-object/-/is-plain-object-2.0.4.tgz#2c163b3fafb1b606d9d17928f05c2a1c38e07677" + resolved "https://registry.yarnpkg.com/is-plain-object/-/is-plain-object-2.0.4.tgz" integrity sha512-h5PpgXkWitc38BBMYawTYMWJHFZJVnBquFE57xFpjB8pJFiF6gZ+bU+WyI/yqXiFR5mdLsgYNaPe8uao6Uv9Og== dependencies: isobject "^3.0.1" is-regexp@^1.0.0: version "1.0.0" - resolved "https://registry.yarnpkg.com/is-regexp/-/is-regexp-1.0.0.tgz#fd2d883545c46bac5a633e7b9a09e87fa2cb5069" + resolved "https://registry.yarnpkg.com/is-regexp/-/is-regexp-1.0.0.tgz" integrity sha1-/S2INUXEa6xaYz57mgnof6LLUGk= is-relative@^1.0.0: version "1.0.0" - resolved "https://registry.yarnpkg.com/is-relative/-/is-relative-1.0.0.tgz#a1bb6935ce8c5dba1e8b9754b9b2dcc020e2260d" + resolved "https://registry.yarnpkg.com/is-relative/-/is-relative-1.0.0.tgz" integrity sha512-Kw/ReK0iqwKeu0MITLFuj0jbPAmEiOsIwyIXvvbfa6QfmN9pkD1M+8pdk7Rl/dTKbH34/XBFMbgD4iMJhLQbGA== dependencies: is-unc-path "^1.0.0" is-unc-path@^1.0.0: version "1.0.0" - resolved "https://registry.yarnpkg.com/is-unc-path/-/is-unc-path-1.0.0.tgz#d731e8898ed090a12c352ad2eaed5095ad322c9d" + resolved "https://registry.yarnpkg.com/is-unc-path/-/is-unc-path-1.0.0.tgz" integrity sha512-mrGpVd0fs7WWLfVsStvgF6iEJnbjDFZh9/emhRDcGWTduTfNHd9CHeUwH3gYIjdbwo4On6hunkztwOaAw0yllQ== dependencies: unc-path-regex "^0.1.2" is-utf8@^0.2.0, is-utf8@^0.2.1: version "0.2.1" - resolved "https://registry.yarnpkg.com/is-utf8/-/is-utf8-0.2.1.tgz#4b0da1442104d1b336340e80797e865cf39f7d72" + resolved "https://registry.yarnpkg.com/is-utf8/-/is-utf8-0.2.1.tgz" integrity sha1-Sw2hRCEE0bM2NA6AeX6GXPOffXI= is-valid-glob@^1.0.0: version "1.0.0" - resolved "https://registry.yarnpkg.com/is-valid-glob/-/is-valid-glob-1.0.0.tgz#29bf3eff701be2d4d315dbacc39bc39fe8f601aa" + resolved "https://registry.yarnpkg.com/is-valid-glob/-/is-valid-glob-1.0.0.tgz" integrity sha1-Kb8+/3Ab4tTTFdusw5vDn+j2Aao= is-windows@^1.0.1, is-windows@^1.0.2: version "1.0.2" - resolved "https://registry.yarnpkg.com/is-windows/-/is-windows-1.0.2.tgz#d1850eb9791ecd18e6182ce12a30f396634bb19d" + resolved "https://registry.yarnpkg.com/is-windows/-/is-windows-1.0.2.tgz" integrity sha512-eXK1UInq2bPmjyX6e3VHIzMLobc4J94i4AWn+Hpq3OU5KkrRC96OAcR3PRJ/pGu6m8TRnBHP9dkXQVsT/COVIA== isarray@1.0.0, isarray@~1.0.0: version "1.0.0" - resolved "https://registry.yarnpkg.com/isarray/-/isarray-1.0.0.tgz#bb935d48582cba168c06834957a54a3e07124f11" + resolved "https://registry.yarnpkg.com/isarray/-/isarray-1.0.0.tgz" integrity sha1-u5NdSFgsuhaMBoNJV6VKPgcSTxE= isexe@^2.0.0: version "2.0.0" - resolved "https://registry.yarnpkg.com/isexe/-/isexe-2.0.0.tgz#e8fbf374dc556ff8947a10dcb0572d633f2cfa10" + resolved "https://registry.yarnpkg.com/isexe/-/isexe-2.0.0.tgz" integrity sha1-6PvzdNxVb/iUehDcsFctYz8s+hA= isobject@^2.0.0: version "2.1.0" - resolved "https://registry.yarnpkg.com/isobject/-/isobject-2.1.0.tgz#f065561096a3f1da2ef46272f815c840d87e0c89" + resolved "https://registry.yarnpkg.com/isobject/-/isobject-2.1.0.tgz" integrity sha1-8GVWEJaj8dou9GJy+BXIQNh+DIk= dependencies: isarray "1.0.0" isobject@^3.0.0, isobject@^3.0.1: version "3.0.1" - resolved "https://registry.yarnpkg.com/isobject/-/isobject-3.0.1.tgz#4e431e92b11a9731636aa1f9c8d1ccbcfdab78df" + resolved "https://registry.yarnpkg.com/isobject/-/isobject-3.0.1.tgz" integrity sha1-TkMekrEalzFjaqH5yNHMvP2reN8= json-stable-stringify-without-jsonify@^1.0.1: version "1.0.1" - resolved "https://registry.yarnpkg.com/json-stable-stringify-without-jsonify/-/json-stable-stringify-without-jsonify-1.0.1.tgz#9db7b59496ad3f3cfef30a75142d2d930ad72651" + resolved "https://registry.yarnpkg.com/json-stable-stringify-without-jsonify/-/json-stable-stringify-without-jsonify-1.0.1.tgz" integrity sha1-nbe1lJatPzz+8wp1FC0tkwrXJlE= just-debounce@^1.0.0: version "1.0.0" - resolved "https://registry.yarnpkg.com/just-debounce/-/just-debounce-1.0.0.tgz#87fccfaeffc0b68cd19d55f6722943f929ea35ea" + resolved "https://registry.yarnpkg.com/just-debounce/-/just-debounce-1.0.0.tgz" integrity sha1-h/zPrv/AtozRnVX2cilD+SnqNeo= kind-of@^3.0.2, kind-of@^3.0.3, kind-of@^3.2.0: version "3.2.2" - resolved "https://registry.yarnpkg.com/kind-of/-/kind-of-3.2.2.tgz#31ea21a734bab9bbb0f32466d893aea51e4a3c64" + resolved "https://registry.yarnpkg.com/kind-of/-/kind-of-3.2.2.tgz" integrity sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ= dependencies: is-buffer "^1.1.5" kind-of@^4.0.0: version "4.0.0" - resolved "https://registry.yarnpkg.com/kind-of/-/kind-of-4.0.0.tgz#20813df3d712928b207378691a45066fae72dd57" + resolved "https://registry.yarnpkg.com/kind-of/-/kind-of-4.0.0.tgz" integrity sha1-IIE989cSkosgc3hpGkUGb65y3Vc= dependencies: is-buffer "^1.1.5" kind-of@^5.0.0, kind-of@^5.0.2: version "5.1.0" - resolved "https://registry.yarnpkg.com/kind-of/-/kind-of-5.1.0.tgz#729c91e2d857b7a419a1f9aa65685c4c33f5845d" + resolved "https://registry.yarnpkg.com/kind-of/-/kind-of-5.1.0.tgz" integrity sha512-NGEErnH6F2vUuXDh+OlbcKW7/wOcfdRHaZ7VWtqCztfHri/++YKmP51OdWeGPuqCOba6kk2OTe5d02VmTB80Pw== kind-of@^6.0.0, kind-of@^6.0.2: version "6.0.3" - resolved "https://registry.yarnpkg.com/kind-of/-/kind-of-6.0.3.tgz#07c05034a6c349fa06e24fa35aa76db4580ce4dd" + resolved "https://registry.yarnpkg.com/kind-of/-/kind-of-6.0.3.tgz" integrity sha512-dcS1ul+9tmeD95T+x28/ehLgd9mENa3LsvDTtzm3vyBEO7RPptvAD+t44WVXaUjTBRcrpFeFlC8WCruUR456hw== last-run@^1.1.0: version "1.1.1" - resolved "https://registry.yarnpkg.com/last-run/-/last-run-1.1.1.tgz#45b96942c17b1c79c772198259ba943bebf8ca5b" + resolved "https://registry.yarnpkg.com/last-run/-/last-run-1.1.1.tgz" integrity sha1-RblpQsF7HHnHchmCWbqUO+v4yls= dependencies: default-resolution "^2.0.0" @@ -1239,28 +1276,28 @@ last-run@^1.1.0: lazystream@^1.0.0: version "1.0.0" - resolved "https://registry.yarnpkg.com/lazystream/-/lazystream-1.0.0.tgz#f6995fe0f820392f61396be89462407bb77168e4" + resolved "https://registry.yarnpkg.com/lazystream/-/lazystream-1.0.0.tgz" integrity sha1-9plf4PggOS9hOWvolGJAe7dxaOQ= dependencies: readable-stream "^2.0.5" lcid@^1.0.0: version "1.0.0" - resolved "https://registry.yarnpkg.com/lcid/-/lcid-1.0.0.tgz#308accafa0bc483a3867b4b6f2b9506251d1b835" + resolved "https://registry.yarnpkg.com/lcid/-/lcid-1.0.0.tgz" integrity sha1-MIrMr6C8SDo4Z7S28rlQYlHRuDU= dependencies: invert-kv "^1.0.0" lead@^1.0.0: version "1.0.0" - resolved "https://registry.yarnpkg.com/lead/-/lead-1.0.0.tgz#6f14f99a37be3a9dd784f5495690e5903466ee42" + resolved "https://registry.yarnpkg.com/lead/-/lead-1.0.0.tgz" integrity sha1-bxT5mje+Op3XhPVJVpDlkDRm7kI= dependencies: flush-write-stream "^1.0.2" liftoff@^3.1.0: version "3.1.0" - resolved "https://registry.yarnpkg.com/liftoff/-/liftoff-3.1.0.tgz#c9ba6081f908670607ee79062d700df062c52ed3" + resolved "https://registry.yarnpkg.com/liftoff/-/liftoff-3.1.0.tgz" integrity sha512-DlIPlJUkCV0Ips2zf2pJP0unEoT1kwYhiiPUGF3s/jtxTCjziNLoiVVh+jqWOWeFi6mmwQ5fNxvAUyPad4Dfog== dependencies: extend "^3.0.0" @@ -1274,14 +1311,14 @@ liftoff@^3.1.0: linkify-it@^3.0.1: version "3.0.2" - resolved "https://registry.yarnpkg.com/linkify-it/-/linkify-it-3.0.2.tgz#f55eeb8bc1d3ae754049e124ab3bb56d97797fb8" + resolved "https://registry.yarnpkg.com/linkify-it/-/linkify-it-3.0.2.tgz" integrity sha512-gDBO4aHNZS6coiZCKVhSNh43F9ioIL4JwRjLZPkoLIY4yZFwg264Y5lu2x6rb1Js42Gh6Yqm2f6L2AJcnkzinQ== dependencies: uc.micro "^1.0.1" load-json-file@^1.0.0: version "1.1.0" - resolved "https://registry.yarnpkg.com/load-json-file/-/load-json-file-1.1.0.tgz#956905708d58b4bab4c2261b04f59f31c99374c0" + resolved "https://registry.yarnpkg.com/load-json-file/-/load-json-file-1.1.0.tgz" integrity sha1-lWkFcI1YtLq0wiYbBPWfMcmTdMA= dependencies: graceful-fs "^4.1.2" @@ -1292,26 +1329,26 @@ load-json-file@^1.0.0: make-iterator@^1.0.0: version "1.0.1" - resolved "https://registry.yarnpkg.com/make-iterator/-/make-iterator-1.0.1.tgz#29b33f312aa8f547c4a5e490f56afcec99133ad6" + resolved "https://registry.yarnpkg.com/make-iterator/-/make-iterator-1.0.1.tgz" integrity sha512-pxiuXh0iVEq7VM7KMIhs5gxsfxCux2URptUQaXo4iZZJxBAzTPOLE2BumO5dbfVYq/hBJFBR/a1mFDmOx5AGmw== dependencies: kind-of "^6.0.2" map-cache@^0.2.0, map-cache@^0.2.2: version "0.2.2" - resolved "https://registry.yarnpkg.com/map-cache/-/map-cache-0.2.2.tgz#c32abd0bd6525d9b051645bb4f26ac5dc98a0dbf" + resolved "https://registry.yarnpkg.com/map-cache/-/map-cache-0.2.2.tgz" integrity sha1-wyq9C9ZSXZsFFkW7TyasXcmKDb8= map-visit@^1.0.0: version "1.0.0" - resolved "https://registry.yarnpkg.com/map-visit/-/map-visit-1.0.0.tgz#ecdca8f13144e660f1b5bd41f12f3479d98dfb8f" + resolved "https://registry.yarnpkg.com/map-visit/-/map-visit-1.0.0.tgz" integrity sha1-7Nyo8TFE5mDxtb1B8S80edmN+48= dependencies: object-visit "^1.0.0" markdown-it@11.0.0: version "11.0.0" - resolved "https://registry.yarnpkg.com/markdown-it/-/markdown-it-11.0.0.tgz#dbfc30363e43d756ebc52c38586b91b90046b876" + resolved "https://registry.yarnpkg.com/markdown-it/-/markdown-it-11.0.0.tgz" integrity sha512-+CvOnmbSubmQFSA9dKz1BRiaSMV7rhexl3sngKqFyXSagoA3fBdJQ8oZWtRy2knXdpDXaBw44euz37DeJQ9asg== dependencies: argparse "^1.0.7" @@ -1321,15 +1358,15 @@ markdown-it@11.0.0: uc.micro "^1.0.5" markdownlint@^0.21.0: - version "0.21.0" - resolved "https://registry.yarnpkg.com/markdownlint/-/markdownlint-0.21.0.tgz#411a6937315c7562042e478cd91f52194ff88da4" - integrity sha512-rTxr0fbCFmS65oxXBD0HNy3/+PSukLS+b7Z6rGDWbjdRJp/e2dKj538r3KTn8oXrusx+ZtuYOozV2Knpnn0pkQ== + version "0.21.1" + resolved "https://registry.yarnpkg.com/markdownlint/-/markdownlint-0.21.1.tgz" + integrity sha512-8kc88w5dyEzlmOWIElp8J17qBgzouOQfJ0LhCcpBFrwgyYK6JTKvILsk4FCEkiNqHkTxwxopT2RS2DYb/10qqg== dependencies: markdown-it "11.0.0" matchdep@^2.0.0: version "2.0.0" - resolved "https://registry.yarnpkg.com/matchdep/-/matchdep-2.0.0.tgz#c6f34834a0d8dbc3b37c27ee8bbcb27c7775582e" + resolved "https://registry.yarnpkg.com/matchdep/-/matchdep-2.0.0.tgz" integrity sha1-xvNINKDY28OzfCfui7yyfHd1WC4= dependencies: findup-sync "^2.0.0" @@ -1339,12 +1376,12 @@ matchdep@^2.0.0: mdurl@^1.0.1: version "1.0.1" - resolved "https://registry.yarnpkg.com/mdurl/-/mdurl-1.0.1.tgz#fe85b2ec75a59037f2adfec100fd6c601761152e" + resolved "https://registry.yarnpkg.com/mdurl/-/mdurl-1.0.1.tgz" integrity sha1-/oWy7HWlkDfyrf7BAP1sYBdhFS4= micromatch@^3.0.4, micromatch@^3.1.10, micromatch@^3.1.4: version "3.1.10" - resolved "https://registry.yarnpkg.com/micromatch/-/micromatch-3.1.10.tgz#70859bc95c9840952f359a068a3fc49f9ecfac23" + resolved "https://registry.yarnpkg.com/micromatch/-/micromatch-3.1.10.tgz" integrity sha512-MWikgl9n9M3w+bpsY3He8L+w9eF9338xRl8IAO5viDizwSzziFEyUzo2xrrloB64ADbTf8uA8vRqqttDTOmccg== dependencies: arr-diff "^4.0.0" @@ -1363,14 +1400,14 @@ micromatch@^3.0.4, micromatch@^3.1.10, micromatch@^3.1.4: minimatch@^3.0.4: version "3.0.4" - resolved "https://registry.yarnpkg.com/minimatch/-/minimatch-3.0.4.tgz#5166e286457f03306064be5497e8dbb0c3d32083" + resolved "https://registry.yarnpkg.com/minimatch/-/minimatch-3.0.4.tgz" integrity sha512-yJHVQEhyqPLUTgt9B83PXu6W3rx4MvvHvSUvToogpwoGDOUQ+yDrR0HRot+yOCdCO7u4hX3pWft6kWBBcqh0UA== dependencies: brace-expansion "^1.1.7" mixin-deep@^1.2.0: version "1.3.2" - resolved "https://registry.yarnpkg.com/mixin-deep/-/mixin-deep-1.3.2.tgz#1120b43dc359a785dce65b55b82e257ccf479566" + resolved "https://registry.yarnpkg.com/mixin-deep/-/mixin-deep-1.3.2.tgz" integrity sha512-WRoDn//mXBiJ1H40rqa3vH0toePwSsGb45iInWlTySa+Uu4k3tYUSxa2v1KqAiLtvlrSzaExqS1gtk96A9zvEA== dependencies: for-in "^1.0.2" @@ -1378,22 +1415,22 @@ mixin-deep@^1.2.0: ms@2.0.0: version "2.0.0" - resolved "https://registry.yarnpkg.com/ms/-/ms-2.0.0.tgz#5608aeadfc00be6c2901df5f9861788de0d597c8" + resolved "https://registry.yarnpkg.com/ms/-/ms-2.0.0.tgz" integrity sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g= mute-stdout@^1.0.0: version "1.0.1" - resolved "https://registry.yarnpkg.com/mute-stdout/-/mute-stdout-1.0.1.tgz#acb0300eb4de23a7ddeec014e3e96044b3472331" + resolved "https://registry.yarnpkg.com/mute-stdout/-/mute-stdout-1.0.1.tgz" integrity sha512-kDcwXR4PS7caBpuRYYBUz9iVixUk3anO3f5OYFiIPwK/20vCzKCHyKoulbiDY1S53zD2bxUpxN/IJ+TnXjfvxg== nan@^2.12.1: - version "2.14.1" - resolved "https://registry.yarnpkg.com/nan/-/nan-2.14.1.tgz#d7be34dfa3105b91494c3147089315eff8874b01" - integrity sha512-isWHgVjnFjh2x2yuJ/tj3JbwoHu3UC2dX5G/88Cm24yB6YopVgxvBObDY7n5xW6ExmFhJpSEQqFPvq9zaXc8Jw== + version "2.14.2" + resolved "https://registry.yarnpkg.com/nan/-/nan-2.14.2.tgz" + integrity sha512-M2ufzIiINKCuDfBSAUr1vWQ+vuVcA9kqx8JJUsbQi6yf1uGRyb7HfpdfUr5qLXf3B/t8dPvcjhKMmlfnP47EzQ== nanomatch@^1.2.9: version "1.2.13" - resolved "https://registry.yarnpkg.com/nanomatch/-/nanomatch-1.2.13.tgz#b87a8aa4fc0de8fe6be88895b38983ff265bd119" + resolved "https://registry.yarnpkg.com/nanomatch/-/nanomatch-1.2.13.tgz" integrity sha512-fpoe2T0RbHwBTBUOftAfBPaDEi06ufaUai0mE6Yn1kacc3SnTErfb/h+X94VXzI64rKFHYImXSvdwGGCmwOqCA== dependencies: arr-diff "^4.0.0" @@ -1410,12 +1447,12 @@ nanomatch@^1.2.9: next-tick@~1.0.0: version "1.0.0" - resolved "https://registry.yarnpkg.com/next-tick/-/next-tick-1.0.0.tgz#ca86d1fe8828169b0120208e3dc8424b9db8342c" + resolved "https://registry.yarnpkg.com/next-tick/-/next-tick-1.0.0.tgz" integrity sha1-yobR/ogoFpsBICCOPchCS524NCw= normalize-package-data@^2.3.2: version "2.5.0" - resolved "https://registry.yarnpkg.com/normalize-package-data/-/normalize-package-data-2.5.0.tgz#e66db1838b200c1dfc233225d12cb36520e234a8" + resolved "https://registry.yarnpkg.com/normalize-package-data/-/normalize-package-data-2.5.0.tgz" integrity sha512-/5CMN3T0R4XTj4DcGaexo+roZSdSFW/0AOOTROrjxzCG1wrWXEsGbRKevjlIL+ZDE4sZlJr5ED4YW0yqmkK+eA== dependencies: hosted-git-info "^2.1.4" @@ -1425,62 +1462,62 @@ normalize-package-data@^2.3.2: normalize-path@^2.1.1: version "2.1.1" - resolved "https://registry.yarnpkg.com/normalize-path/-/normalize-path-2.1.1.tgz#1ab28b556e198363a8c1a6f7e6fa20137fe6aed9" + resolved "https://registry.yarnpkg.com/normalize-path/-/normalize-path-2.1.1.tgz" integrity sha1-GrKLVW4Zg2Oowab35vogE3/mrtk= dependencies: remove-trailing-separator "^1.0.1" normalize-path@^3.0.0: version "3.0.0" - resolved "https://registry.yarnpkg.com/normalize-path/-/normalize-path-3.0.0.tgz#0dcd69ff23a1c9b11fd0978316644a0388216a65" + resolved "https://registry.yarnpkg.com/normalize-path/-/normalize-path-3.0.0.tgz" integrity sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA== now-and-later@^2.0.0: version "2.0.1" - resolved "https://registry.yarnpkg.com/now-and-later/-/now-and-later-2.0.1.tgz#8e579c8685764a7cc02cb680380e94f43ccb1f7c" + resolved "https://registry.yarnpkg.com/now-and-later/-/now-and-later-2.0.1.tgz" integrity sha512-KGvQ0cB70AQfg107Xvs/Fbu+dGmZoTRJp2TaPwcwQm3/7PteUyN2BCgk8KBMPGBUXZdVwyWS8fDCGFygBm19UQ== dependencies: once "^1.3.2" number-is-nan@^1.0.0: version "1.0.1" - resolved "https://registry.yarnpkg.com/number-is-nan/-/number-is-nan-1.0.1.tgz#097b602b53422a522c1afb8790318336941a011d" + resolved "https://registry.yarnpkg.com/number-is-nan/-/number-is-nan-1.0.1.tgz" integrity sha1-CXtgK1NCKlIsGvuHkDGDNpQaAR0= object-copy@^0.1.0: version "0.1.0" - resolved "https://registry.yarnpkg.com/object-copy/-/object-copy-0.1.0.tgz#7e7d858b781bd7c991a41ba975ed3812754e998c" + resolved "https://registry.yarnpkg.com/object-copy/-/object-copy-0.1.0.tgz" integrity sha1-fn2Fi3gb18mRpBupde04EnVOmYw= dependencies: copy-descriptor "^0.1.0" define-property "^0.2.5" kind-of "^3.0.3" -object-keys@^1.0.11, object-keys@^1.0.12: +object-keys@^1.0.12, object-keys@^1.1.1: version "1.1.1" - resolved "https://registry.yarnpkg.com/object-keys/-/object-keys-1.1.1.tgz#1c47f272df277f3b1daf061677d9c82e2322c60e" + resolved "https://registry.yarnpkg.com/object-keys/-/object-keys-1.1.1.tgz" integrity sha512-NuAESUOUMrlIXOfHKzD6bpPu3tYt3xvjNdRIQ+FeT0lNb4K8WR70CaDxhuNguS2XG+GjkyMwOzsN5ZktImfhLA== object-visit@^1.0.0: version "1.0.1" - resolved "https://registry.yarnpkg.com/object-visit/-/object-visit-1.0.1.tgz#f79c4493af0c5377b59fe39d395e41042dd045bb" + resolved "https://registry.yarnpkg.com/object-visit/-/object-visit-1.0.1.tgz" integrity sha1-95xEk68MU3e1n+OdOV5BBC3QRbs= dependencies: isobject "^3.0.0" -object.assign@^4.0.4, object.assign@^4.1.0: - version "4.1.0" - resolved "https://registry.yarnpkg.com/object.assign/-/object.assign-4.1.0.tgz#968bf1100d7956bb3ca086f006f846b3bc4008da" - integrity sha512-exHJeq6kBKj58mqGyTQ9DFvrZC/eR6OwxzoM9YRoGBqrXYonaFyGiFMuc9VZrXf7DarreEwMpurG3dd+CNyW5w== +object.assign@^4.0.4: + version "4.1.2" + resolved "https://registry.yarnpkg.com/object.assign/-/object.assign-4.1.2.tgz" + integrity sha512-ixT2L5THXsApyiUPYKmW+2EHpXXe5Ii3M+f4e+aJFAHao5amFRW6J0OO6c/LU8Be47utCx2GL89hxGB6XSmKuQ== dependencies: - define-properties "^1.1.2" - function-bind "^1.1.1" - has-symbols "^1.0.0" - object-keys "^1.0.11" + call-bind "^1.0.0" + define-properties "^1.1.3" + has-symbols "^1.0.1" + object-keys "^1.1.1" object.defaults@^1.0.0, object.defaults@^1.1.0: version "1.1.0" - resolved "https://registry.yarnpkg.com/object.defaults/-/object.defaults-1.1.0.tgz#3a7f868334b407dea06da16d88d5cd29e435fecf" + resolved "https://registry.yarnpkg.com/object.defaults/-/object.defaults-1.1.0.tgz" integrity sha1-On+GgzS0B96gbaFtiNXNKeQ1/s8= dependencies: array-each "^1.0.1" @@ -1490,7 +1527,7 @@ object.defaults@^1.0.0, object.defaults@^1.1.0: object.map@^1.0.0: version "1.0.1" - resolved "https://registry.yarnpkg.com/object.map/-/object.map-1.0.1.tgz#cf83e59dc8fcc0ad5f4250e1f78b3b81bd801d37" + resolved "https://registry.yarnpkg.com/object.map/-/object.map-1.0.1.tgz" integrity sha1-z4Plncj8wK1fQlDh94s7gb2AHTc= dependencies: for-own "^1.0.0" @@ -1498,14 +1535,14 @@ object.map@^1.0.0: object.pick@^1.2.0, object.pick@^1.3.0: version "1.3.0" - resolved "https://registry.yarnpkg.com/object.pick/-/object.pick-1.3.0.tgz#87a10ac4c1694bd2e1cbf53591a66141fb5dd747" + resolved "https://registry.yarnpkg.com/object.pick/-/object.pick-1.3.0.tgz" integrity sha1-h6EKxMFpS9Lhy/U1kaZhQftd10c= dependencies: isobject "^3.0.1" object.reduce@^1.0.0: version "1.0.1" - resolved "https://registry.yarnpkg.com/object.reduce/-/object.reduce-1.0.1.tgz#6fe348f2ac7fa0f95ca621226599096825bb03ad" + resolved "https://registry.yarnpkg.com/object.reduce/-/object.reduce-1.0.1.tgz" integrity sha1-b+NI8qx/oPlcpiEiZZkJaCW7A60= dependencies: for-own "^1.0.0" @@ -1513,33 +1550,33 @@ object.reduce@^1.0.0: once@^1.3.0, once@^1.3.1, once@^1.3.2, once@^1.4.0: version "1.4.0" - resolved "https://registry.yarnpkg.com/once/-/once-1.4.0.tgz#583b1aa775961d4b113ac17d9c50baef9dd76bd1" + resolved "https://registry.yarnpkg.com/once/-/once-1.4.0.tgz" integrity sha1-WDsap3WWHUsROsF9nFC6753Xa9E= dependencies: wrappy "1" ordered-read-streams@^1.0.0: version "1.0.1" - resolved "https://registry.yarnpkg.com/ordered-read-streams/-/ordered-read-streams-1.0.1.tgz#77c0cb37c41525d64166d990ffad7ec6a0e1363e" + resolved "https://registry.yarnpkg.com/ordered-read-streams/-/ordered-read-streams-1.0.1.tgz" integrity sha1-d8DLN8QVJdZBZtmQ/61+xqDhNj4= dependencies: readable-stream "^2.0.1" os-homedir@^1.0.0: version "1.0.2" - resolved "https://registry.yarnpkg.com/os-homedir/-/os-homedir-1.0.2.tgz#ffbc4988336e0e833de0c168c7ef152121aa7fb3" + resolved "https://registry.yarnpkg.com/os-homedir/-/os-homedir-1.0.2.tgz" integrity sha1-/7xJiDNuDoM94MFox+8VISGqf7M= os-locale@^1.4.0: version "1.4.0" - resolved "https://registry.yarnpkg.com/os-locale/-/os-locale-1.4.0.tgz#20f9f17ae29ed345e8bde583b13d2009803c14d9" + resolved "https://registry.yarnpkg.com/os-locale/-/os-locale-1.4.0.tgz" integrity sha1-IPnxeuKe00XoveWDsT0gCYA8FNk= dependencies: lcid "^1.0.0" parse-filepath@^1.0.1: version "1.0.2" - resolved "https://registry.yarnpkg.com/parse-filepath/-/parse-filepath-1.0.2.tgz#a632127f53aaf3d15876f5872f3ffac763d6c891" + resolved "https://registry.yarnpkg.com/parse-filepath/-/parse-filepath-1.0.2.tgz" integrity sha1-pjISf1Oq89FYdvWHLz/6x2PWyJE= dependencies: is-absolute "^1.0.0" @@ -1548,63 +1585,63 @@ parse-filepath@^1.0.1: parse-json@^2.2.0: version "2.2.0" - resolved "https://registry.yarnpkg.com/parse-json/-/parse-json-2.2.0.tgz#f480f40434ef80741f8469099f8dea18f55a4dc9" + resolved "https://registry.yarnpkg.com/parse-json/-/parse-json-2.2.0.tgz" integrity sha1-9ID0BDTvgHQfhGkJn43qGPVaTck= dependencies: error-ex "^1.2.0" parse-node-version@^1.0.0: version "1.0.1" - resolved "https://registry.yarnpkg.com/parse-node-version/-/parse-node-version-1.0.1.tgz#e2b5dbede00e7fa9bc363607f53327e8b073189b" + resolved "https://registry.yarnpkg.com/parse-node-version/-/parse-node-version-1.0.1.tgz" integrity sha512-3YHlOa/JgH6Mnpr05jP9eDG254US9ek25LyIxZlDItp2iJtwyaXQb57lBYLdT3MowkUFYEV2XXNAYIPlESvJlA== parse-passwd@^1.0.0: version "1.0.0" - resolved "https://registry.yarnpkg.com/parse-passwd/-/parse-passwd-1.0.0.tgz#6d5b934a456993b23d37f40a382d6f1666a8e5c6" + resolved "https://registry.yarnpkg.com/parse-passwd/-/parse-passwd-1.0.0.tgz" integrity sha1-bVuTSkVpk7I9N/QKOC1vFmao5cY= pascalcase@^0.1.1: version "0.1.1" - resolved "https://registry.yarnpkg.com/pascalcase/-/pascalcase-0.1.1.tgz#b363e55e8006ca6fe21784d2db22bd15d7917f14" + resolved "https://registry.yarnpkg.com/pascalcase/-/pascalcase-0.1.1.tgz" integrity sha1-s2PlXoAGym/iF4TS2yK9FdeRfxQ= path-dirname@^1.0.0: version "1.0.2" - resolved "https://registry.yarnpkg.com/path-dirname/-/path-dirname-1.0.2.tgz#cc33d24d525e099a5388c0336c6e32b9160609e0" + resolved "https://registry.yarnpkg.com/path-dirname/-/path-dirname-1.0.2.tgz" integrity sha1-zDPSTVJeCZpTiMAzbG4yuRYGCeA= path-exists@^2.0.0: version "2.1.0" - resolved "https://registry.yarnpkg.com/path-exists/-/path-exists-2.1.0.tgz#0feb6c64f0fc518d9a754dd5efb62c7022761f4b" + resolved "https://registry.yarnpkg.com/path-exists/-/path-exists-2.1.0.tgz" integrity sha1-D+tsZPD8UY2adU3V77YscCJ2H0s= dependencies: pinkie-promise "^2.0.0" path-is-absolute@^1.0.0: version "1.0.1" - resolved "https://registry.yarnpkg.com/path-is-absolute/-/path-is-absolute-1.0.1.tgz#174b9268735534ffbc7ace6bf53a5a9e1b5c5f5f" + resolved "https://registry.yarnpkg.com/path-is-absolute/-/path-is-absolute-1.0.1.tgz" integrity sha1-F0uSaHNVNP+8es5r9TpanhtcX18= path-parse@^1.0.6: version "1.0.6" - resolved "https://registry.yarnpkg.com/path-parse/-/path-parse-1.0.6.tgz#d62dbb5679405d72c4737ec58600e9ddcf06d24c" + resolved "https://registry.yarnpkg.com/path-parse/-/path-parse-1.0.6.tgz" integrity sha512-GSmOT2EbHrINBf9SR7CDELwlJ8AENk3Qn7OikK4nFYAu3Ote2+JYNVvkpAEQm3/TLNEJFD/xZJjzyxg3KBWOzw== path-root-regex@^0.1.0: version "0.1.2" - resolved "https://registry.yarnpkg.com/path-root-regex/-/path-root-regex-0.1.2.tgz#bfccdc8df5b12dc52c8b43ec38d18d72c04ba96d" + resolved "https://registry.yarnpkg.com/path-root-regex/-/path-root-regex-0.1.2.tgz" integrity sha1-v8zcjfWxLcUsi0PsONGNcsBLqW0= path-root@^0.1.1: version "0.1.1" - resolved "https://registry.yarnpkg.com/path-root/-/path-root-0.1.1.tgz#9a4a6814cac1c0cd73360a95f32083c8ea4745b7" + resolved "https://registry.yarnpkg.com/path-root/-/path-root-0.1.1.tgz" integrity sha1-mkpoFMrBwM1zNgqV8yCDyOpHRbc= dependencies: path-root-regex "^0.1.0" path-type@^1.0.0: version "1.1.0" - resolved "https://registry.yarnpkg.com/path-type/-/path-type-1.1.0.tgz#59c44f7ee491da704da415da5a4070ba4f8fe441" + resolved "https://registry.yarnpkg.com/path-type/-/path-type-1.1.0.tgz" integrity sha1-WcRPfuSR2nBNpBXaWkBwuk+P5EE= dependencies: graceful-fs "^4.1.2" @@ -1613,46 +1650,46 @@ path-type@^1.0.0: pify@^2.0.0: version "2.3.0" - resolved "https://registry.yarnpkg.com/pify/-/pify-2.3.0.tgz#ed141a6ac043a849ea588498e7dca8b15330e90c" + resolved "https://registry.yarnpkg.com/pify/-/pify-2.3.0.tgz" integrity sha1-7RQaasBDqEnqWISY59yosVMw6Qw= pinkie-promise@^2.0.0: version "2.0.1" - resolved "https://registry.yarnpkg.com/pinkie-promise/-/pinkie-promise-2.0.1.tgz#2135d6dfa7a358c069ac9b178776288228450ffa" + resolved "https://registry.yarnpkg.com/pinkie-promise/-/pinkie-promise-2.0.1.tgz" integrity sha1-ITXW36ejWMBprJsXh3YogihFD/o= dependencies: pinkie "^2.0.0" pinkie@^2.0.0: version "2.0.4" - resolved "https://registry.yarnpkg.com/pinkie/-/pinkie-2.0.4.tgz#72556b80cfa0d48a974e80e77248e80ed4f7f870" + resolved "https://registry.yarnpkg.com/pinkie/-/pinkie-2.0.4.tgz" integrity sha1-clVrgM+g1IqXToDnckjoDtT3+HA= plur@^3.0.0: version "3.1.1" - resolved "https://registry.yarnpkg.com/plur/-/plur-3.1.1.tgz#60267967866a8d811504fe58f2faaba237546a5b" + resolved "https://registry.yarnpkg.com/plur/-/plur-3.1.1.tgz" integrity sha512-t1Ax8KUvV3FFII8ltczPn2tJdjqbd1sIzu6t4JL7nQ3EyeL/lTrj5PWKb06ic5/6XYDr65rQ4uzQEGN70/6X5w== dependencies: irregular-plurals "^2.0.0" posix-character-classes@^0.1.0: version "0.1.1" - resolved "https://registry.yarnpkg.com/posix-character-classes/-/posix-character-classes-0.1.1.tgz#01eac0fe3b5af71a2a6c02feabb8c1fef7e00eab" + resolved "https://registry.yarnpkg.com/posix-character-classes/-/posix-character-classes-0.1.1.tgz" integrity sha1-AerA/jta9xoqbAL+q7jB/vfgDqs= pretty-hrtime@^1.0.0: version "1.0.3" - resolved "https://registry.yarnpkg.com/pretty-hrtime/-/pretty-hrtime-1.0.3.tgz#b7e3ea42435a4c9b2759d99e0f201eb195802ee1" + resolved "https://registry.yarnpkg.com/pretty-hrtime/-/pretty-hrtime-1.0.3.tgz" integrity sha1-t+PqQkNaTJsnWdmeDyAesZWALuE= process-nextick-args@^2.0.0, process-nextick-args@~2.0.0: version "2.0.1" - resolved "https://registry.yarnpkg.com/process-nextick-args/-/process-nextick-args-2.0.1.tgz#7820d9b16120cc55ca9ae7792680ae7dba6d7fe2" + resolved "https://registry.yarnpkg.com/process-nextick-args/-/process-nextick-args-2.0.1.tgz" integrity sha512-3ouUOpQhtgrbOa17J7+uxOTpITYWaGP7/AhoR3+A+/1e9skrzelGi/dXzEYyvbxubEF6Wn2ypscTKiKJFFn1ag== pump@^2.0.0: version "2.0.1" - resolved "https://registry.yarnpkg.com/pump/-/pump-2.0.1.tgz#12399add6e4cf7526d973cbc8b5ce2e2908b3909" + resolved "https://registry.yarnpkg.com/pump/-/pump-2.0.1.tgz" integrity sha512-ruPMNRkN3MHP1cWJc9OWr+T/xDP0jhXYCLfJcBuX54hhfIBnaQmAUMfDcG4DM5UMWByBbJY69QSphm3jtDKIkA== dependencies: end-of-stream "^1.1.0" @@ -1660,7 +1697,7 @@ pump@^2.0.0: pumpify@^1.3.5: version "1.5.1" - resolved "https://registry.yarnpkg.com/pumpify/-/pumpify-1.5.1.tgz#36513be246ab27570b1a374a5ce278bfd74370ce" + resolved "https://registry.yarnpkg.com/pumpify/-/pumpify-1.5.1.tgz" integrity sha512-oClZI37HvuUJJxSKKrC17bZ9Cu0ZYhEAGPsPUy9KlMUmv9dKX2o77RUmq7f3XjIxbwyGwYzbzQ1L2Ks8sIradQ== dependencies: duplexify "^3.6.0" @@ -1669,7 +1706,7 @@ pumpify@^1.3.5: read-pkg-up@^1.0.1: version "1.0.1" - resolved "https://registry.yarnpkg.com/read-pkg-up/-/read-pkg-up-1.0.1.tgz#9d63c13276c065918d57f002a57f40a1b643fb02" + resolved "https://registry.yarnpkg.com/read-pkg-up/-/read-pkg-up-1.0.1.tgz" integrity sha1-nWPBMnbAZZGNV/ACpX9AobZD+wI= dependencies: find-up "^1.0.0" @@ -1677,7 +1714,7 @@ read-pkg-up@^1.0.1: read-pkg@^1.0.0: version "1.1.0" - resolved "https://registry.yarnpkg.com/read-pkg/-/read-pkg-1.1.0.tgz#f5ffaa5ecd29cb31c0474bca7d756b6bb29e3f28" + resolved "https://registry.yarnpkg.com/read-pkg/-/read-pkg-1.1.0.tgz" integrity sha1-9f+qXs0pyzHAR0vKfXVra7KePyg= dependencies: load-json-file "^1.0.0" @@ -1686,7 +1723,7 @@ read-pkg@^1.0.0: readable-stream@3: version "3.6.0" - resolved "https://registry.yarnpkg.com/readable-stream/-/readable-stream-3.6.0.tgz#337bbda3adc0706bd3e024426a286d4b4b2c9198" + resolved "https://registry.yarnpkg.com/readable-stream/-/readable-stream-3.6.0.tgz" integrity sha512-BViHy7LKeTz4oNnkcLJ+lVSL6vpiFeX6/d3oSH8zCW7UxP2onchk+vTGB143xuFjHS3deTgkKoXXymXqymiIdA== dependencies: inherits "^2.0.3" @@ -1695,7 +1732,7 @@ readable-stream@3: readable-stream@^2.0.0, readable-stream@^2.0.1, readable-stream@^2.0.2, readable-stream@^2.0.5, readable-stream@^2.1.5, readable-stream@^2.2.2, readable-stream@^2.3.3, readable-stream@^2.3.5, readable-stream@^2.3.6, readable-stream@~2.3.6: version "2.3.7" - resolved "https://registry.yarnpkg.com/readable-stream/-/readable-stream-2.3.7.tgz#1eca1cf711aef814c04f62252a36a62f6cb23b57" + resolved "https://registry.yarnpkg.com/readable-stream/-/readable-stream-2.3.7.tgz" integrity sha512-Ebho8K4jIbHAxnuxi7o42OrZgF/ZTNcsZj6nRKyUmkhLFq8CHItp/fy6hQZuZmP/n3yZ9VBUbp4zz/mX8hmYPw== dependencies: core-util-is "~1.0.0" @@ -1708,7 +1745,7 @@ readable-stream@^2.0.0, readable-stream@^2.0.1, readable-stream@^2.0.2, readable readdirp@^2.2.1: version "2.2.1" - resolved "https://registry.yarnpkg.com/readdirp/-/readdirp-2.2.1.tgz#0e87622a3325aa33e892285caf8b4e846529a525" + resolved "https://registry.yarnpkg.com/readdirp/-/readdirp-2.2.1.tgz" integrity sha512-1JU/8q+VgFZyxwrJ+SVIOsh+KywWGpds3NTqikiKpDMZWScmAYyKIgqkO+ARvNWJfXeXR1zxz7aHF4u4CyH6vQ== dependencies: graceful-fs "^4.1.11" @@ -1717,14 +1754,14 @@ readdirp@^2.2.1: rechoir@^0.6.2: version "0.6.2" - resolved "https://registry.yarnpkg.com/rechoir/-/rechoir-0.6.2.tgz#85204b54dba82d5742e28c96756ef43af50e3384" + resolved "https://registry.yarnpkg.com/rechoir/-/rechoir-0.6.2.tgz" integrity sha1-hSBLVNuoLVdC4oyWdW70OvUOM4Q= dependencies: resolve "^1.1.6" regex-not@^1.0.0, regex-not@^1.0.2: version "1.0.2" - resolved "https://registry.yarnpkg.com/regex-not/-/regex-not-1.0.2.tgz#1f4ece27e00b0b65e0247a6810e6a85d83a5752c" + resolved "https://registry.yarnpkg.com/regex-not/-/regex-not-1.0.2.tgz" integrity sha512-J6SDjUgDxQj5NusnOtdFxDwN/+HWykR8GELwctJ7mdqhcyy1xEc4SRFHUXvxTp661YaVKAjfRLZ9cCqS6tn32A== dependencies: extend-shallow "^3.0.2" @@ -1732,7 +1769,7 @@ regex-not@^1.0.0, regex-not@^1.0.2: remove-bom-buffer@^3.0.0: version "3.0.0" - resolved "https://registry.yarnpkg.com/remove-bom-buffer/-/remove-bom-buffer-3.0.0.tgz#c2bf1e377520d324f623892e33c10cac2c252b53" + resolved "https://registry.yarnpkg.com/remove-bom-buffer/-/remove-bom-buffer-3.0.0.tgz" integrity sha512-8v2rWhaakv18qcvNeli2mZ/TMTL2nEyAKRvzo1WtnZBl15SHyEhrCu2/xKlJyUFKHiHgfXIyuY6g2dObJJycXQ== dependencies: is-buffer "^1.1.5" @@ -1740,7 +1777,7 @@ remove-bom-buffer@^3.0.0: remove-bom-stream@^1.2.0: version "1.2.0" - resolved "https://registry.yarnpkg.com/remove-bom-stream/-/remove-bom-stream-1.2.0.tgz#05f1a593f16e42e1fb90ebf59de8e569525f9523" + resolved "https://registry.yarnpkg.com/remove-bom-stream/-/remove-bom-stream-1.2.0.tgz" integrity sha1-BfGlk/FuQuH7kOv1nejlaVJflSM= dependencies: remove-bom-buffer "^3.0.0" @@ -1749,27 +1786,27 @@ remove-bom-stream@^1.2.0: remove-trailing-separator@^1.0.1, remove-trailing-separator@^1.1.0: version "1.1.0" - resolved "https://registry.yarnpkg.com/remove-trailing-separator/-/remove-trailing-separator-1.1.0.tgz#c24bce2a283adad5bc3f58e0d48249b92379d8ef" + resolved "https://registry.yarnpkg.com/remove-trailing-separator/-/remove-trailing-separator-1.1.0.tgz" integrity sha1-wkvOKig62tW8P1jg1IJJuSN52O8= repeat-element@^1.1.2: version "1.1.3" - resolved "https://registry.yarnpkg.com/repeat-element/-/repeat-element-1.1.3.tgz#782e0d825c0c5a3bb39731f84efee6b742e6b1ce" + resolved "https://registry.yarnpkg.com/repeat-element/-/repeat-element-1.1.3.tgz" integrity sha512-ahGq0ZnV5m5XtZLMb+vP76kcAM5nkLqk0lpqAuojSKGgQtn4eRi4ZZGm2olo2zKFH+sMsWaqOCW1dqAnOru72g== repeat-string@^1.6.1: version "1.6.1" - resolved "https://registry.yarnpkg.com/repeat-string/-/repeat-string-1.6.1.tgz#8dcae470e1c88abc2d600fff4a776286da75e637" + resolved "https://registry.yarnpkg.com/repeat-string/-/repeat-string-1.6.1.tgz" integrity sha1-jcrkcOHIirwtYA//Sndihtp15jc= replace-ext@^1.0.0: version "1.0.1" - resolved "https://registry.yarnpkg.com/replace-ext/-/replace-ext-1.0.1.tgz#2d6d996d04a15855d967443631dd5f77825b016a" + resolved "https://registry.yarnpkg.com/replace-ext/-/replace-ext-1.0.1.tgz" integrity sha512-yD5BHCe7quCgBph4rMQ+0KkIRKwWCrHDOX1p1Gp6HwjPM5kVoCdKGNhN7ydqqsX6lJEnQDKZ/tFMiEdQ1dvPEw== replace-homedir@^1.0.0: version "1.0.0" - resolved "https://registry.yarnpkg.com/replace-homedir/-/replace-homedir-1.0.0.tgz#e87f6d513b928dde808260c12be7fec6ff6e798c" + resolved "https://registry.yarnpkg.com/replace-homedir/-/replace-homedir-1.0.0.tgz" integrity sha1-6H9tUTuSjd6AgmDBK+f+xv9ueYw= dependencies: homedir-polyfill "^1.0.1" @@ -1778,17 +1815,17 @@ replace-homedir@^1.0.0: require-directory@^2.1.1: version "2.1.1" - resolved "https://registry.yarnpkg.com/require-directory/-/require-directory-2.1.1.tgz#8c64ad5fd30dab1c976e2344ffe7f792a6a6df42" + resolved "https://registry.yarnpkg.com/require-directory/-/require-directory-2.1.1.tgz" integrity sha1-jGStX9MNqxyXbiNE/+f3kqam30I= require-main-filename@^1.0.1: version "1.0.1" - resolved "https://registry.yarnpkg.com/require-main-filename/-/require-main-filename-1.0.1.tgz#97f717b69d48784f5f526a6c5aa8ffdda055a4d1" + resolved "https://registry.yarnpkg.com/require-main-filename/-/require-main-filename-1.0.1.tgz" integrity sha1-l/cXtp1IeE9fUmpsWqj/3aBVpNE= resolve-dir@^1.0.0, resolve-dir@^1.0.1: version "1.0.1" - resolved "https://registry.yarnpkg.com/resolve-dir/-/resolve-dir-1.0.1.tgz#79a40644c362be82f26effe739c9bb5382046f43" + resolved "https://registry.yarnpkg.com/resolve-dir/-/resolve-dir-1.0.1.tgz" integrity sha1-eaQGRMNivoLybv/nOcm7U4IEb0M= dependencies: expand-tilde "^2.0.0" @@ -1796,65 +1833,66 @@ resolve-dir@^1.0.0, resolve-dir@^1.0.1: resolve-options@^1.1.0: version "1.1.0" - resolved "https://registry.yarnpkg.com/resolve-options/-/resolve-options-1.1.0.tgz#32bb9e39c06d67338dc9378c0d6d6074566ad131" + resolved "https://registry.yarnpkg.com/resolve-options/-/resolve-options-1.1.0.tgz" integrity sha1-MrueOcBtZzONyTeMDW1gdFZq0TE= dependencies: value-or-function "^3.0.0" resolve-url@^0.2.1: version "0.2.1" - resolved "https://registry.yarnpkg.com/resolve-url/-/resolve-url-0.2.1.tgz#2c637fe77c893afd2a663fe21aa9080068e2052a" + resolved "https://registry.yarnpkg.com/resolve-url/-/resolve-url-0.2.1.tgz" integrity sha1-LGN/53yJOv0qZj/iGqkIAGjiBSo= resolve@^1.1.6, resolve@^1.1.7, resolve@^1.10.0, resolve@^1.4.0: - version "1.17.0" - resolved "https://registry.yarnpkg.com/resolve/-/resolve-1.17.0.tgz#b25941b54968231cc2d1bb76a79cb7f2c0bf8444" - integrity sha512-ic+7JYiV8Vi2yzQGFWOkiZD5Z9z7O2Zhm9XMaTxdJExKasieFCr+yXZ/WmXsckHiKl12ar0y6XiXDx3m4RHn1w== + version "1.19.0" + resolved "https://registry.yarnpkg.com/resolve/-/resolve-1.19.0.tgz" + integrity sha512-rArEXAgsBG4UgRGcynxWIWKFvh/XZCcS8UJdHhwy91zwAvCZIbcs+vAbflgBnNjYMs/i/i+/Ux6IZhML1yPvxg== dependencies: + is-core-module "^2.1.0" path-parse "^1.0.6" ret@~0.1.10: version "0.1.15" - resolved "https://registry.yarnpkg.com/ret/-/ret-0.1.15.tgz#b8a4825d5bdb1fc3f6f53c2bc33f81388681c7bc" + resolved "https://registry.yarnpkg.com/ret/-/ret-0.1.15.tgz" integrity sha512-TTlYpa+OL+vMMNG24xSlQGEJ3B/RzEfUlLct7b5G/ytav+wPrplCpVMFuwzXbkecJrb6IYo1iFb0S9v37754mg== safe-buffer@^5.1.0, safe-buffer@~5.2.0: version "5.2.1" - resolved "https://registry.yarnpkg.com/safe-buffer/-/safe-buffer-5.2.1.tgz#1eaf9fa9bdb1fdd4ec75f58f9cdb4e6b7827eec6" + resolved "https://registry.yarnpkg.com/safe-buffer/-/safe-buffer-5.2.1.tgz" integrity sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ== safe-buffer@~5.1.0, safe-buffer@~5.1.1: version "5.1.2" - resolved "https://registry.yarnpkg.com/safe-buffer/-/safe-buffer-5.1.2.tgz#991ec69d296e0313747d59bdfd2b745c35f8828d" + resolved "https://registry.yarnpkg.com/safe-buffer/-/safe-buffer-5.1.2.tgz" integrity sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g== safe-regex@^1.1.0: version "1.1.0" - resolved "https://registry.yarnpkg.com/safe-regex/-/safe-regex-1.1.0.tgz#40a3669f3b077d1e943d44629e157dd48023bf2e" + resolved "https://registry.yarnpkg.com/safe-regex/-/safe-regex-1.1.0.tgz" integrity sha1-QKNmnzsHfR6UPURinhV91IAjvy4= dependencies: ret "~0.1.10" semver-greatest-satisfied-range@^1.1.0: version "1.1.0" - resolved "https://registry.yarnpkg.com/semver-greatest-satisfied-range/-/semver-greatest-satisfied-range-1.1.0.tgz#13e8c2658ab9691cb0cd71093240280d36f77a5b" + resolved "https://registry.yarnpkg.com/semver-greatest-satisfied-range/-/semver-greatest-satisfied-range-1.1.0.tgz" integrity sha1-E+jCZYq5aRywzXEJMkAoDTb3els= dependencies: sver-compat "^1.5.0" "semver@2 || 3 || 4 || 5": version "5.7.1" - resolved "https://registry.yarnpkg.com/semver/-/semver-5.7.1.tgz#a954f931aeba508d307bbf069eff0c01c96116f7" + resolved "https://registry.yarnpkg.com/semver/-/semver-5.7.1.tgz" integrity sha512-sauaDf/PZdVgrLTNYHRtpXa1iRiKcaebiKQ1BJdpQlWH2lCvexQdX55snPFyK7QzpudqbCI0qXFfOasHdyNDGQ== set-blocking@^2.0.0: version "2.0.0" - resolved "https://registry.yarnpkg.com/set-blocking/-/set-blocking-2.0.0.tgz#045f9782d011ae9a6803ddd382b24392b3d890f7" + resolved "https://registry.yarnpkg.com/set-blocking/-/set-blocking-2.0.0.tgz" integrity sha1-BF+XgtARrppoA93TgrJDkrPYkPc= set-value@^2.0.0, set-value@^2.0.1: version "2.0.1" - resolved "https://registry.yarnpkg.com/set-value/-/set-value-2.0.1.tgz#a18d40530e6f07de4228c7defe4227af8cad005b" + resolved "https://registry.yarnpkg.com/set-value/-/set-value-2.0.1.tgz" integrity sha512-JxHc1weCN68wRY0fhCoXpyK55m/XPHafOmK4UWD7m2CI14GMcFypt4w/0+NV5f/ZMby2F6S2wwA7fgynh9gWSw== dependencies: extend-shallow "^2.0.1" @@ -1864,7 +1902,7 @@ set-value@^2.0.0, set-value@^2.0.1: snapdragon-node@^2.0.1: version "2.1.1" - resolved "https://registry.yarnpkg.com/snapdragon-node/-/snapdragon-node-2.1.1.tgz#6c175f86ff14bdb0724563e8f3c1b021a286853b" + resolved "https://registry.yarnpkg.com/snapdragon-node/-/snapdragon-node-2.1.1.tgz" integrity sha512-O27l4xaMYt/RSQ5TR3vpWCAB5Kb/czIcqUFOM/C4fYcLnbZUc1PkjTAMjof2pBWaSTwOUd6qUHcFGVGj7aIwnw== dependencies: define-property "^1.0.0" @@ -1873,14 +1911,14 @@ snapdragon-node@^2.0.1: snapdragon-util@^3.0.1: version "3.0.1" - resolved "https://registry.yarnpkg.com/snapdragon-util/-/snapdragon-util-3.0.1.tgz#f956479486f2acd79700693f6f7b805e45ab56e2" + resolved "https://registry.yarnpkg.com/snapdragon-util/-/snapdragon-util-3.0.1.tgz" integrity sha512-mbKkMdQKsjX4BAL4bRYTj21edOf8cN7XHdYUJEe+Zn99hVEYcMvKPct1IqNe7+AZPirn8BCDOQBHQZknqmKlZQ== dependencies: kind-of "^3.2.0" snapdragon@^0.8.1: version "0.8.2" - resolved "https://registry.yarnpkg.com/snapdragon/-/snapdragon-0.8.2.tgz#64922e7c565b0e14204ba1aa7d6964278d25182d" + resolved "https://registry.yarnpkg.com/snapdragon/-/snapdragon-0.8.2.tgz" integrity sha512-FtyOnWN/wCHTVXOMwvSv26d+ko5vWlIDD6zoUJ7LW8vh+ZBC8QdljveRP+crNrtBwioEUWy/4dMtbBjA4ioNlg== dependencies: base "^0.11.1" @@ -1894,7 +1932,7 @@ snapdragon@^0.8.1: source-map-resolve@^0.5.0: version "0.5.3" - resolved "https://registry.yarnpkg.com/source-map-resolve/-/source-map-resolve-0.5.3.tgz#190866bece7553e1f8f267a2ee82c606b5509a1a" + resolved "https://registry.yarnpkg.com/source-map-resolve/-/source-map-resolve-0.5.3.tgz" integrity sha512-Htz+RnsXWk5+P2slx5Jh3Q66vhQj1Cllm0zvnaY98+NFx+Dv2CF/f5O/t8x+KaNdrdIAsruNzoh/KpialbqAnw== dependencies: atob "^2.1.2" @@ -1905,27 +1943,27 @@ source-map-resolve@^0.5.0: source-map-url@^0.4.0: version "0.4.0" - resolved "https://registry.yarnpkg.com/source-map-url/-/source-map-url-0.4.0.tgz#3e935d7ddd73631b97659956d55128e87b5084a3" + resolved "https://registry.yarnpkg.com/source-map-url/-/source-map-url-0.4.0.tgz" integrity sha1-PpNdfd1zYxuXZZlW1VEo6HtQhKM= source-map@^0.5.6: version "0.5.7" - resolved "https://registry.yarnpkg.com/source-map/-/source-map-0.5.7.tgz#8a039d2d1021d22d1ea14c80d8ea468ba2ef3fcc" + resolved "https://registry.yarnpkg.com/source-map/-/source-map-0.5.7.tgz" integrity sha1-igOdLRAh0i0eoUyA2OpGi6LvP8w= source-map@^0.6.1: version "0.6.1" - resolved "https://registry.yarnpkg.com/source-map/-/source-map-0.6.1.tgz#74722af32e9614e9c287a8d0bbde48b5e2f1a263" + resolved "https://registry.yarnpkg.com/source-map/-/source-map-0.6.1.tgz" integrity sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g== sparkles@^1.0.0: version "1.0.1" - resolved "https://registry.yarnpkg.com/sparkles/-/sparkles-1.0.1.tgz#008db65edce6c50eec0c5e228e1945061dd0437c" + resolved "https://registry.yarnpkg.com/sparkles/-/sparkles-1.0.1.tgz" integrity sha512-dSO0DDYUahUt/0/pD/Is3VIm5TGJjludZ0HVymmhYF6eNA53PVLhnUk0znSYbH8IYBuJdCE+1luR22jNLMaQdw== spdx-correct@^3.0.0: version "3.1.1" - resolved "https://registry.yarnpkg.com/spdx-correct/-/spdx-correct-3.1.1.tgz#dece81ac9c1e6713e5f7d1b6f17d468fa53d89a9" + resolved "https://registry.yarnpkg.com/spdx-correct/-/spdx-correct-3.1.1.tgz" integrity sha512-cOYcUWwhCuHCXi49RhFRCyJEK3iPj1Ziz9DpViV3tbZOwXD49QzIN3MpOLJNxh2qwq2lJJZaKMVw9qNi4jTC0w== dependencies: spdx-expression-parse "^3.0.0" @@ -1933,42 +1971,42 @@ spdx-correct@^3.0.0: spdx-exceptions@^2.1.0: version "2.3.0" - resolved "https://registry.yarnpkg.com/spdx-exceptions/-/spdx-exceptions-2.3.0.tgz#3f28ce1a77a00372683eade4a433183527a2163d" + resolved "https://registry.yarnpkg.com/spdx-exceptions/-/spdx-exceptions-2.3.0.tgz" integrity sha512-/tTrYOC7PPI1nUAgx34hUpqXuyJG+DTHJTnIULG4rDygi4xu/tfgmq1e1cIRwRzwZgo4NLySi+ricLkZkw4i5A== spdx-expression-parse@^3.0.0: version "3.0.1" - resolved "https://registry.yarnpkg.com/spdx-expression-parse/-/spdx-expression-parse-3.0.1.tgz#cf70f50482eefdc98e3ce0a6833e4a53ceeba679" + resolved "https://registry.yarnpkg.com/spdx-expression-parse/-/spdx-expression-parse-3.0.1.tgz" integrity sha512-cbqHunsQWnJNE6KhVSMsMeH5H/L9EpymbzqTQ3uLwNCLZ1Q481oWaofqH7nO6V07xlXwY6PhQdQ2IedWx/ZK4Q== dependencies: spdx-exceptions "^2.1.0" spdx-license-ids "^3.0.0" spdx-license-ids@^3.0.0: - version "3.0.5" - resolved "https://registry.yarnpkg.com/spdx-license-ids/-/spdx-license-ids-3.0.5.tgz#3694b5804567a458d3c8045842a6358632f62654" - integrity sha512-J+FWzZoynJEXGphVIS+XEh3kFSjZX/1i9gFBaWQcB+/tmpe2qUsSBABpcxqxnAxFdiUFEgAX1bjYGQvIZmoz9Q== + version "3.0.6" + resolved "https://registry.yarnpkg.com/spdx-license-ids/-/spdx-license-ids-3.0.6.tgz" + integrity sha512-+orQK83kyMva3WyPf59k1+Y525csj5JejicWut55zeTWANuN17qSiSLUXWtzHeNWORSvT7GLDJ/E/XiIWoXBTw== split-string@^3.0.1, split-string@^3.0.2: version "3.1.0" - resolved "https://registry.yarnpkg.com/split-string/-/split-string-3.1.0.tgz#7cb09dda3a86585705c64b39a6466038682e8fe2" + resolved "https://registry.yarnpkg.com/split-string/-/split-string-3.1.0.tgz" integrity sha512-NzNVhJDYpwceVVii8/Hu6DKfD2G+NrQHlS/V/qgv763EYudVwEcMQNxd2lh+0VrUByXN/oJkl5grOhYWvQUYiw== dependencies: extend-shallow "^3.0.0" sprintf-js@~1.0.2: version "1.0.3" - resolved "https://registry.yarnpkg.com/sprintf-js/-/sprintf-js-1.0.3.tgz#04e6926f662895354f3dd015203633b857297e2c" + resolved "https://registry.yarnpkg.com/sprintf-js/-/sprintf-js-1.0.3.tgz" integrity sha1-BOaSb2YolTVPPdAVIDYzuFcpfiw= stack-trace@0.0.10: version "0.0.10" - resolved "https://registry.yarnpkg.com/stack-trace/-/stack-trace-0.0.10.tgz#547c70b347e8d32b4e108ea1a2a159e5fdde19c0" + resolved "https://registry.yarnpkg.com/stack-trace/-/stack-trace-0.0.10.tgz" integrity sha1-VHxws0fo0ytOEI6hoqFZ5f3eGcA= static-extend@^0.1.1: version "0.1.2" - resolved "https://registry.yarnpkg.com/static-extend/-/static-extend-0.1.2.tgz#60809c39cbff55337226fd5e0b520f341f1fb5c6" + resolved "https://registry.yarnpkg.com/static-extend/-/static-extend-0.1.2.tgz" integrity sha1-YICcOcv/VTNyJv1eC1IPNB8ftcY= dependencies: define-property "^0.2.5" @@ -1976,17 +2014,17 @@ static-extend@^0.1.1: stream-exhaust@^1.0.1: version "1.0.2" - resolved "https://registry.yarnpkg.com/stream-exhaust/-/stream-exhaust-1.0.2.tgz#acdac8da59ef2bc1e17a2c0ccf6c320d120e555d" + resolved "https://registry.yarnpkg.com/stream-exhaust/-/stream-exhaust-1.0.2.tgz" integrity sha512-b/qaq/GlBK5xaq1yrK9/zFcyRSTNxmcZwFLGSTG0mXgZl/4Z6GgiyYOXOvY7N3eEvFRAG1bkDRz5EPGSvPYQlw== stream-shift@^1.0.0: version "1.0.1" - resolved "https://registry.yarnpkg.com/stream-shift/-/stream-shift-1.0.1.tgz#d7088281559ab2778424279b0877da3c392d5a3d" + resolved "https://registry.yarnpkg.com/stream-shift/-/stream-shift-1.0.1.tgz" integrity sha512-AiisoFqQ0vbGcZgQPY1cdP2I76glaVA/RauYR4G4thNFgkTqr90yXTo4LYX60Jl+sIlPNHHdGSwo01AvbKUSVQ== string-width@^1.0.1, string-width@^1.0.2: version "1.0.2" - resolved "https://registry.yarnpkg.com/string-width/-/string-width-1.0.2.tgz#118bdf5b8cdc51a2a7e70d211e07e2b0b9b107d3" + resolved "https://registry.yarnpkg.com/string-width/-/string-width-1.0.2.tgz" integrity sha1-EYvfW4zcUaKn5w0hHgfisLmxB9M= dependencies: code-point-at "^1.0.0" @@ -1995,21 +2033,21 @@ string-width@^1.0.1, string-width@^1.0.2: string_decoder@^1.1.1: version "1.3.0" - resolved "https://registry.yarnpkg.com/string_decoder/-/string_decoder-1.3.0.tgz#42f114594a46cf1a8e30b0a84f56c78c3edac21e" + resolved "https://registry.yarnpkg.com/string_decoder/-/string_decoder-1.3.0.tgz" integrity sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA== dependencies: safe-buffer "~5.2.0" string_decoder@~1.1.1: version "1.1.1" - resolved "https://registry.yarnpkg.com/string_decoder/-/string_decoder-1.1.1.tgz#9cf1611ba62685d7030ae9e4ba34149c3af03fc8" + resolved "https://registry.yarnpkg.com/string_decoder/-/string_decoder-1.1.1.tgz" integrity sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg== dependencies: safe-buffer "~5.1.0" stringify-object@^3.0.0: version "3.3.0" - resolved "https://registry.yarnpkg.com/stringify-object/-/stringify-object-3.3.0.tgz#703065aefca19300d3ce88af4f5b3956d7556629" + resolved "https://registry.yarnpkg.com/stringify-object/-/stringify-object-3.3.0.tgz" integrity sha512-rHqiFh1elqCQ9WPLIC8I0Q/g/wj5J1eMkyoiD6eoQApWHP0FtlK7rqnhmabL5VUY9JQCcqwwvlOaSuutekgyrw== dependencies: get-own-enumerable-property-symbols "^3.0.0" @@ -2018,28 +2056,28 @@ stringify-object@^3.0.0: strip-ansi@^3.0.0, strip-ansi@^3.0.1: version "3.0.1" - resolved "https://registry.yarnpkg.com/strip-ansi/-/strip-ansi-3.0.1.tgz#6a385fb8853d952d5ff05d0e8aaf94278dc63dcf" + resolved "https://registry.yarnpkg.com/strip-ansi/-/strip-ansi-3.0.1.tgz" integrity sha1-ajhfuIU9lS1f8F0Oiq+UJ43GPc8= dependencies: ansi-regex "^2.0.0" strip-bom@^2.0.0: version "2.0.0" - resolved "https://registry.yarnpkg.com/strip-bom/-/strip-bom-2.0.0.tgz#6219a85616520491f35788bdbf1447a99c7e6b0e" + resolved "https://registry.yarnpkg.com/strip-bom/-/strip-bom-2.0.0.tgz" integrity sha1-YhmoVhZSBJHzV4i9vxRHqZx+aw4= dependencies: is-utf8 "^0.2.0" supports-color@^5.3.0: version "5.5.0" - resolved "https://registry.yarnpkg.com/supports-color/-/supports-color-5.5.0.tgz#e2e69a44ac8772f78a1ec0b35b689df6530efc8f" + resolved "https://registry.yarnpkg.com/supports-color/-/supports-color-5.5.0.tgz" integrity sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow== dependencies: has-flag "^3.0.0" sver-compat@^1.5.0: version "1.5.0" - resolved "https://registry.yarnpkg.com/sver-compat/-/sver-compat-1.5.0.tgz#3cf87dfeb4d07b4a3f14827bc186b3fd0c645cd8" + resolved "https://registry.yarnpkg.com/sver-compat/-/sver-compat-1.5.0.tgz" integrity sha1-PPh9/rTQe0o/FIJ7wYaz/QxkXNg= dependencies: es6-iterator "^2.0.1" @@ -2047,7 +2085,7 @@ sver-compat@^1.5.0: through2-filter@^3.0.0: version "3.0.0" - resolved "https://registry.yarnpkg.com/through2-filter/-/through2-filter-3.0.0.tgz#700e786df2367c2c88cd8aa5be4cf9c1e7831254" + resolved "https://registry.yarnpkg.com/through2-filter/-/through2-filter-3.0.0.tgz" integrity sha512-jaRjI2WxN3W1V8/FMZ9HKIBXixtiqs3SQSX4/YGIiP3gL6djW48VoZq9tDqeCWs3MT8YY5wb/zli8VW8snY1CA== dependencies: through2 "~2.0.0" @@ -2055,7 +2093,7 @@ through2-filter@^3.0.0: through2@^2.0.0, through2@^2.0.3, through2@~2.0.0: version "2.0.5" - resolved "https://registry.yarnpkg.com/through2/-/through2-2.0.5.tgz#01c1e39eb31d07cb7d03a96a70823260b23132cd" + resolved "https://registry.yarnpkg.com/through2/-/through2-2.0.5.tgz" integrity sha512-/mrRod8xqpA+IHSLyGCQ2s8SPHiCDEeQJSep1jqLYeEUClOFG2Qsh+4FU6G9VeqpZnGW/Su8LQGc4YKni5rYSQ== dependencies: readable-stream "~2.3.6" @@ -2063,26 +2101,26 @@ through2@^2.0.0, through2@^2.0.3, through2@~2.0.0: through2@^4.0.2: version "4.0.2" - resolved "https://registry.yarnpkg.com/through2/-/through2-4.0.2.tgz#a7ce3ac2a7a8b0b966c80e7c49f0484c3b239764" + resolved "https://registry.yarnpkg.com/through2/-/through2-4.0.2.tgz" integrity sha512-iOqSav00cVxEEICeD7TjLB1sueEL+81Wpzp2bY17uZjZN0pWZPuo4suZ/61VujxmqSGFfgOcNuTZ85QJwNZQpw== dependencies: readable-stream "3" tildify@^1.1.2: version "1.2.0" - resolved "https://registry.yarnpkg.com/tildify/-/tildify-1.2.0.tgz#dcec03f55dca9b7aa3e5b04f21817eb56e63588a" + resolved "https://registry.yarnpkg.com/tildify/-/tildify-1.2.0.tgz" integrity sha1-3OwD9V3Km3qj5bBPIYF+tW5jWIo= dependencies: os-homedir "^1.0.0" time-stamp@^1.0.0: version "1.1.0" - resolved "https://registry.yarnpkg.com/time-stamp/-/time-stamp-1.1.0.tgz#764a5a11af50561921b133f3b44e618687e0f5c3" + resolved "https://registry.yarnpkg.com/time-stamp/-/time-stamp-1.1.0.tgz" integrity sha1-dkpaEa9QVhkhsTPztE5hhofg9cM= to-absolute-glob@^2.0.0: version "2.0.2" - resolved "https://registry.yarnpkg.com/to-absolute-glob/-/to-absolute-glob-2.0.2.tgz#1865f43d9e74b0822db9f145b78cff7d0f7c849b" + resolved "https://registry.yarnpkg.com/to-absolute-glob/-/to-absolute-glob-2.0.2.tgz" integrity sha1-GGX0PZ50sIItufFFt4z/fQ98hJs= dependencies: is-absolute "^1.0.0" @@ -2090,14 +2128,14 @@ to-absolute-glob@^2.0.0: to-object-path@^0.3.0: version "0.3.0" - resolved "https://registry.yarnpkg.com/to-object-path/-/to-object-path-0.3.0.tgz#297588b7b0e7e0ac08e04e672f85c1f4999e17af" + resolved "https://registry.yarnpkg.com/to-object-path/-/to-object-path-0.3.0.tgz" integrity sha1-KXWIt7Dn4KwI4E5nL4XB9JmeF68= dependencies: kind-of "^3.0.2" to-regex-range@^2.1.0: version "2.1.1" - resolved "https://registry.yarnpkg.com/to-regex-range/-/to-regex-range-2.1.1.tgz#7c80c17b9dfebe599e27367e0d4dd5590141db38" + resolved "https://registry.yarnpkg.com/to-regex-range/-/to-regex-range-2.1.1.tgz" integrity sha1-fIDBe53+vlmeJzZ+DU3VWQFB2zg= dependencies: is-number "^3.0.0" @@ -2105,7 +2143,7 @@ to-regex-range@^2.1.0: to-regex@^3.0.1, to-regex@^3.0.2: version "3.0.2" - resolved "https://registry.yarnpkg.com/to-regex/-/to-regex-3.0.2.tgz#13cfdd9b336552f30b51f33a8ae1b42a7a7599ce" + resolved "https://registry.yarnpkg.com/to-regex/-/to-regex-3.0.2.tgz" integrity sha512-FWtleNAtZ/Ki2qtqej2CXTOayOH9bHDQF+Q48VpWyDXjbYxA4Yz8iDB31zXOBUlOHHKidDbqGVrTUvQMPmBGBw== dependencies: define-property "^2.0.2" @@ -2115,51 +2153,52 @@ to-regex@^3.0.1, to-regex@^3.0.2: to-through@^2.0.0: version "2.0.0" - resolved "https://registry.yarnpkg.com/to-through/-/to-through-2.0.0.tgz#fc92adaba072647bc0b67d6b03664aa195093af6" + resolved "https://registry.yarnpkg.com/to-through/-/to-through-2.0.0.tgz" integrity sha1-/JKtq6ByZHvAtn1rA2ZKoZUJOvY= dependencies: through2 "^2.0.3" type@^1.0.1: version "1.2.0" - resolved "https://registry.yarnpkg.com/type/-/type-1.2.0.tgz#848dd7698dafa3e54a6c479e759c4bc3f18847a0" + resolved "https://registry.yarnpkg.com/type/-/type-1.2.0.tgz" integrity sha512-+5nt5AAniqsCnu2cEQQdpzCAh33kVx8n0VoFidKpB1dVVLAN/F+bgVOqOJqOnEnrhp222clB5p3vUlD+1QAnfg== type@^2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/type/-/type-2.0.0.tgz#5f16ff6ef2eb44f260494dae271033b29c09a9c3" - integrity sha512-KBt58xCHry4Cejnc2ISQAF7QY+ORngsWfxezO68+12hKV6lQY8P/psIkcbjeHWn7MqcgciWJyCCevFMJdIXpow== + version "2.1.0" + resolved "https://registry.yarnpkg.com/type/-/type-2.1.0.tgz" + integrity sha512-G9absDWvhAWCV2gmF1zKud3OyC61nZDwWvBL2DApaVFogI07CprggiQAOOjvp2NRjYWFzPyu7vwtDrQFq8jeSA== typedarray@^0.0.6: version "0.0.6" - resolved "https://registry.yarnpkg.com/typedarray/-/typedarray-0.0.6.tgz#867ac74e3864187b1d3d47d996a78ec5c8830777" + resolved "https://registry.yarnpkg.com/typedarray/-/typedarray-0.0.6.tgz" integrity sha1-hnrHTjhkGHsdPUfZlqeOxciDB3c= uc.micro@^1.0.1, uc.micro@^1.0.5: version "1.0.6" - resolved "https://registry.yarnpkg.com/uc.micro/-/uc.micro-1.0.6.tgz#9c411a802a409a91fc6cf74081baba34b24499ac" + resolved "https://registry.yarnpkg.com/uc.micro/-/uc.micro-1.0.6.tgz" integrity sha512-8Y75pvTYkLJW2hWQHXxoqRgV7qb9B+9vFEtidML+7koHUFapnVJAZ6cKs+Qjz5Aw3aZWHMC6u0wJE3At+nSGwA== unc-path-regex@^0.1.2: version "0.1.2" - resolved "https://registry.yarnpkg.com/unc-path-regex/-/unc-path-regex-0.1.2.tgz#e73dd3d7b0d7c5ed86fbac6b0ae7d8c6a69d50fa" + resolved "https://registry.yarnpkg.com/unc-path-regex/-/unc-path-regex-0.1.2.tgz" integrity sha1-5z3T17DXxe2G+6xrCufYxqadUPo= undertaker-registry@^1.0.0: version "1.0.1" - resolved "https://registry.yarnpkg.com/undertaker-registry/-/undertaker-registry-1.0.1.tgz#5e4bda308e4a8a2ae584f9b9a4359a499825cc50" + resolved "https://registry.yarnpkg.com/undertaker-registry/-/undertaker-registry-1.0.1.tgz" integrity sha1-XkvaMI5KiirlhPm5pDWaSZglzFA= undertaker@^1.2.1: - version "1.2.1" - resolved "https://registry.yarnpkg.com/undertaker/-/undertaker-1.2.1.tgz#701662ff8ce358715324dfd492a4f036055dfe4b" - integrity sha512-71WxIzDkgYk9ZS+spIB8iZXchFhAdEo2YU8xYqBYJ39DIUIqziK78ftm26eecoIY49X0J2MLhG4hr18Yp6/CMA== + version "1.3.0" + resolved "https://registry.yarnpkg.com/undertaker/-/undertaker-1.3.0.tgz" + integrity sha512-/RXwi5m/Mu3H6IHQGww3GNt1PNXlbeCuclF2QYR14L/2CHPz3DFZkvB5hZ0N/QUkiXWCACML2jXViIQEQc2MLg== dependencies: arr-flatten "^1.0.1" arr-map "^2.0.0" bach "^1.0.0" collection-map "^1.0.0" es6-weak-map "^2.0.1" + fast-levenshtein "^1.0.0" last-run "^1.1.0" object.defaults "^1.0.0" object.reduce "^1.0.0" @@ -2167,7 +2206,7 @@ undertaker@^1.2.1: union-value@^1.0.0: version "1.0.1" - resolved "https://registry.yarnpkg.com/union-value/-/union-value-1.0.1.tgz#0b6fe7b835aecda61c6ea4d4f02c14221e109847" + resolved "https://registry.yarnpkg.com/union-value/-/union-value-1.0.1.tgz" integrity sha512-tJfXmxMeWYnczCVs7XAEvIV7ieppALdyepWMkHkwciRpZraG/xwT+s2JN8+pr1+8jCRf80FFzvr+MpQeeoF4Xg== dependencies: arr-union "^3.1.0" @@ -2177,7 +2216,7 @@ union-value@^1.0.0: unique-stream@^2.0.2: version "2.3.1" - resolved "https://registry.yarnpkg.com/unique-stream/-/unique-stream-2.3.1.tgz#c65d110e9a4adf9a6c5948b28053d9a8d04cbeac" + resolved "https://registry.yarnpkg.com/unique-stream/-/unique-stream-2.3.1.tgz" integrity sha512-2nY4TnBE70yoxHkDli7DMazpWiP7xMdCYqU2nBRO0UB+ZpEkGsSija7MvmvnZFUeC+mrgiUfcHSr3LmRFIg4+A== dependencies: json-stable-stringify-without-jsonify "^1.0.1" @@ -2185,7 +2224,7 @@ unique-stream@^2.0.2: unset-value@^1.0.0: version "1.0.0" - resolved "https://registry.yarnpkg.com/unset-value/-/unset-value-1.0.0.tgz#8376873f7d2335179ffb1e6fc3a8ed0dfc8ab559" + resolved "https://registry.yarnpkg.com/unset-value/-/unset-value-1.0.0.tgz" integrity sha1-g3aHP30jNRef+x5vw6jtDfyKtVk= dependencies: has-value "^0.3.1" @@ -2193,34 +2232,34 @@ unset-value@^1.0.0: upath@^1.1.1: version "1.2.0" - resolved "https://registry.yarnpkg.com/upath/-/upath-1.2.0.tgz#8f66dbcd55a883acdae4408af8b035a5044c1894" + resolved "https://registry.yarnpkg.com/upath/-/upath-1.2.0.tgz" integrity sha512-aZwGpamFO61g3OlfT7OQCHqhGnW43ieH9WZeP7QxN/G/jS4jfqUkZxoryvJgVPEcrl5NL/ggHsSmLMHuH64Lhg== urix@^0.1.0: version "0.1.0" - resolved "https://registry.yarnpkg.com/urix/-/urix-0.1.0.tgz#da937f7a62e21fec1fd18d49b35c2935067a6c72" + resolved "https://registry.yarnpkg.com/urix/-/urix-0.1.0.tgz" integrity sha1-2pN/emLiH+wf0Y1Js1wpNQZ6bHI= use@^3.1.0: version "3.1.1" - resolved "https://registry.yarnpkg.com/use/-/use-3.1.1.tgz#d50c8cac79a19fbc20f2911f56eb973f4e10070f" + resolved "https://registry.yarnpkg.com/use/-/use-3.1.1.tgz" integrity sha512-cwESVXlO3url9YWlFW/TA9cshCEhtu7IKJ/p5soJ/gGpj7vbvFrAY/eIioQ6Dw23KjZhYgiIo8HOs1nQ2vr/oQ== util-deprecate@^1.0.1, util-deprecate@~1.0.1: version "1.0.2" - resolved "https://registry.yarnpkg.com/util-deprecate/-/util-deprecate-1.0.2.tgz#450d4dc9fa70de732762fbd2d4a28981419a0ccf" + resolved "https://registry.yarnpkg.com/util-deprecate/-/util-deprecate-1.0.2.tgz" integrity sha1-RQ1Nyfpw3nMnYvvS1KKJgUGaDM8= -v8flags@^3.0.1: - version "3.1.3" - resolved "https://registry.yarnpkg.com/v8flags/-/v8flags-3.1.3.tgz#fc9dc23521ca20c5433f81cc4eb9b3033bb105d8" - integrity sha512-amh9CCg3ZxkzQ48Mhcb8iX7xpAfYJgePHxWMQCBWECpOSqJUXgY26ncA61UTV0BkPqfhcy6mzwCIoP4ygxpW8w== +v8flags@^3.2.0: + version "3.2.0" + resolved "https://registry.yarnpkg.com/v8flags/-/v8flags-3.2.0.tgz" + integrity sha512-mH8etigqMfiGWdeXpaaqGfs6BndypxusHHcv2qSHyZkGEznCd/qAXCWWRzeowtL54147cktFOC4P5y+kl8d8Jg== dependencies: homedir-polyfill "^1.0.1" validate-npm-package-license@^3.0.1: version "3.0.4" - resolved "https://registry.yarnpkg.com/validate-npm-package-license/-/validate-npm-package-license-3.0.4.tgz#fc91f6b9c7ba15c857f4cb2c5defeec39d4f410a" + resolved "https://registry.yarnpkg.com/validate-npm-package-license/-/validate-npm-package-license-3.0.4.tgz" integrity sha512-DpKm2Ui/xN7/HQKCtpZxoRWBhZ9Z0kqtygG8XCgNQ8ZlDnxuQmWhj566j8fN4Cu3/JmbhsDo7fcAJq4s9h27Ew== dependencies: spdx-correct "^3.0.0" @@ -2228,12 +2267,12 @@ validate-npm-package-license@^3.0.1: value-or-function@^3.0.0: version "3.0.0" - resolved "https://registry.yarnpkg.com/value-or-function/-/value-or-function-3.0.0.tgz#1c243a50b595c1be54a754bfece8563b9ff8d813" + resolved "https://registry.yarnpkg.com/value-or-function/-/value-or-function-3.0.0.tgz" integrity sha1-HCQ6ULWVwb5Up1S/7OhWO5/42BM= vinyl-fs@^3.0.0: version "3.0.3" - resolved "https://registry.yarnpkg.com/vinyl-fs/-/vinyl-fs-3.0.3.tgz#c85849405f67428feabbbd5c5dbdd64f47d31bc7" + resolved "https://registry.yarnpkg.com/vinyl-fs/-/vinyl-fs-3.0.3.tgz" integrity sha512-vIu34EkyNyJxmP0jscNzWBSygh7VWhqun6RmqVfXePrOwi9lhvRs//dOaGOTRUQr4tx7/zd26Tk5WeSVZitgng== dependencies: fs-mkdirp-stream "^1.0.0" @@ -2256,7 +2295,7 @@ vinyl-fs@^3.0.0: vinyl-sourcemap@^1.1.0: version "1.1.0" - resolved "https://registry.yarnpkg.com/vinyl-sourcemap/-/vinyl-sourcemap-1.1.0.tgz#92a800593a38703a8cdb11d8b300ad4be63b3e16" + resolved "https://registry.yarnpkg.com/vinyl-sourcemap/-/vinyl-sourcemap-1.1.0.tgz" integrity sha1-kqgAWTo4cDqM2xHYswCtS+Y7PhY= dependencies: append-buffer "^1.0.2" @@ -2268,9 +2307,9 @@ vinyl-sourcemap@^1.1.0: vinyl "^2.0.0" vinyl@^2.0.0: - version "2.2.0" - resolved "https://registry.yarnpkg.com/vinyl/-/vinyl-2.2.0.tgz#d85b07da96e458d25b2ffe19fece9f2caa13ed86" - integrity sha512-MBH+yP0kC/GQ5GwBqrTPTzEfiiLjta7hTtvQtbxBgTeSXsmKQRQecjibMbxIXzVT3Y9KJK+drOz1/k+vsu8Nkg== + version "2.2.1" + resolved "https://registry.yarnpkg.com/vinyl/-/vinyl-2.2.1.tgz" + integrity sha512-LII3bXRFBZLlezoG5FfZVcXflZgWP/4dCwKtxd5ky9+LOtM4CS3bIRQsmR1KMnMW07jpE8fqR2lcxPZ+8sJIcw== dependencies: clone "^2.1.1" clone-buffer "^1.0.0" @@ -2281,19 +2320,19 @@ vinyl@^2.0.0: which-module@^1.0.0: version "1.0.0" - resolved "https://registry.yarnpkg.com/which-module/-/which-module-1.0.0.tgz#bba63ca861948994ff307736089e3b96026c2a4f" + resolved "https://registry.yarnpkg.com/which-module/-/which-module-1.0.0.tgz" integrity sha1-u6Y8qGGUiZT/MHc2CJ47lgJsKk8= which@^1.2.14: version "1.3.1" - resolved "https://registry.yarnpkg.com/which/-/which-1.3.1.tgz#a45043d54f5805316da8d62f9f50918d3da70b0a" + resolved "https://registry.yarnpkg.com/which/-/which-1.3.1.tgz" integrity sha512-HxJdYWq1MTIQbJ3nw0cqssHoTNU267KlrDuGZ1WYlxDStUtKUhOaJmh112/TZmHxxUfuJqPXSOm7tDyas0OSIQ== dependencies: isexe "^2.0.0" wrap-ansi@^2.0.0: version "2.1.0" - resolved "https://registry.yarnpkg.com/wrap-ansi/-/wrap-ansi-2.1.0.tgz#d8fc3d284dd05794fe84973caecdd1cf824fdd85" + resolved "https://registry.yarnpkg.com/wrap-ansi/-/wrap-ansi-2.1.0.tgz" integrity sha1-2Pw9KE3QV5T+hJc8rs3Rz4JP3YU= dependencies: string-width "^1.0.1" @@ -2301,20 +2340,20 @@ wrap-ansi@^2.0.0: wrappy@1: version "1.0.2" - resolved "https://registry.yarnpkg.com/wrappy/-/wrappy-1.0.2.tgz#b5243d8f3ec1aa35f1364605bc0d1036e30ab69f" + resolved "https://registry.yarnpkg.com/wrappy/-/wrappy-1.0.2.tgz" integrity sha1-tSQ9jz7BqjXxNkYFvA0QNuMKtp8= xtend@~4.0.0, xtend@~4.0.1: version "4.0.2" - resolved "https://registry.yarnpkg.com/xtend/-/xtend-4.0.2.tgz#bb72779f5fa465186b1f438f674fa347fdb5db54" + resolved "https://registry.yarnpkg.com/xtend/-/xtend-4.0.2.tgz" integrity sha512-LKYU1iAXJXUgAXn9URjiu+MWhyUXHsvfp7mcuYm9dSUKK0/CjtrUwFAxD82/mCWbtLsGjFIad0wIsod4zrTAEQ== -y18n@^3.2.1: - version "3.2.1" - resolved "https://registry.yarnpkg.com/y18n/-/y18n-3.2.1.tgz#6d15fba884c08679c0d77e88e7759e811e07fa41" - integrity sha1-bRX7qITAhnnA136I53WegR4H+kE= +y18n@^3.2.1, y18n@^5.0.5: + version "5.0.5" + resolved "https://registry.yarnpkg.com/y18n/-/y18n-5.0.5.tgz#8769ec08d03b1ea2df2500acef561743bbb9ab18" + integrity sha512-hsRUr4FFrvhhRH12wOdfs38Gy7k2FFzB9qgN9v3aLykRq0dRcdcpz5C9FxdS2NuhOrI/628b/KSTJ3rwHysYSg== -yargs-parser@13.1.2: +yargs-parser@5.0.0-security.0, yargs-parser@^13.1.2: version "13.1.2" resolved "https://registry.yarnpkg.com/yargs-parser/-/yargs-parser-13.1.2.tgz#130f09702ebaeef2650d54ce6e3e5706f7a4fb38" integrity sha512-3lbsNRf/j+A4QuSZfDRA7HRSfWrzO0YjqTJd5kjAq37Zep1CEgaYmrH9Q3GwPiB9cHyd1Y1UwggGhJGoxipbzg== @@ -2322,17 +2361,9 @@ yargs-parser@13.1.2: camelcase "^5.0.0" decamelize "^1.2.0" -yargs-parser@5.0.0-security.0: - version "5.0.0-security.0" - resolved "https://registry.yarnpkg.com/yargs-parser/-/yargs-parser-5.0.0-security.0.tgz#4ff7271d25f90ac15643b86076a2ab499ec9ee24" - integrity sha512-T69y4Ps64LNesYxeYGYPvfoMTt/7y1XtfpIslUeK4um+9Hu7hlGoRtaDLvdXb7+/tfq4opVa2HRY5xGip022rQ== - dependencies: - camelcase "^3.0.0" - object.assign "^4.1.0" - yargs@^7.1.0: version "7.1.1" - resolved "https://registry.yarnpkg.com/yargs/-/yargs-7.1.1.tgz#67f0ef52e228d4ee0d6311acede8850f53464df6" + resolved "https://registry.yarnpkg.com/yargs/-/yargs-7.1.1.tgz" integrity sha512-huO4Fr1f9PmiJJdll5kwoS2e4GqzGSsMT3PPMpOwoVkOK8ckqAewMTZyA6LXVQWflleb/Z8oPBEvNsMft0XE+g== dependencies: camelcase "^3.0.0" diff --git a/test/powershell/Language/Operators/ReplaceOperator.Tests.ps1 b/test/powershell/Language/Operators/ReplaceOperator.Tests.ps1 index 59d7039898a..b72779f59c4 100644 --- a/test/powershell/Language/Operators/ReplaceOperator.Tests.ps1 +++ b/test/powershell/Language/Operators/ReplaceOperator.Tests.ps1 @@ -11,6 +11,12 @@ Describe "Replace Operator" -Tags CI { $res | Should -BeExactly "image.jpg" } + It "Replace operator can convert an substitution object to string" { + $substitution = Get-Process -Id $pid + $res = "!3!" -replace "3",$substitution + $res | Should -BeExactly "!System.Diagnostics.Process (pwsh)!" + } + It "Replace operator can be case-insensitive and case-sensitive" { $res = "book" -replace "B","C" $res | Should -BeExactly "Cook" @@ -29,6 +35,18 @@ Describe "Replace Operator" -Tags CI { $res = "PowerPoint" -replace "Point" $res | Should -BeExactly "Power" } + + It "Replace operator can take an enumerable as first argument, a mandatory pattern, and an optional substitution" { + $res = "PowerPoint1","PowerPoint2" -replace "Point","Shell" + $res.Count | Should -Be 2 + $res[0] | Should -BeExactly "PowerShell1" + $res[1] | Should -BeExactly "PowerShell2" + + $res = "PowerPoint1","PowerPoint2" -replace "Point" + $res.Count | Should -Be 2 + $res[0] | Should -BeExactly "Power1" + $res[1] | Should -BeExactly "Power2" + } } Context "Replace operator substitutions" { diff --git a/test/powershell/Modules/Microsoft.PowerShell.Management/Add-Content.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Management/Add-Content.Tests.ps1 index d4bd23a6fee..6d63206b709 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Management/Add-Content.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Management/Add-Content.Tests.ps1 @@ -5,6 +5,7 @@ Describe "Add-Content cmdlet tests" -Tags "CI" { BeforeAll { $file1 = "file1.txt" Setup -File "$file1" + $streamContent = "ShouldWork" } Context "Add-Content should actually add content" { @@ -47,6 +48,29 @@ Describe "Add-Content cmdlet tests" -Tags "CI" { { Add-Content -Path . -Value "WriteContainerContentException" -ErrorAction Stop } | Should -Throw -ErrorId "WriteContainerContentException,Microsoft.PowerShell.Commands.AddContentCommand" } + Context "Add-Content should work with alternate data streams on Windows" { + BeforeAll { + if (!$isWindows) { + return + } + $ADSTestDir = "addcontentadstest" + $ADSTestFile = "addcontentads.txt" + $streamContent = "This is a test stream." + Setup -Directory "$ADSTestDir" + Setup -File "$ADSTestFile" + } + + It "Should add an alternate data stream on a directory" -Skip:(!$IsWindows) { + Add-Content -Path TestDrive:\$ADSTestDir -Stream Add-Content-Test-Stream -Value $streamContent -ErrorAction Stop + Get-Content -Path TestDrive:\$ADSTestDir -Stream Add-Content-Test-Stream | Should -BeExactly $streamContent + } + + It "Should add an alternate data stream on a file" -Skip:(!$IsWindows) { + Add-Content -Path TestDrive:\$ADSTestFile -Stream Add-Content-Test-Stream -Value $streamContent -ErrorAction Stop + Get-Content -Path TestDrive:\$ADSTestFile -Stream Add-Content-Test-Stream | Should -BeExactly $streamContent + } + } + #[BugId(BugDatabase.WindowsOutOfBandReleases, 906022)] It "should throw 'NotSupportedException' when you add-content to an unsupported provider" -Skip:($IsLinux -Or $IsMacOS) { { Add-Content -Path HKLM:\\software\\microsoft -Value "ShouldNotWorkBecausePathIsUnsupported" -ErrorAction Stop } | Should -Throw -ErrorId "NotSupported,Microsoft.PowerShell.Commands.AddContentCommand" diff --git a/test/powershell/Modules/Microsoft.PowerShell.Management/Clear-Content.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Management/Clear-Content.Tests.ps1 index e2ab56fc809..ff9d0c8f39c 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Management/Clear-Content.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Management/Clear-Content.Tests.ps1 @@ -51,6 +51,8 @@ Describe "Clear-Content cmdlet tests" -Tags "CI" { Setup -File "$file3" -Content $content2 $streamContent = "content for alternate stream" $streamName = "altStream1" + $dirName = "clearcontent" + Setup -Directory "$dirName" } Context "Clear-Content should actually clear content" { @@ -75,32 +77,50 @@ Describe "Clear-Content cmdlet tests" -Tags "CI" { $cci.SupportsShouldProcess | Should -BeTrue } - It "Alternate streams should be cleared with clear-content" -Skip:(!$IsWindows) { - # make sure that the content is correct - # this is here rather than BeforeAll because only windows can write to an alternate stream - Set-Content -Path "TestDrive:/$file3" -Stream $streamName -Value $streamContent - Get-Content -Path "TestDrive:/$file3" | Should -BeExactly $content2 - Get-Content -Path "TestDrive:/$file3" -Stream $streamName | Should -BeExactly $streamContent - Clear-Content -Path "TestDrive:/$file3" -Stream $streamName - Get-Content -Path "TestDrive:/$file3" | Should -BeExactly $content2 - Get-Content -Path "TestDrive:/$file3" -Stream $streamName | Should -BeNullOrEmpty - } + Context "Clear-Content should work with alternate data streams on Windows" { + It "Alternate streams should be cleared with Clear-Content on a file" -Skip:(!$IsWindows) { + + Set-Content -Path "TestDrive:/$file3" -Stream $streamName -Value $streamContent + Get-Content -Path "TestDrive:/$file3" -Stream $streamName | Should -BeExactly $streamContent + + Clear-Content -Path "TestDrive:/$file3" -Stream $streamName -ErrorAction Stop + + $result = Get-Item -Path "TestDrive:/$file3" -Stream $streamName + $result | Should -BeOfType System.Management.Automation.Internal.AlternateStreamData + $result.length | Should -Be 0 + } - It "the '-Stream' dynamic parameter is visible to get-command in the filesystem" -Skip:(!$IsWindows) { - try { - Push-Location -Path TestDrive: - (Get-Command Clear-Content -Stream foo).parameters.keys -eq "stream" | Should -Be "stream" + It "Alternate streams should be cleared with Clear-Content on a directory" -Skip:(!$IsWindows) { + Set-Content -Path "TestDrive:/$dirName" -Stream $streamName -Value $streamContent + + Get-Content -Path "TestDrive:/$dirName" -Stream $streamName | Should -BeExactly $streamContent + Clear-Content -Path "TestDrive:/$dirName" -Stream $streamName -ErrorAction Stop + + $result = Get-Item -Path "TestDrive:/$dirName" -Stream $streamName + $result | Should -BeOfType System.Management.Automation.Internal.AlternateStreamData + $result.length | Should -Be 0 } - finally { - Pop-Location + + It "the '-Stream' dynamic parameter is visible to get-command in the filesystem" -Skip:(!$IsWindows) { + try { + Push-Location -Path TestDrive: + (Get-Command Clear-Content -Stream foo).parameters.keys -eq "Stream" | Should -BeExactly "Stream" + } + finally { + Pop-Location + } } - } - It "the '-Stream' dynamic parameter should not be visible to get-command in the function provider" { - Push-Location -Path function: - { Get-Command Clear-Content -Stream $streamName } | - Should -Throw -ErrorId "NamedParameterNotFound,Microsoft.PowerShell.Commands.GetCommandCommand" - Pop-Location + It "the '-Stream' dynamic parameter should not be visible to get-command in the function provider" -Skip:(!$IsWindows) { + try { + Push-Location -Path function: + { Get-Command Clear-Content -Stream $streamName } | + Should -Throw -ErrorId "NamedParameterNotFound,Microsoft.PowerShell.Commands.GetCommandCommand" + } + finally { + Pop-Location + } + } } } diff --git a/test/powershell/Modules/Microsoft.PowerShell.Management/Get-Content.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Management/Get-Content.Tests.ps1 index 6c50cee5aa8..5fdc904580d 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Management/Get-Content.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Management/Get-Content.Tests.ps1 @@ -221,25 +221,27 @@ Describe "Get-Content" -Tags "CI" { $expected = 'He', 'o,', '', 'Wor', "d${nl}He", 'o2,', '', 'Wor', "d2${nl}" for ($i = 0; $i -lt $result.Length ; $i++) { $result[$i] | Should -BeExactly $expected[$i]} } + + Context "Alternate Data Stream support on Windows" { + It "Should support NTFS streams using colon syntax" -Skip:(!$IsWindows) { + Set-Content "${testPath}:Stream" -Value "Foo" + { Test-Path "${testPath}:Stream" | Should -Throw -ErrorId "ItemExistsNotSupportedError,Microsoft.PowerShell.Commands,TestPathCommand" } + Get-Content "${testPath}:Stream" | Should -BeExactly "Foo" + Get-Content $testPath | Should -BeExactly $testString + } - It "Should support NTFS streams using colon syntax" -Skip:(!$IsWindows) { - Set-Content "${testPath}:Stream" -Value "Foo" - { Test-Path "${testPath}:Stream" | Should -Throw -ErrorId "ItemExistsNotSupportedError,Microsoft.PowerShell.Commands,TestPathCommand" } - Get-Content "${testPath}:Stream" | Should -BeExactly "Foo" - Get-Content $testPath | Should -BeExactly $testString - } - - It "Should support NTFS streams using -Stream" -Skip:(!$IsWindows) { - Set-Content -Path $testPath -Stream hello -Value World - Get-Content -Path $testPath | Should -BeExactly $testString - Get-Content -Path $testPath -Stream hello | Should -BeExactly "World" - $item = Get-Item -Path $testPath -Stream hello - $item | Should -BeOfType System.Management.Automation.Internal.AlternateStreamData - $item.Stream | Should -BeExactly "hello" - Clear-Content -Path $testPath -Stream hello - Get-Content -Path $testPath -Stream hello | Should -BeNullOrEmpty - Remove-Item -Path $testPath -Stream hello - { Get-Content -Path $testPath -Stream hello | Should -Throw -ErrorId "GetContentReaderFileNotFoundError,Microsoft.PowerShell.Commands.GetContentCommand" } + It "Should support NTFS streams using -Stream" -Skip:(!$IsWindows) { + Set-Content -Path $testPath -Stream hello -Value World + Get-Content -Path $testPath | Should -BeExactly $testString + Get-Content -Path $testPath -Stream hello | Should -BeExactly "World" + $item = Get-Item -Path $testPath -Stream hello + $item | Should -BeOfType System.Management.Automation.Internal.AlternateStreamData + $item.Stream | Should -BeExactly "hello" + Clear-Content -Path $testPath -Stream hello + Get-Content -Path $testPath -Stream hello | Should -BeNullOrEmpty + Remove-Item -Path $testPath -Stream hello + { Get-Content -Path $testPath -Stream hello -ErrorAction stop} | Should -Throw -ErrorId "GetContentReaderFileNotFoundError,Microsoft.PowerShell.Commands.GetContentCommand" + } } It "Should support colons in filename on Linux/Mac" -Skip:($IsWindows) { diff --git a/test/powershell/Modules/Microsoft.PowerShell.Management/Get-Item.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Management/Get-Item.Tests.ps1 index 86b831ba8d0..c04412e91b4 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Management/Get-Item.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Management/Get-Item.Tests.ps1 @@ -112,16 +112,38 @@ Describe "Get-Item" -Tags "CI" { return } $altStreamPath = "$TESTDRIVE/altStream.txt" + $altStreamDirectory = "$TESTDRIVE/altstreamdir" + $noAltStreamDirectory = "$TESTDRIVE/noaltstreamdir" $stringData = "test data" $streamName = "test" - $item = New-Item -type file $altStreamPath + $absentStreamName = "noExist" + $null = New-Item -type file $altStreamPath Set-Content -Path $altStreamPath -Stream $streamName -Value $stringData + $null = New-Item -type directory $altStreamDirectory + Set-Content -Path $altStreamDirectory -Stream $streamName -Value $stringData + $null = New-Item -type directory $noAltStreamDirectory } - It "Should find an alternate stream if present" -Skip:$skipNotWindows { + It "Should find an alternate stream on a file if present" -Skip:$skipNotWindows { $result = Get-Item $altStreamPath -Stream $streamName $result.Length | Should -Be ($stringData.Length + [Environment]::NewLine.Length) $result.Stream | Should -Be $streamName } + It "Should error if it cannot find alternate stream on an existing file" -Skip:$skipNotWindows { + { Get-Item $altStreamPath -Stream $absentStreamName -ErrorAction Stop } | Should -Throw -ErrorId "AlternateDataStreamNotFound,Microsoft.PowerShell.Commands.GetItemCommand" + } + It "Should find an alternate stream on a directory if present, and it should not be a container" -Skip:$skipNotWindows { + $result = Get-Item $altStreamDirectory -Stream $streamName + $result.Length | Should -Be ($stringData.Length + [Environment]::NewLine.Length ) + $result.Stream | Should -Be $streamName + $result.PSIsContainer | Should -BeExactly $false + } + It "Should not find an alternate stream on a directory if not present" -Skip:$skipNotWindows { + { Get-Item $noAltStreamDirectory -Stream $absentStreamName -ErrorAction Stop } | Should -Throw -ErrorId "AlternateDataStreamNotFound,Microsoft.PowerShell.Commands.GetItemCommand" + } + It "Should find zero alt streams and not fail on a directory with a wildcard stream name if no alt streams are present" -Skip:$skipNotWindows { + $result = Get-Item $noAltStreamDirectory -Stream * -ErrorAction Stop + $result | Should -BeExactly $null + } } Context "Registry Provider" { diff --git a/test/powershell/Modules/Microsoft.PowerShell.Management/Remove-Item.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Management/Remove-Item.Tests.ps1 index 769a8a34003..3e8ccb8fa91 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Management/Remove-Item.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Management/Remove-Item.Tests.ps1 @@ -7,9 +7,7 @@ Describe "Remove-Item" -Tags "CI" { Context "File removal Tests" { BeforeEach { New-Item -Name $testfile -Path $testpath -ItemType "file" -Value "lorem ipsum" -Force - Test-Path $testfilepath | Should -BeTrue - } It "Should be able to be called on a regular file without error using the Path parameter" { @@ -138,4 +136,35 @@ Describe "Remove-Item" -Tags "CI" { Test-Path $testdirectory | Should -BeFalse } } + + Context "Alternate Data Streams should be supported on Windows" { + BeforeAll { + if (!$IsWindows) { + return + } + $fileName = "ADStest.txt" + $streamName = "teststream" + $dirName = "ADStestdir" + $fileContent =" This is file content." + $streamContent = "datastream content here" + $streamfile = Join-Path -Path $testpath -ChildPath $fileName + $streamdir = Join-Path -Path $testpath -ChildPath $dirName + + $null = New-Item -Path $streamfile -ItemType "File" -force + Add-Content -Path $streamfile -Value $fileContent + Add-Content -Path $streamfile -Stream $streamName -Value $streamContent + $null = New-Item -Path $streamdir -ItemType "Directory" -Force + Add-Content -Path $streamdir -Stream $streamName -Value $streamContent + } + It "Should completely remove a datastream from a file" -Skip:(!$IsWindows) { + Get-Item -Path $streamfile -Stream $streamName | Should -Not -BeNullOrEmpty + Remove-Item -Path $streamfile -Stream $streamName + Get-Item -Path $streamfile -Stream $streamName -ErrorAction SilentlyContinue | Should -BeNullOrEmpty + } + It "Should completely remove a datastream from a directory" -Skip:(!$IsWindows) { + Get-Item -Path $streamdir -Stream $streamName | Should -Not -BeNullOrEmpty + Remove-Item -Path $streamdir -Stream $streamName + Get-Item -Path $streamdir -Stream $streamname -ErrorAction SilentlyContinue | Should -BeNullOrEmpty + } + } } diff --git a/test/powershell/Modules/Microsoft.PowerShell.Management/Set-Content.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Management/Set-Content.Tests.ps1 index 6e8f8bde083..fefd73412df 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Management/Set-Content.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Management/Set-Content.Tests.ps1 @@ -72,6 +72,39 @@ Describe "Set-Content cmdlet tests" -Tags "CI" { $result[1] | Should -BeExactly "world" } } + Context "Set-Content should work with alternate data streams on Windows" { + BeforeAll { + if ( -Not $IsWindows ) + { + return + } + $altStreamPath = "$TESTDRIVE/altStream.txt" + $altStreamPath2 = "$TESTDRIVE/altStream2.txt" + $altStreamDirectory = "$TESTDRIVE/altstreamdir" + $altStreamDirectory2 = "$TESTDRIVE/altstream2dir" + $stringData = "test data" + $streamName = "test" + $absentStreamName = "noExist" + $item = New-Item -type file $altStreamPath + $altstreamdiritem = New-Item -type directory $altStreamDirectory + } + It "Should create a new data stream on a file" -Skip:(-Not $IsWindows) { + Set-Content -Path $altStreamPath -Stream $streamName -Value $stringData + Get-Content -Path $altStreamPath -Stream $streamName | Should -BeExactly $stringData + } + It "Should create a new data stream on a file using colon syntax" -Skip:(-Not $IsWindows) { + Set-Content -Path ${altStreamPath2}:${streamName} -Value $stringData + Get-Content -Path ${altStreamPath2} -Stream $streamName | Should -BeExactly $stringData + } + It "Should create a new data stream on a directory" -Skip:(-Not $IsWindows) { + Set-Content -Path $altStreamDirectory -Stream $streamName -Value $stringData + Get-Content -Path $altStreamDirectory -Stream $streamName | Should -BeExactly $stringData + } + It "Should create a new data stream on a directory using colon syntax" -Skip:(-Not $IsWindows) { + Set-Content -Path ${altStreamDirectory2}:${streamName} -Value $stringData + Get-Content -Path ${altStreamDirectory2} -Stream ${streamName} | Should -BeExactly $stringData + } + } } Describe "Set-Content should work for PSDrive with UNC path as root" -Tags @('CI', 'RequireAdminOnWindows') { diff --git a/test/powershell/Modules/Microsoft.PowerShell.Management/Test-Connection.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Management/Test-Connection.Tests.ps1 index bcd0562af85..10f39bca320 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Management/Test-Connection.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Management/Test-Connection.Tests.ps1 @@ -44,6 +44,7 @@ Describe "Test-Connection" -tags "CI" { $targetAddress = "127.0.0.1" $targetAddressIPv6 = "::1" $UnreachableAddress = "10.11.12.13" + # under some environments, we can't round trip this and retrieve the real name from the address # in this case we will simply use the hostname $jobContinues = Start-Job { Test-Connection $using:targetAddress -Repeat } @@ -105,7 +106,7 @@ Describe "Test-Connection" -tags "CI" { $error[0].Exception.InnerException.ErrorCode | Should -Be $code } - It "Force IPv4 with implicit PingOptions" -Pending { + It "Force IPv4 with implicit PingOptions" { $result = Test-Connection $testAddress -Count 1 -IPv4 $result[0].Address | Should -BeExactly $testAddress @@ -116,6 +117,7 @@ Describe "Test-Connection" -tags "CI" { } # In VSTS, address is 0.0.0.0 + # This test is marked as PENDING as .NET Core does not return correct PingOptions from ping request It "Force IPv4 with explicit PingOptions" -Pending { $result1 = Test-Connection $testAddress -Count 1 -IPv4 -MaxHops 10 -DontFragment @@ -259,7 +261,7 @@ Describe "Test-Connection" -tags "CI" { Context "MTUSizeDetect" { # We skip the MtuSize detection tests when in containers, as the environments throw raw exceptions # instead of returning a PacketTooBig response cleanly. - It "MTUSizeDetect works" -Pending:($true -or $env:__INCONTAINER -eq 1) { + It "MTUSizeDetect works" -Pending:($env:__INCONTAINER -eq 1) { $result = Test-Connection $testAddress -MtuSize $result | Should -BeOfType Microsoft.PowerShell.Commands.TestConnectionCommand+PingMtuStatus @@ -282,7 +284,7 @@ Describe "Test-Connection" -tags "CI" { $result = Test-Connection $testAddress -TraceRoute -IPv4 $result[0] | Should -BeOfType Microsoft.PowerShell.Commands.TestConnectionCommand+TraceStatus - $result[0].Source | Should -BeExactly $hostName + $result[0].Source | Should -BeExactly $testAddress $result[0].TargetAddress | Should -BeExactly $testAddress $result[0].Target | Should -BeExactly $testAddress $result[0].Hop | Should -Be 1 diff --git a/test/powershell/Modules/Microsoft.PowerShell.Utility/PowerShellData.tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Utility/PowerShellData.tests.ps1 index 6d13be5005b..222bbf7e900 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Utility/PowerShellData.tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Utility/PowerShellData.tests.ps1 @@ -1,6 +1,19 @@ # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. Describe "Tests for the Import-PowerShellDataFile cmdlet" -Tags "CI" { + BeforeAll { + $largePsd1Path = Join-Path -Path $TestDrive -ChildPath 'large.psd1' + $largePsd1Builder = [System.Text.StringBuilder]::new('@{') + 1..501 | ForEach-Object { + $largePsd1Builder.Append("key$_ = $_;") + } + $largePsd1Builder.Append('}') + Set-Content -Path $largePsd1Path -Value $largePsd1Builder.ToString() + + if ((Get-ExperimentalFeature Microsoft.PowerShell.Utility.PSImportPSDataFileSkipLimitCheck).Enabled -ne $true) { + $skipTest = $true + } + } It "Validates error on a missing path" { { Import-PowerShellDataFile -Path /SomeMissingDirectory -ErrorAction Stop } | @@ -32,4 +45,12 @@ Describe "Tests for the Import-PowerShellDataFile cmdlet" -Tags "CI" { $result.Hello | Should -BeExactly "World" } + It 'Fails if psd1 file has more than 500 keys' { + { Import-PowerShellDataFile $largePsd1Path } | Should -Throw -ErrorId 'System.InvalidOperationException,Microsoft.PowerShell.Commands.ImportPowerShellDataFileCommand' + } + + It 'Succeeds if -NoLimit is used and has more than 500 keys' -Skip:$skipTest { + $result = Import-PowerShellDataFile $largePsd1Path -SkipLimitCheck + $result.Keys.Count | Should -Be 501 + } } diff --git a/test/powershell/engine/Formatting/OutputRendering.Tests.ps1 b/test/powershell/engine/Formatting/OutputRendering.Tests.ps1 new file mode 100644 index 00000000000..27dea30689e --- /dev/null +++ b/test/powershell/engine/Formatting/OutputRendering.Tests.ps1 @@ -0,0 +1,85 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +Describe 'OutputRendering tests' { + BeforeAll { + $PSDefaultParameterValues.Add('It:Skip', (-not $EnabledExperimentalFeatures.Contains('PSAnsiRendering'))) + $th = New-TestHost + $rs = [runspacefactory]::Createrunspace($th) + $rs.open() + $ps = [powershell]::Create() + $ps.Runspace = $rs + } + + AfterAll { + $PSDefaultParameterValues.Remove('It:Skip') + } + + BeforeEach { + if ($null -ne $PSStyle) { + $oldOutputRendering = $PSStyle.OutputRendering + } + } + + AfterEach { + if ($null -ne $PSStyle) { + $PSStyle.OutputRendering = $oldOutputRendering + } + + $ps.Commands.Clear() + } + + It 'OutputRendering works for "" to the host' -TestCases @( + @{ outputRendering = 'automatic'; ansi = $true } + @{ outputRendering = 'host' ; ansi = $true } + @{ outputRendering = 'ansi' ; ansi = $true } + @{ outputRendering = 'plaintext'; ansi = $false } + ) { + param($outputRendering, $ansi) + + $out = pwsh -noprofile -command "[System.Management.Automation.Internal.InternalTestHooks]::SetTestHook('BypassOutputRedirectionCheck', `$true); `$PSStyle.OutputRendering = '$outputRendering'; write-host '$($PSStyle.Foreground.Green)hello'" + + if ($ansi) { + $out | Should -BeLike "*`e*" -Because ($out | Format-Hex | Out-String) + } + else { + $out | Should -Not -BeLike "*`e*" -Because ($out | Format-Hex | Out-String) + } + } + + It 'OutputRendering works for "" to the pipeline' -TestCases @( + @{ outputRendering = 'automatic'; ansi = $true } + @{ outputRendering = 'host' ; ansi = $false } + @{ outputRendering = 'ansi' ; ansi = $true } + @{ outputRendering = 'plaintext'; ansi = $false } + ) { + param($outputRendering, $ansi) + + $PSStyle.OutputRendering = $outputRendering + $out = "$($PSStyle.Foreground.Green)hello" | Out-String + + if ($ansi) { + $out | Should -BeLike "*`e*" -Because ($out | Format-Hex | Out-String) + } + else { + $out | Should -Not -BeLike "*`e*" -Because ($out | Format-Hex | Out-String) + } + } + + # Error isn't covered here because it has custom formatting + It 'OutputRendering is correct for ' -TestCases @( + @{ stream = 'Verbose' } + @{ stream = 'Debug' } + @{ stream = 'Warning' } + ) { + param($stream) + + if ($stream -ne 'Warning') + { + $switch = "-$stream" + } + + $out = pwsh -noprofile -command "[System.Management.Automation.Internal.InternalTestHooks]::SetTestHook('BypassOutputRedirectionCheck', `$true); write-$stream $switch 'hello'" + $out | Should -BeExactly "$($PSStyle.Formatting.$stream)$($stream.ToUpper()): hello" + } +} diff --git a/test/powershell/engine/Formatting/PSStyle.Tests.ps1 b/test/powershell/engine/Formatting/PSStyle.Tests.ps1 new file mode 100644 index 00000000000..5e02e2e231c --- /dev/null +++ b/test/powershell/engine/Formatting/PSStyle.Tests.ps1 @@ -0,0 +1,114 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +Describe 'Tests for $PSStyle automatic variable' { + BeforeAll { + $PSDefaultParameterValues.Add('It:Skip', (-not $EnabledExperimentalFeatures.Contains('PSAnsiRendering'))) + $styleDefaults = @{ + Reset = "`e[0m" + BlinkOff = "`e[5m" + Blink = "`e[25m" + BoldOff = "`e[22m" + Bold = "`e[1m" + HiddenOff = "`e[28m" + Hidden = "`e[8m" + ReverseOff = "`e[27m" + Reverse = "`e[7m" + ItalicOff = "`e[23m" + Italic = "`e[3m" + UnderlineOff = "`e[24m" + Underline = "`e[4m" + } + + $formattingDefaults = @{ + FormatAccent = "`e[32;1m" + ErrorAccent = "`e[36;1m" + Error = "`e[31;1m" + Debug = "`e[33;1m" + Verbose = "`e[33;1m" + Warning = "`e[33;1m" + } + + $foregroundDefaults = @{ + Black = "`e[30m" + White = "`e[37m" + DarkGray = "`e[90m" + LightGray = "`e[97m" + Red = "`e[31m" + LightRed = "`e[91m" + Magenta = "`e[35m" + LightMagenta = "`e[95m" + Blue = "`e[34m" + LightBlue = "`e[94m" + Cyan = "`e[36m" + LightCyan = "`e[96m" + Green = "`e[32m" + LightGreen = "`e[92m" + Yellow = "`e[33m" + LightYellow = "`e[93m" + } + + $backgroundDefaults = @{ + Black = "`e[40m" + White = "`e[47m" + DarkGray = "`e[100m" + LightGray = "`e[107m" + Red = "`e[41m" + LightRed = "`e[101m" + Magenta = "`e[45m" + LightMagenta = "`e[105m" + Blue = "`e[44m" + LightBlue = "`e[104m" + Cyan = "`e[46m" + LightCyan = "`e[106m" + Green = "`e[42m" + LightGreen = "`e[102m" + Yellow = "`e[43m" + LightYellow = "`e[103m" + } + + function Get-TestCases($hashtable) { + $testcases = [System.Collections.Generic.List[hashtable]]::new() + foreach ($key in $hashtable.Keys) { + $testcases.Add( + @{ Key = $key; Value = $hashtable[$key] } + ) + } + + return $testcases + } + } + + AfterAll { + $PSDefaultParameterValues.Remove('It:Skip') + } + + It '$PSStyle has correct default for OutputRendering' { + $PSStyle | Should -Not -BeNullOrEmpty + $PSStyle.OutputRendering | Should -BeExactly 'Automatic' + } + + It '$PSStyle has correct defaults for style ' -TestCases (Get-TestCases $styleDefaults) { + param($key, $value) + + $PSStyle.$key | Should -BeExactly $value + } + + It '$PSStyle.Formatting has correct default for ' -TestCases (Get-TestCases $formattingDefaults) { + param($key, $value) + + $PSStyle.Formatting.$key | Should -BeExactly $value + } + + It '$PSStyle.Foreground has correct default for ' -TestCases (Get-TestCases $foregroundDefaults) { + param($key, $value) + + $PSStyle.Foreground.$key | Should -BeExactly $value + } + + It '$PSStyle.Background has correct default for ' -TestCases (Get-TestCases $backgroundDefaults) { + param($key, $value) + + $PSStyle.Background.$key | Should -BeExactly $value + } +} diff --git a/test/powershell/engine/ParameterBinding/ParameterBinding.Tests.ps1 b/test/powershell/engine/ParameterBinding/ParameterBinding.Tests.ps1 index 07d132012a0..a0fe5973c8e 100644 --- a/test/powershell/engine/ParameterBinding/ParameterBinding.Tests.ps1 +++ b/test/powershell/engine/ParameterBinding/ParameterBinding.Tests.ps1 @@ -256,6 +256,62 @@ Describe "Parameter Binding Tests" -Tags "CI" { DynamicParamTest -PipelineVariable bar | ForEach-Object { $bar } | Should -Be "hi" } + Context "PipelineVariable Behaviour" { + + BeforeAll { + function Write-PipelineVariable { + [CmdletBinding()] + [OutputType([int])] + param( + [Parameter(ValueFromPipeline)] + $a + ) + begin { 1 } + process { 2 } + end { 3 } + } + + $testScripts = @( + @{ + CmdletType = 'Script Cmdlet' + Script = { + 1..3 | + Write-PipelineVariable -PipelineVariable pipe | + Select-Object -Property @( + @{ Name = "PipelineVariableSet"; Expression = { $null -ne $pipe ? $true : $false } } + @{ Name = "PipelineVariable"; Expression = { $pipe } } + ) + } + } + @{ + CmdletType = 'Compiled Cmdlet' + Script = { + 1..3 | + Write-PipelineVariable | + ForEach-Object { $_ } -PipelineVariable pipe | + Select-Object -Property @( + @{ Name = "PipelineVariableSet"; Expression = { $null -ne $pipe ? $true : $false } } + @{ Name = "PipelineVariable"; Expression = { $pipe } } + ) + } + } + ) + } + + AfterAll { + Remove-Item -Path 'function:Write-PipelineVariable' + } + + It 'should set the pipeline variable every time for a ' -TestCases $testScripts { + param($Script, $CmdletType) + + $result = & $Script + $result.Count | Should -Be 5 + $result.PipelineVariableSet | Should -Not -Contain $false + $result.PipelineVariable | Should -Be 1, 2, 2, 2, 3 + } + } + Context "Use automatic variables as default value for parameters" { BeforeAll { ## Explicit use of 'CmdletBinding' make it a script cmdlet diff --git a/test/tools/Modules/nuget.config b/test/tools/Modules/nuget.config new file mode 100644 index 00000000000..b0fc73009da --- /dev/null +++ b/test/tools/Modules/nuget.config @@ -0,0 +1,10 @@ + + + + + + + + + + diff --git a/test/tools/TestExe/TestExe.cs b/test/tools/TestExe/TestExe.cs index c8f91d4d38e..0eac8074de0 100644 --- a/test/tools/TestExe/TestExe.cs +++ b/test/tools/TestExe/TestExe.cs @@ -13,7 +13,7 @@ private static int Main(string[] args) { if (args.Length > 0) { - switch(args[0].ToLowerInvariant()) + switch (args[0].ToLowerInvariant()) { case "-echoargs": EchoArgs(args); diff --git a/test/tools/WebListener/Controllers/DosController.cs b/test/tools/WebListener/Controllers/DosController.cs index 6024430095e..7fc138e0e81 100644 --- a/test/tools/WebListener/Controllers/DosController.cs +++ b/test/tools/WebListener/Controllers/DosController.cs @@ -22,7 +22,6 @@ public string Index() Response.StatusCode = 200; - StringValues dosType; if (Request.Query.TryGetValue("dosType", out dosType)) { diff --git a/test/tools/WebListener/Controllers/LinkController.cs b/test/tools/WebListener/Controllers/LinkController.cs index 3aa7541f4ee..e15607d6b9b 100644 --- a/test/tools/WebListener/Controllers/LinkController.cs +++ b/test/tools/WebListener/Controllers/LinkController.cs @@ -109,7 +109,7 @@ public IActionResult Error() return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier }); } - private string GetLink(string baseUri, int maxLinks, int linkNumber, string whitespace, string type, string rel) + private static string GetLink(string baseUri, int maxLinks, int linkNumber, string whitespace, string type, string rel) { return string.Format(Constants.LinkUriTemplate, baseUri, maxLinks, linkNumber, type, whitespace, rel); } diff --git a/test/tools/WebListener/Controllers/ResponseController.cs b/test/tools/WebListener/Controllers/ResponseController.cs index 70e4659b3a4..6347abc98e6 100644 --- a/test/tools/WebListener/Controllers/ResponseController.cs +++ b/test/tools/WebListener/Controllers/ResponseController.cs @@ -99,7 +99,7 @@ public IActionResult Error() return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier }); } - private List GetSingleOrArray(JToken token) + private static List GetSingleOrArray(JToken token) { if (token.HasValues) { diff --git a/test/tools/WebListener/Controllers/ResumeController.cs b/test/tools/WebListener/Controllers/ResumeController.cs index ebcfad40d78..8aec71e416f 100644 --- a/test/tools/WebListener/Controllers/ResumeController.cs +++ b/test/tools/WebListener/Controllers/ResumeController.cs @@ -30,12 +30,12 @@ public async void Index() if (TryGetRangeHeader(out rangeHeader)) { var range = GetRange(rangeHeader); - if(range.From != null) + if (range.From != null) { from = (int)range.From; } - if(range.To != null) + if (range.To != null) { to = (int)range.To; } @@ -49,7 +49,7 @@ public async void Index() return; } - if(to >= FileBytes.Length || from >= FileBytes.Length) + if (to >= FileBytes.Length || from >= FileBytes.Length) { Response.StatusCode = StatusCodes.Status416RequestedRangeNotSatisfiable; Response.Headers[HeaderNames.ContentRange] = $"bytes */{FileBytes.Length}"; @@ -91,7 +91,7 @@ public IActionResult Error() return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier }); } - private RangeItemHeaderValue GetRange(string rangeHeader) + private static RangeItemHeaderValue GetRange(string rangeHeader) { return RangeHeaderValue.Parse(rangeHeader).Ranges.FirstOrDefault(); } @@ -113,7 +113,7 @@ private void SetResumeResponseHeaders() private bool TryGetRangeHeader(out string rangeHeader) { var rangeHeaderSv = new StringValues(); - if(Request.Headers.TryGetValue("Range", out rangeHeaderSv)) + if (Request.Headers.TryGetValue("Range", out rangeHeaderSv)) { rangeHeader = rangeHeaderSv.FirstOrDefault(); return true; diff --git a/test/tools/WebListener/Program.cs b/test/tools/WebListener/Program.cs index 08055965d81..49f3df50bb9 100644 --- a/test/tools/WebListener/Program.cs +++ b/test/tools/WebListener/Program.cs @@ -42,7 +42,7 @@ public static IWebHost BuildWebHost(string[] args) => HttpsConnectionAdapterOptions httpsOption = new HttpsConnectionAdapterOptions(); httpsOption.SslProtocols = SslProtocols.Tls12; httpsOption.ClientCertificateMode = ClientCertificateMode.AllowCertificate; - httpsOption.ClientCertificateValidation = (inCertificate, inChain, inPolicy) => {return true;}; + httpsOption.ClientCertificateValidation = (inCertificate, inChain, inPolicy) => { return true; }; httpsOption.CheckCertificateRevocation = false; httpsOption.ServerCertificate = certificate; listenOptions.UseHttps(httpsOption); @@ -53,7 +53,7 @@ public static IWebHost BuildWebHost(string[] args) => HttpsConnectionAdapterOptions httpsOption = new HttpsConnectionAdapterOptions(); httpsOption.SslProtocols = SslProtocols.Tls11; httpsOption.ClientCertificateMode = ClientCertificateMode.AllowCertificate; - httpsOption.ClientCertificateValidation = (inCertificate, inChain, inPolicy) => {return true;}; + httpsOption.ClientCertificateValidation = (inCertificate, inChain, inPolicy) => { return true; }; httpsOption.CheckCertificateRevocation = false; httpsOption.ServerCertificate = certificate; listenOptions.UseHttps(httpsOption); @@ -64,7 +64,7 @@ public static IWebHost BuildWebHost(string[] args) => HttpsConnectionAdapterOptions httpsOption = new HttpsConnectionAdapterOptions(); httpsOption.SslProtocols = SslProtocols.Tls; httpsOption.ClientCertificateMode = ClientCertificateMode.AllowCertificate; - httpsOption.ClientCertificateValidation = (inCertificate, inChain, inPolicy) => {return true;}; + httpsOption.ClientCertificateValidation = (inCertificate, inChain, inPolicy) => { return true; }; httpsOption.CheckCertificateRevocation = false; httpsOption.ServerCertificate = certificate; listenOptions.UseHttps(httpsOption); @@ -75,7 +75,7 @@ public static IWebHost BuildWebHost(string[] args) => HttpsConnectionAdapterOptions httpsOption = new HttpsConnectionAdapterOptions(); httpsOption.SslProtocols = SslProtocols.Tls13; httpsOption.ClientCertificateMode = ClientCertificateMode.AllowCertificate; - httpsOption.ClientCertificateValidation = (inCertificate, inChain, inPolicy) => {return true;}; + httpsOption.ClientCertificateValidation = (inCertificate, inChain, inPolicy) => { return true; }; httpsOption.CheckCertificateRevocation = false; httpsOption.ServerCertificate = certificate; listenOptions.UseHttps(httpsOption); diff --git a/test/xUnit/csharp/test_AstDefaultVisit.cs b/test/xUnit/csharp/test_AstDefaultVisit.cs index 925f2c6be53..283c1f73071 100644 --- a/test/xUnit/csharp/test_AstDefaultVisit.cs +++ b/test/xUnit/csharp/test_AstDefaultVisit.cs @@ -44,7 +44,7 @@ public static class AstDefaultVisitTests public static void TestCustomAstVisitor() { var ast = Parser.ParseInput("a | b", out _, out _); - var expected = typeof(NamedBlockAst).Name; + var expected = nameof(NamedBlockAst); var myVisitor1 = new MyICustomAstVisitor2(); var result1 = ast.EndBlock.Accept(myVisitor1); diff --git a/test/xUnit/csharp/test_CommandLineParser.cs b/test/xUnit/csharp/test_CommandLineParser.cs index f52fcdf2fee..9e942bb0051 100644 --- a/test/xUnit/csharp/test_CommandLineParser.cs +++ b/test/xUnit/csharp/test_CommandLineParser.cs @@ -976,6 +976,7 @@ public IEnumerator GetEnumerator() yield return new object[] { "-settingsfile", _fileName }; yield return new object[] { "-settings", _fileName }; } + IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); } diff --git a/test/xUnit/csharp/test_FileSystemProvider.cs b/test/xUnit/csharp/test_FileSystemProvider.cs index ef702d47bd6..b2a017b4b95 100644 --- a/test/xUnit/csharp/test_FileSystemProvider.cs +++ b/test/xUnit/csharp/test_FileSystemProvider.cs @@ -39,12 +39,21 @@ public FileSystemProviderTests() File.AppendAllText(testPath, testContent); } - void IDisposable.Dispose() + public void Dispose() { - File.Delete(testPath); + Dispose(true); + GC.SuppressFinalize(this); + } + + protected virtual void Dispose(bool disposing) + { + if (disposing) + { + File.Delete(testPath); + } } - private ExecutionContext GetExecutionContext() + private static ExecutionContext GetExecutionContext() { CultureInfo currentCulture = CultureInfo.CurrentCulture; PSHost hostInterface = new DefaultHost(currentCulture, currentCulture); @@ -54,7 +63,7 @@ private ExecutionContext GetExecutionContext() return executionContext; } - private ProviderInfo GetProvider() + private static ProviderInfo GetProvider() { ExecutionContext executionContext = GetExecutionContext(); SessionStateInternal sessionState = new SessionStateInternal(executionContext); diff --git a/test/xUnit/csharp/test_NamedPipe.cs b/test/xUnit/csharp/test_NamedPipe.cs index 1ee50036fc0..1174799fd95 100644 --- a/test/xUnit/csharp/test_NamedPipe.cs +++ b/test/xUnit/csharp/test_NamedPipe.cs @@ -31,7 +31,7 @@ public void TestCustomPipeNameCreation() [Fact] public void TestCustomPipeNameCreationTooLongOnNonWindows() { - var longPipeName = "DoggoipsumwaggywagssmolborkingdoggowithalongsnootforpatsdoingmeafrightenporgoYapperporgolongwatershoobcloudsbigolpupperlengthboy"; + const string longPipeName = "DoggoipsumwaggywagssmolborkingdoggowithalongsnootforpatsdoingmeafrightenporgoYapperporgolongwatershoobcloudsbigolpupperlengthboy"; if (!Platform.IsWindows) { diff --git a/test/xUnit/csharp/test_PSConfiguration.cs b/test/xUnit/csharp/test_PSConfiguration.cs index 6237f453335..54e69da68f0 100644 --- a/test/xUnit/csharp/test_PSConfiguration.cs +++ b/test/xUnit/csharp/test_PSConfiguration.cs @@ -97,18 +97,27 @@ public PowerShellPolicyFixture() public void Dispose() { - CleanupConfigFiles(); - if (systemWideConfigBackupFile != null) - { - File.Move(systemWideConfigBackupFile, systemWideConfigFile); - } + Dispose(true); + GC.SuppressFinalize(this); + } - if (currentUserConfigBackupFile != null) + protected virtual void Dispose(bool disposing) + { + if (disposing) { - File.Move(currentUserConfigBackupFile, currentUserConfigFile); - } + CleanupConfigFiles(); + if (systemWideConfigBackupFile != null) + { + File.Move(systemWideConfigBackupFile, systemWideConfigFile); + } - InternalTestHooks.BypassGroupPolicyCaching = originalTestHookValue; + if (currentUserConfigBackupFile != null) + { + File.Move(currentUserConfigBackupFile, currentUserConfigFile); + } + + InternalTestHooks.BypassGroupPolicyCaching = originalTestHookValue; + } } internal PowerShellPolicies SystemWidePolicies @@ -357,11 +366,27 @@ public void SetupConfigFile4() CreateEmptyFile(currentUserConfigFile); } - private void CreateEmptyFile(string fileName) + private static void CreateEmptyFile(string fileName) { File.Create(fileName).Dispose(); } + public void SetupConfigFile5() + { + CleanupConfigFiles(); + + // System wide config file is broken + CreateBrokenConfigFile(systemWideConfigFile); + + // Current user config file is broken + CreateBrokenConfigFile(currentUserConfigFile); + } + + private static void CreateBrokenConfigFile(string fileName) + { + File.WriteAllText(fileName, "[abbra"); + } + internal void ForceReadingFromFile() { // Reset the cached roots. @@ -952,5 +977,15 @@ public void Utils_GetPolicySetting_BothConfigFilesNotExist() consoleSessionConfiguration = Utils.GetPolicySetting(Utils.CurrentUserThenSystemWideConfig); fixture.CompareConsoleSessionConfiguration(consoleSessionConfiguration, null); } + + [Fact, Priority(11)] + public void PowerShellConfig_GetPowerShellPolicies_BrokenSystemConfig() + { + fixture.SetupConfigFile5(); + fixture.ForceReadingFromFile(); + + Assert.Throws(() => PowerShellConfig.Instance.GetPowerShellPolicies(ConfigScope.AllUsers)); + Assert.Throws(() => PowerShellConfig.Instance.GetPowerShellPolicies(ConfigScope.CurrentUser)); + } } } diff --git a/test/xUnit/csharp/test_Utils.cs b/test/xUnit/csharp/test_Utils.cs index b30c3ad18f8..ea45ce533d6 100644 --- a/test/xUnit/csharp/test_Utils.cs +++ b/test/xUnit/csharp/test_Utils.cs @@ -59,7 +59,7 @@ public static void TestHistoryStack() [Fact] public static void TestBoundedStack() { - int capacity = 20; + const int capacity = 20; var boundedStack = new BoundedStack(capacity); Assert.Throws(() => boundedStack.Pop()); @@ -116,7 +116,7 @@ public static void TestConvertToJsonWithEnum() public static void TestConvertToJsonWithoutCompress() { var context = new JsonObject.ConvertToJsonContext(maxDepth: 1, enumsAsStrings: true, compressOutput: false); - string expected = @"{ + const string expected = @"{ ""type"": ""Alias"" }"; Hashtable hash = new Hashtable { diff --git a/test/xUnit/xUnit.tests.csproj b/test/xUnit/xUnit.tests.csproj index 6ecf0f798aa..352da3d353d 100644 --- a/test/xUnit/xUnit.tests.csproj +++ b/test/xUnit/xUnit.tests.csproj @@ -27,7 +27,7 @@ - + diff --git a/tools/metadata.json b/tools/metadata.json index 551b28425c6..77d654d1dd1 100644 --- a/tools/metadata.json +++ b/tools/metadata.json @@ -1,9 +1,9 @@ { "StableReleaseTag": "v7.1.0", - "PreviewReleaseTag": "v7.1.0-rc.2", + "PreviewReleaseTag": "v7.2.0-preview.1", "ServicingReleaseTag": "v6.2.7", "ReleaseTag": "v7.1.0", "LTSReleaseTag" : ["v7.0.3"], - "NextReleaseTag": "v7.2.0-preview.1", + "NextReleaseTag": "v7.2.0-preview.2", "LTSRelease": false } diff --git a/tools/packaging/packaging.psm1 b/tools/packaging/packaging.psm1 index 4a1ecd52854..aaaee8688d0 100644 --- a/tools/packaging/packaging.psm1 +++ b/tools/packaging/packaging.psm1 @@ -1825,8 +1825,7 @@ function New-ILNugetPackage "Microsoft.PowerShell.SDK.dll", "Microsoft.WSMan.Management.dll", "Microsoft.WSMan.Runtime.dll", - "System.Management.Automation.dll", - "Microsoft.PowerShell.MarkdownRender.dll") + "System.Management.Automation.dll") $linuxExceptionList = @( "Microsoft.Management.Infrastructure.CimCmdlets.dll", @@ -1934,7 +1933,6 @@ function New-ILNugetPackage 'Microsoft.PowerShell.Commands.Utility' { $deps.Add([tuple]::Create([tuple]::Create('id', 'System.Management.Automation'), [tuple]::Create('version', $PackageVersion))) > $null - $deps.Add([tuple]::Create([tuple]::Create('id', 'Microsoft.PowerShell.MarkdownRender'), [tuple]::Create('version', $PackageVersion))) > $null foreach($packageInfo in (Get-ProjectPackageInformation -ProjectName $fileBaseName)) { @@ -1996,14 +1994,6 @@ function New-ILNugetPackage $deps.Add([tuple]::Create([tuple]::Create('id', $packageInfo.Name), [tuple]::Create('version', $packageInfo.Version))) > $null } } - - 'Microsoft.PowerShell.MarkdownRender' { - $deps.Add([tuple]::Create([tuple]::Create('id', 'System.Management.Automation'), [tuple]::Create('version', $PackageVersion))) > $null - foreach($packageInfo in (Get-ProjectPackageInformation -ProjectName $fileBaseName)) - { - $deps.Add([tuple]::Create([tuple]::Create('id', $packageInfo.Name), [tuple]::Create('version', $packageInfo.Version))) > $null - } - } } New-NuSpec -PackageId $fileBaseName -PackageVersion $PackageVersion -Dependency $deps -FilePath (Join-Path $filePackageFolder.FullName "$fileBaseName.nuspec") @@ -2321,7 +2311,6 @@ function CleanupGeneratedSourceCode '[Microsoft.PowerShell.Commands.AddMemberCommand' '[System.Management.Automation.ArgumentCompleterAttribute(typeof(Microsoft.PowerShell.Commands.Utility.JoinItemCompleter))]' '[System.Management.Automation.ArgumentCompleterAttribute(typeof(System.Management.Automation.PropertyNameCompleter))]' - '[System.Management.Automation.OutputTypeAttribute(typeof(Microsoft.PowerShell.MarkdownRender' '[Microsoft.PowerShell.Commands.ArgumentToTypeNameTransformationAttribute]' '[System.Management.Automation.Internal.ArchitectureSensitiveAttribute]' '[Microsoft.PowerShell.Commands.SelectStringCommand.FileinfoToStringAttribute]' @@ -2401,7 +2390,6 @@ function CleanupGeneratedSourceCode if ($assemblyName -in $patternToReplace.ApplyTo -and $line.Contains($patternToReplace.Pattern)) { $line = $line.Replace($patternToReplace.Pattern, $patternToReplace.Replacement) $lineWasProcessed = $true - break } } diff --git a/tools/packaging/projects/reference/Microsoft.PowerShell.Commands.Utility/Microsoft.PowerShell.Commands.Utility.csproj b/tools/packaging/projects/reference/Microsoft.PowerShell.Commands.Utility/Microsoft.PowerShell.Commands.Utility.csproj index 8890d53951a..d6aa032de2b 100644 --- a/tools/packaging/projects/reference/Microsoft.PowerShell.Commands.Utility/Microsoft.PowerShell.Commands.Utility.csproj +++ b/tools/packaging/projects/reference/Microsoft.PowerShell.Commands.Utility/Microsoft.PowerShell.Commands.Utility.csproj @@ -15,5 +15,6 @@ + diff --git a/tools/releaseBuild/azureDevOps/AzArtifactFeed/PSGalleryToAzArtifacts.yml b/tools/releaseBuild/azureDevOps/AzArtifactFeed/PSGalleryToAzArtifacts.yml index fab28643168..221a385b8b8 100644 --- a/tools/releaseBuild/azureDevOps/AzArtifactFeed/PSGalleryToAzArtifacts.yml +++ b/tools/releaseBuild/azureDevOps/AzArtifactFeed/PSGalleryToAzArtifacts.yml @@ -18,7 +18,7 @@ steps: - pwsh: | Import-Module -Force "$(Build.SourcesDirectory)/tools/releaseBuild/azureDevOps/AzArtifactFeed/SyncGalleryToAzArtifacts.psm1" - SyncGalleryToAzArtifacts -AzDevOpsFeedUserName $(AzDevOpsFeedUserName) -AzDevOpsPAT $(AzDevOpsFeedPAT) -Destination $(Build.ArtifactStagingDirectory) + SyncGalleryToAzArtifacts -AzDevOpsFeedUserName $(AzDevOpsFeedUserName) -AzDevOpsPAT $(AzDevOpsFeedPAT2) -Destination $(Build.ArtifactStagingDirectory) displayName: Download packages from PSGallery that need to be updated condition: succeededOrFailed() diff --git a/tools/releaseBuild/azureDevOps/releaseBuild.yml b/tools/releaseBuild/azureDevOps/releaseBuild.yml index 6df2fe18f09..5e87ff58ec7 100644 --- a/tools/releaseBuild/azureDevOps/releaseBuild.yml +++ b/tools/releaseBuild/azureDevOps/releaseBuild.yml @@ -16,6 +16,7 @@ resources: type: github endpoint: ComplianceGHRepo name: PowerShell/compliance + ref: master variables: - name: DOTNET_CLI_TELEMETRY_OPTOUT diff --git a/tools/releaseBuild/azureDevOps/templates/insert-nuget-config-azfeed.yml b/tools/releaseBuild/azureDevOps/templates/insert-nuget-config-azfeed.yml index ae697e70e33..5fdb9f7d977 100644 --- a/tools/releaseBuild/azureDevOps/templates/insert-nuget-config-azfeed.yml +++ b/tools/releaseBuild/azureDevOps/templates/insert-nuget-config-azfeed.yml @@ -1,11 +1,25 @@ +parameters: + - name: "repoRoot" + default: $(REPOROOT) + steps: -- powershell: | - Import-Module $(Build.SourcesDirectory)/build.psm1 -Force - New-NugetConfigFile -NugetFeedUrl $(AzDevOpsFeed) -UserName $(AzDevOpsFeedUserName) -ClearTextPAT $(AzDevOpsFeedPAT) -FeedName AzDevOpsFeed -Destination $(Build.SourcesDirectory)/src/Modules +- pwsh: | + Import-Module ${{ parameters.repoRoot }}/build.psm1 -Force + New-NugetConfigFile -NugetFeedUrl $(AzDevOpsFeed) -UserName $(AzDevOpsFeedUserName) -ClearTextPAT $(AzDevOpsFeedPAT2) -FeedName AzDevOpsFeed -Destination '${{ parameters.repoRoot }}/src/Modules' - if(-not (Test-Path "$(Build.SourcesDirectory)/src/Modules/nuget.config")) + if(-not (Test-Path "${{ parameters.repoRoot }}/src/Modules/nuget.config")) { throw "nuget.config is not created" } displayName: 'Add nuget.config for Azure DevOps feed for PSGallery modules' condition: and(succeededOrFailed(), ne(variables['AzDevOpsFeed'], '')) +- pwsh: | + Import-Module ${{ parameters.repoRoot }}/build.psm1 -Force + New-NugetConfigFile -NugetFeedUrl $(AzDevOpsPackageFeed) -UserName $(AzDevOpsFeedUserName) -ClearTextPAT $(AzDevOpsFeedPAT2) -FeedName AzDevOpsFeed -Destination '${{ parameters.repoRoot }}' + + if(-not (Test-Path "${{ parameters.repoRoot }}/nuget.config")) + { + throw "nuget.config is not created" + } + displayName: 'Add nuget.config for Azure DevOps feed for packages' + condition: and(succeededOrFailed(), ne(variables['AzDevOpsPackageFeed'], '')) diff --git a/tools/releaseBuild/azureDevOps/templates/linux.yml b/tools/releaseBuild/azureDevOps/templates/linux.yml index 5c94fce0c26..0fac7ae4f24 100644 --- a/tools/releaseBuild/azureDevOps/templates/linux.yml +++ b/tools/releaseBuild/azureDevOps/templates/linux.yml @@ -7,15 +7,23 @@ jobs: - job: build_${{ parameters.buildName }} displayName: Build ${{ parameters.buildName }} condition: succeeded() - pool: Hosted Ubuntu 1604 + pool: + vmImage: ubuntu-16.04 dependsOn: ${{ parameters.parentJob }} variables: - build: ${{ parameters.buildName }} - runCodesignValidationInjection: false + - name: runCodesignValidationInjection + value: false + - name: build + value: ${{ parameters.buildName }} + - group: ESRP + steps: - checkout: self clean: true + - checkout: ComplianceRepo + clean: true + - template: SetVersionVariables.yml parameters: ReleaseTagVar: $(ReleaseTagVar) @@ -34,16 +42,19 @@ jobs: displayName: 'Skip Alpine or fxdependent for PS v6.0.*' - template: insert-nuget-config-azfeed.yml - + parameters: + repoRoot: $(REPOROOT) - powershell: | - import-module ./build.psm1 + import-module "$env:REPOROOT/build.psm1" Sync-PSTags -AddRemoteIfMissing displayName: SyncTags condition: and(succeeded(), ne(variables['SkipBuild'], 'true')) - powershell: | - tools/releaseBuild/vstsbuild.ps1 -ReleaseTag $(ReleaseTagVar) -Name '$(build)' + $env:AzDevOpsFeedPAT2 = '$(AzDevOpsFeedPAT2)' + & "$env:REPOROOT/tools/releaseBuild/vstsbuild.ps1" -ReleaseTag $(ReleaseTagVar) -Name '$(build)' + $env:AzDevOpsFeedPAT2 = $null displayName: 'Build and package' condition: and(succeeded(), ne(variables['SkipBuild'], 'true')) @@ -52,10 +63,19 @@ jobs: displayName: ${{ parameters.uploadDisplayName }} ${{ parameters.buildName }} dependsOn: build_${{ parameters.buildName }} condition: succeeded() - pool: Package ES Standard Build + pool: + vmImage: windows-latest variables: - buildName: ${{ parameters.buildName }} + - name: buildName + value: ${{ parameters.buildName }} + - group: ESRP + steps: + - checkout: self + clean: true + + - checkout: ComplianceRepo + clean: true - template: shouldSign.yml @@ -86,32 +106,26 @@ jobs: downloadPath: '$(System.ArtifactsDirectory)\rpm' condition: and(eq(variables['buildName'], 'RPM'),succeeded()) - - task: securedevelopmentteam.vss-secure-development-tools.build-task-antimalware.AntiMalware@3 - displayName: 'Run Defender Scan' - - - powershell: | - $authenticodefiles = @() - Get-ChildItem -Path '$(System.ArtifactsDirectory)\rpm\*.rpm' -recurse | ForEach-Object { $authenticodefiles += $_.FullName} - tools/releaseBuild/generatePackgeSigning.ps1 -LinuxFiles $authenticodeFiles -path "$(System.ArtifactsDirectory)\package.xml" - displayName: 'Generate RPM Signing Xml' - condition: and(and(succeeded(), eq(variables['SHOULD_SIGN'], 'true')),eq(variables['buildName'], 'RPM')) - - - powershell: | - Get-Content "$(System.ArtifactsDirectory)\package.xml" - displayName: 'Capture RPM signing xml' - condition: and(and(succeeded(), eq(variables['SHOULD_SIGN'], 'true')),eq(variables['buildName'], 'RPM')) - - - task: PkgESCodeSign@10 - displayName: 'CodeSign RPM $(System.ArtifactsDirectory)\package.xml' - env: - SYSTEM_ACCESSTOKEN: $(System.AccessToken) - inputs: - signConfigXml: '$(System.ArtifactsDirectory)\package.xml' - outPathRoot: '$(Build.StagingDirectory)\signedPackages' - binVersion: $(SigingVersion) - binVersionOverride: $(SigningVersionOverride) - condition: and(and(succeeded(), eq(variables['SHOULD_SIGN'], 'true')),eq(variables['buildName'], 'RPM')) - + - template: EsrpScan.yml@ComplianceRepo + parameters: + scanPath: $(System.ArtifactsDirectory) + pattern: | + **\*.rpm + **\*.deb + **\*.tar.gz + + - ${{ if eq(variables['buildName'], 'RPM') }}: + - template: EsrpSign.yml@ComplianceRepo + parameters: + buildOutputPath: $(System.ArtifactsDirectory)\rpm + signOutputPath: $(Build.StagingDirectory)\signedPackages + certificateId: "CP-450779-Pgp" + pattern: | + **\*.rpm + useMinimatch: true + shouldSign: $(SHOULD_SIGN) + + # requires windows - task: AzureFileCopy@4 displayName: 'Upload to Azure - DEB and tar.gz' inputs: @@ -125,6 +139,7 @@ jobs: parameters: artifactPath: $(System.ArtifactsDirectory)\finished\release + # requires windows - task: AzureFileCopy@4 displayName: 'Upload to Azure - RPM - Unsigned' inputs: @@ -135,10 +150,11 @@ jobs: ContainerName: '$(AzureVersion)' condition: and(and(succeeded(), ne(variables['SHOULD_SIGN'], 'true')),eq(variables['buildName'], 'RPM')) + # requires windows - task: AzureFileCopy@4 displayName: 'Upload to Azure - RPM - Signed' inputs: - SourcePath: '$(Build.StagingDirectory)\signedPackages\*' + SourcePath: '$(Build.StagingDirectory)\signedPackages\release\*' azureSubscription: '$(AzureFileCopySubscription)' Destination: AzureBlob storage: '$(StorageAccount)' @@ -152,7 +168,7 @@ jobs: - template: upload-final-results.yml parameters: - artifactPath: '$(Build.StagingDirectory)\signedPackages' + artifactPath: '$(Build.StagingDirectory)\signedPackages\release' condition: and(and(succeeded(), eq(variables['SHOULD_SIGN'], 'true')),eq(variables['buildName'], 'RPM')) - task: ms.vss-governance-buildtask.governance-build-task-component-detection.ComponentGovernanceComponentDetection@0 diff --git a/tools/releaseBuild/azureDevOps/templates/mac-file-signing.yml b/tools/releaseBuild/azureDevOps/templates/mac-file-signing.yml index fddbe5f131d..0332ec560d0 100644 --- a/tools/releaseBuild/azureDevOps/templates/mac-file-signing.yml +++ b/tools/releaseBuild/azureDevOps/templates/mac-file-signing.yml @@ -9,13 +9,15 @@ jobs: pool: name: Package ES Standard Build variables: - BuildConfiguration: release - BuildPlatform: any cpu + - group: ESRP steps: - checkout: self clean: true + - checkout: ComplianceRepo + clean: true + - template: shouldSign.yml - template: SetVersionVariables.yml @@ -63,27 +65,15 @@ jobs: Write-Host $zipFile displayName: 'Compress macOS binary files' - - pwsh: | - $pkgFiles = "$(Build.StagingDirectory)\macos\powershell-files-$(Version)-osx-x64.zip", "$(Build.StagingDirectory)\macos\powershell-lts-$(Version)-osx-x64.zip" - tools/releaseBuild/generatePackgeSigning.ps1 -MacDeveloperFiles $pkgFiles -path "$(System.ArtifactsDirectory)\package.xml" - displayName: 'Generate macOS binary Signing Xml' - - - pwsh: | - Get-Content "$(System.ArtifactsDirectory)\package.xml" - displayName: 'Capture macOS signing xml' - # Diagnostics is not critical it passes every time it runs - continueOnError: true - - - task: PkgESCodeSign@10 - displayName: 'CodeSign $(System.ArtifactsDirectory)\package.xml' - env: - SYSTEM_ACCESSTOKEN: $(System.AccessToken) - inputs: - signConfigXml: '$(System.ArtifactsDirectory)\package.xml' - outPathRoot: '$(Build.StagingDirectory)\signedMacOSPackages' - binVersion: $(SigingVersion) - binVersionOverride: $(SigningVersionOverride) - condition: and(succeeded(), eq(variables['SHOULD_SIGN'], 'true')) + - template: EsrpSign.yml@ComplianceRepo + parameters: + buildOutputPath: $(Build.StagingDirectory)\macos + signOutputPath: $(Build.StagingDirectory)\signedMacOSPackages + certificateId: "CP-401337-Apple" + pattern: | + **\*.zip + useMinimatch: true + shouldSign: $(SHOULD_SIGN) - pwsh: | $destination = "$(System.ArtifactsDirectory)\azureMacOs" @@ -100,8 +90,12 @@ jobs: artifactName: signedMacOsBins condition: and(succeeded(), eq(variables['SHOULD_SIGN'], 'true')) - - task: securedevelopmentteam.vss-secure-development-tools.build-task-antimalware.AntiMalware@3 - displayName: 'Run Defender Scan' + - ${{ if eq(variables['SHOULD_SIGN'], 'true') }}: + - template: EsrpScan.yml@ComplianceRepo + parameters: + scanPath: $(System.ArtifactsDirectory)\azureMacOs + pattern: | + **\* - task: ms.vss-governance-buildtask.governance-build-task-component-detection.ComponentGovernanceComponentDetection@0 displayName: 'Component Detection' diff --git a/tools/releaseBuild/azureDevOps/templates/mac-package-signing.yml b/tools/releaseBuild/azureDevOps/templates/mac-package-signing.yml index 05fe9114892..8d13693ca5a 100644 --- a/tools/releaseBuild/azureDevOps/templates/mac-package-signing.yml +++ b/tools/releaseBuild/azureDevOps/templates/mac-package-signing.yml @@ -9,13 +9,15 @@ jobs: pool: name: Package ES Standard Build variables: - BuildConfiguration: release - BuildPlatform: any cpu + - group: ESRP steps: - checkout: self clean: true + - checkout: ComplianceRepo + clean: true + - template: shouldSign.yml - template: SetVersionVariables.yml @@ -50,27 +52,15 @@ jobs: } displayName: 'Compress macOS Package' - - pwsh: | - $pkgFiles = "$(Build.StagingDirectory)\macos\powershell-$(Version)-osx-x64.zip", "$(Build.StagingDirectory)\macos\powershell-lts-$(Version)-osx-x64.zip" - tools/releaseBuild/generatePackgeSigning.ps1 -MacDeveloperFiles $pkgFiles -path "$(System.ArtifactsDirectory)\package.xml" - displayName: 'Generate macOS Package Signing Xml' - - - pwsh: | - Get-Content "$(System.ArtifactsDirectory)\package.xml" - displayName: 'Capture macOS signing xml' - # Diagnostics is not critical it passes every time it runs - continueOnError: true - - - task: PkgESCodeSign@10 - displayName: 'CodeSign $(System.ArtifactsDirectory)\package.xml' - env: - SYSTEM_ACCESSTOKEN: $(System.AccessToken) - inputs: - signConfigXml: '$(System.ArtifactsDirectory)\package.xml' - outPathRoot: '$(Build.StagingDirectory)\signedMacOSPackages' - binVersion: $(SigingVersion) - binVersionOverride: $(SigningVersionOverride) - condition: and(succeeded(), eq(variables['SHOULD_SIGN'], 'true')) + - template: EsrpSign.yml@ComplianceRepo + parameters: + buildOutputPath: $(Build.StagingDirectory)\macos + signOutputPath: $(Build.StagingDirectory)\signedMacOSPackages + certificateId: "CP-401337-Apple" + pattern: | + **\*.zip + useMinimatch: true + shouldSign: $(SHOULD_SIGN) - template: upload-final-results.yml parameters: @@ -120,9 +110,6 @@ jobs: ContainerName: '$(AzureVersion)' condition: and(succeeded(), eq(variables['SHOULD_SIGN'], 'true')) - - task: securedevelopmentteam.vss-secure-development-tools.build-task-antimalware.AntiMalware@3 - displayName: 'Run Defender Scan' - - task: ms.vss-governance-buildtask.governance-build-task-component-detection.ComponentGovernanceComponentDetection@0 displayName: 'Component Detection' inputs: diff --git a/tools/releaseBuild/azureDevOps/templates/mac.yml b/tools/releaseBuild/azureDevOps/templates/mac.yml index f38e9b63573..6690f678888 100644 --- a/tools/releaseBuild/azureDevOps/templates/mac.yml +++ b/tools/releaseBuild/azureDevOps/templates/mac.yml @@ -35,20 +35,14 @@ jobs: tools/releaseBuild/macOS/PowerShellPackageVsts.ps1 -location $(PowerShellRoot) -BootStrap displayName: 'Bootstrap VM' - - pwsh: | - Import-Module $(Build.SourcesDirectory)/build.psm1 -Force - New-NugetConfigFile -NugetFeedUrl $(AzDevOpsFeed) -UserName $(AzDevOpsFeedUserName) -ClearTextPAT $(AzDevOpsFeedPAT) -FeedName AzDevOpsFeed -Destination "$(PowerShellRoot)/src/Modules" - - if(-not (Test-Path "$(PowerShellRoot)/src/Modules/nuget.config")) - { - throw "nuget.config is not created" - } - displayName: 'Add nuget.config for AzDevOps feed for PSGallery modules ' + - template: /tools/releaseBuild/azureDevOps/templates/insert-nuget-config-azfeed.yml + parameters: + repoRoot: $(PowerShellRoot) - pwsh: | - $env:AZDEVOPSFEEDPAT = '$(AzDevOpsFeedPAT)' + $env:AzDevOpsFeedPAT2 = '$(AzDevOpsFeedPAT2)' $(Build.SourcesDirectory)/tools/releaseBuild/macOS/PowerShellPackageVsts.ps1 -ReleaseTag $(ReleaseTagVar) -Destination $(System.ArtifactsDirectory) -Symbols -location $(PowerShellRoot) -Build -ArtifactName macosBinResults - $env:AZDEVOPSFEEDPAT = $null + $env:AzDevOpsFeedPAT2 = $null displayName: 'Build' - task: ms.vss-governance-buildtask.governance-build-task-component-detection.ComponentGovernanceComponentDetection@0 diff --git a/tools/releaseBuild/azureDevOps/templates/nuget.yml b/tools/releaseBuild/azureDevOps/templates/nuget.yml index 0e81e337aed..b2702f162ee 100644 --- a/tools/releaseBuild/azureDevOps/templates/nuget.yml +++ b/tools/releaseBuild/azureDevOps/templates/nuget.yml @@ -12,19 +12,35 @@ jobs: timeoutInMinutes: 90 variables: - runCodesignValidationInjection: false - GenAPIToolPath: '$(System.ArtifactsDirectory)/GenAPI' - PackagePath: '$(System.ArtifactsDirectory)/UnifiedPackagePath' - winFxdPath: '$(System.ArtifactsDirectory)/winFxd' - winFxdWinDesktopPath: '$(System.ArtifactsDirectory)/winFxdWinDesktop' - linuxFxdPath: '$(System.ArtifactsDirectory)/linuxFxd' + - name: runCodesignValidationInjection + value: false + - name: build + value: ${{ parameters.buildName }} + - group: ESRP + - name: GenAPIToolPath + value: '$(System.ArtifactsDirectory)/GenAPI' + - name: PackagePath + value: '$(System.ArtifactsDirectory)/UnifiedPackagePath' + - name: winFxdPath + value: '$(System.ArtifactsDirectory)/winFxd' + - name: winFxdWinDesktopPath + value: '$(System.ArtifactsDirectory)/winFxdWinDesktop' + - name: linuxFxdPath + value: '$(System.ArtifactsDirectory)/linuxFxd' steps: - checkout: self clean: true + - checkout: ComplianceRepo + clean: true + + - template: SetVersionVariables.yml + parameters: + ReleaseTagVar: $(ReleaseTagVar) + - powershell: | - $content = Get-Content "$(Build.SourcesDirectory)/global.json" -Raw | ConvertFrom-Json + $content = Get-Content "$env:REPOROOT/global.json" -Raw | ConvertFrom-Json $vstsCommandString = "vso[task.setvariable variable=SDKVersion]$($content.sdk.version)" Write-Host "sending " + $vstsCommandString Write-Host "##$vstsCommandString" @@ -90,8 +106,8 @@ jobs: displayName: 'Install NuGet.exe' - powershell: | - Import-Module $env:BUILD_SOURCESDIRECTORY\build.psm1 - Import-Module $env:BUILD_SOURCESDIRECTORY\tools\packaging + Import-Module $env:REPOROOT\build.psm1 + Import-Module $env:REPOROOT\tools\packaging Find-Dotnet New-ILNugetPackage -PackagePath "$(PackagePath)" -PackageVersion "$(Version)" -WinFxdBinPath '$(winFxdPath)' -LinuxFxdBinPath '$(linuxFxdPath)' -GenAPIToolPath "$(GenAPIToolPath)" displayName: 'Create Nuget Package Folders' @@ -103,8 +119,8 @@ jobs: displayName: Capture fxd folders - powershell: | - Import-Module $env:BUILD_SOURCESDIRECTORY\build.psm1 - Import-Module $env:BUILD_SOURCESDIRECTORY\tools\packaging + Import-Module $env:REPOROOT\build.psm1 + Import-Module $env:REPOROOT\tools\packaging Find-Dotnet # Create unified package first New-GlobalToolNupkg -UnifiedPackage -LinuxBinPath "$(linuxFxdPath)" -WindowsBinPath "$(winFxdPath)" -WindowsDesktopBinPath "$(winFxdWinDesktopPath)" -PackageVersion "$(Version)" -DestinationPath "$(PackagePath)\globaltool" @@ -117,28 +133,15 @@ jobs: Get-ChildItem "$(PackagePath)" -Recurse displayName: Capture generated packages - - powershell: | - $packages = Get-ChildItem "$(PackagePath)\*.nupkg", "$(PackagePath)\globaltool\*.nupkg" | Select-Object -ExpandProperty FullName - - if($packages.Count -lt 1) - { - throw "No packages created" - } - - $(Build.SourcesDirectory)\tools\releaseBuild\generatePackgeSigning.ps1 -Path $(PackagePath)\NugetSigning.xml -NuPkgFiles $packages - displayName: Create signing file - - - task: PkgESCodeSign@10 - displayName: 'CodeSign Nuget Packages' - env: - SYSTEM_ACCESSTOKEN: $(System.AccessToken) - inputs: - signConfigXml: '$(PackagePath)\NugetSigning.xml' - inPathRoot: '$(PackagePath)' - outPathRoot: '$(System.ArtifactsDirectory)\signed' - binVersion: $(SigingVersion) - binVersionOverride: $(SigningVersionOverride) - condition: and(succeeded(), eq(variables['SHOULD_SIGN'], 'true')) + - template: EsrpSign.yml@ComplianceRepo + parameters: + buildOutputPath: $(PackagePath) + signOutputPath: $(System.ArtifactsDirectory)\signed + certificateId: "CP-401405" + pattern: | + **\*.nupkg + useMinimatch: true + shouldSign: $(SHOULD_SIGN) - pwsh: | if (-not (Test-Path '$(System.ArtifactsDirectory)\signed\')) { $null = New-Item -ItemType Directory -Path '$(System.ArtifactsDirectory)\signed\' } @@ -148,7 +151,7 @@ jobs: condition: eq(variables['SHOULD_SIGN'], 'false') - powershell: | - Import-Module $(Build.SourcesDirectory)\build.psm1 -Force + Import-Module "${env:REPOROOT}\build.psm1" -Force Get-ChildItem -Recurse "$(System.ArtifactsDirectory)\signed\*.nupkg" -Verbose | ForEach-Object { Start-NativeExecution -sb { nuget.exe verify -All $_.FullName } } displayName: Verify all packages are signed condition: eq(variables['SHOULD_SIGN'], 'true') diff --git a/tools/releaseBuild/azureDevOps/templates/windows-hosted-build.yml b/tools/releaseBuild/azureDevOps/templates/windows-hosted-build.yml index 3413896f0b2..cc05417b17b 100644 --- a/tools/releaseBuild/azureDevOps/templates/windows-hosted-build.yml +++ b/tools/releaseBuild/azureDevOps/templates/windows-hosted-build.yml @@ -31,10 +31,12 @@ jobs: parameters: ReleaseTagVar: $(ReleaseTagVar) - - template: insert-nuget-config-azfeed.yml - - template: cloneToOfficialPath.yml + - template: /tools/releaseBuild/azureDevOps/templates/insert-nuget-config-azfeed.yml + parameters: + repoRoot: $(PowerShellRoot) + - powershell: | $runtime = switch ($env:Architecture) diff --git a/tools/releaseBuild/azureDevOps/templates/windows-package-signing.yml b/tools/releaseBuild/azureDevOps/templates/windows-package-signing.yml index 571467a3fb5..070a0840991 100644 --- a/tools/releaseBuild/azureDevOps/templates/windows-package-signing.yml +++ b/tools/releaseBuild/azureDevOps/templates/windows-package-signing.yml @@ -8,15 +8,19 @@ jobs: ${{ parameters.parentJobs }} condition: succeeded() pool: - name: Package ES Standard Build + vmImage: windows-latest variables: - BuildConfiguration: release - BuildPlatform: any cpu + - name: DOTNET_SKIP_FIRST_TIME_EXPERIENCE + value: 1 + - group: ESRP steps: - checkout: self clean: true + - checkout: ComplianceRepo + clean: true + - template: shouldSign.yml - template: SetVersionVariables.yml parameters: @@ -36,36 +40,16 @@ jobs: # Diagnostics is not critical it passes every time it runs continueOnError: true - - powershell: | - $authenticodefiles = @( - "$(System.ArtifactsDirectory)\signed\PowerShell-$(Version)-win-x64.msi" - "$(System.ArtifactsDirectory)\signed\PowerShell-$(Version)-win-x86.msi" - ) - - $msixFiles = @( - "$(System.ArtifactsDirectory)\signed\PowerShell-$(Version)-win-x86.msix" - "$(System.ArtifactsDirectory)\signed\PowerShell-$(Version)-win-x64.msix" - "$(System.ArtifactsDirectory)\signed\PowerShell-$(Version)-win-arm32.msix" - "$(System.ArtifactsDirectory)\signed\PowerShell-$(Version)-win-arm64.msix" - ) - - tools/releaseBuild/generatePackgeSigning.ps1 -AuthenticodeFiles $authenticodeFiles -path "$(System.ArtifactsDirectory)\package.xml" -MsixCertType $env:MSIX_TYPE -MsixFiles $msixFiles - displayName: 'Generate Package Signing Xml' - - - powershell: | - Get-Content "$(System.ArtifactsDirectory)\package.xml" - displayName: 'Capture signing xml' - - - task: PkgESCodeSign@10 - displayName: 'CodeSign $(System.ArtifactsDirectory)\package.xml' - env: - SYSTEM_ACCESSTOKEN: $(System.AccessToken) - inputs: - signConfigXml: '$(System.ArtifactsDirectory)\package.xml' - outPathRoot: '$(Build.StagingDirectory)\signedPackages' - binVersion: $(SigingVersion) - binVersionOverride: $(SigningVersionOverride) - condition: and(succeeded(), eq(variables['SHOULD_SIGN'], 'true')) + - template: EsrpSign.yml@ComplianceRepo + parameters: + buildOutputPath: $(System.ArtifactsDirectory)\signed + signOutputPath: $(Build.StagingDirectory)\signedPackages + certificateId: "CP-230012" + pattern: | + **\*.msi + **\*.msix + useMinimatch: true + shouldSign: $(SHOULD_SIGN) - powershell: | new-item -itemtype Directory -path '$(Build.StagingDirectory)\signedPackages' @@ -110,8 +94,13 @@ jobs: msi: no msix: no - - task: securedevelopmentteam.vss-secure-development-tools.build-task-antimalware.AntiMalware@3 - displayName: 'Run Defender Scan' + - template: EsrpScan.yml@ComplianceRepo + parameters: + scanPath: $(Build.StagingDirectory) + pattern: | + **\*.msix + **\*.msi + **\*.zip - task: ms.vss-governance-buildtask.governance-build-task-component-detection.ComponentGovernanceComponentDetection@0 displayName: 'Component Detection' diff --git a/tools/releaseBuild/azureDevOps/templates/windows-packaging.yml b/tools/releaseBuild/azureDevOps/templates/windows-packaging.yml index a89a397f343..81eac8e5a11 100644 --- a/tools/releaseBuild/azureDevOps/templates/windows-packaging.yml +++ b/tools/releaseBuild/azureDevOps/templates/windows-packaging.yml @@ -60,7 +60,7 @@ jobs: - template: cloneToOfficialPath.yml - - powershell: | + - pwsh: | # cleanup previous install if((Test-Path "${env:ProgramFiles(x86)}\WiX Toolset xcopy")) { Remove-Item "${env:ProgramFiles(x86)}\WiX Toolset xcopy" -Recurse -Force @@ -68,7 +68,7 @@ jobs: $toolsDir = New-Item -ItemType Directory -Path '$(Build.ArtifactStagingDirectory)\tools' $wixUri = 'https://github.com/wixtoolset/wix3/releases/download/wix311rtm/wix311-binaries.zip' - Invoke-RestMethod -Uri $wixUri -OutFile '$(Build.ArtifactStagingDirectory)\tools\wix.zip' + Invoke-RestMethod -Uri $wixUri -OutFile '$(Build.ArtifactStagingDirectory)\tools\wix.zip' -MaximumRetryCount 5 -RetryIntervalSec 10 Import-Module '$(PowerShellRoot)/tools/releaseBuild/Images/microsoft_powershell_windowsservercore/wix.psm1' Install-WixZip -zipPath '$(Build.ArtifactStagingDirectory)\tools\wix.zip' @@ -124,13 +124,18 @@ jobs: "$($fullSymbolsFolder)\System.Management.Automation.dll" = "" } + $itemsToExclude = @( + # This package is retrieved from https://www.github.com/powershell/MarkdownRender + "$($fullSymbolsFolder)\Microsoft.PowerShell.MarkdownRender.dll" + ) + if ("$env:Architecture" -notlike 'fxdependent*') { $itemsToCopy += @{"$($fullSymbolsFolder)\pwsh.exe" = ""} } Write-Verbose -verbose "recusively copying $($itemsToCopyWithRecurse | out-string) to $filesToSignDirectory" - Copy-Item -Path $itemsToCopyWithRecurse -Destination $filesToSignDirectory -Recurse -verbose + Copy-Item -Path $itemsToCopyWithRecurse -Destination $filesToSignDirectory -Recurse -verbose -exclude $itemsToExclude foreach($pattern in $itemsToCopy.Keys) { $destinationFolder = Join-Path $filesToSignDirectory -ChildPath $itemsToCopy.$pattern @@ -153,6 +158,7 @@ jobs: **\*.ps1 **\*.exe useMinimatch: true + shouldSign: $(SHOULD_SIGN) - pwsh: | Import-Module $(PowerShellRoot)/build.psm1 -Force @@ -188,6 +194,7 @@ jobs: pattern: | **\*.dll useMinimatch: true + shouldSign: $(SHOULD_SIGN) - powershell: | Get-ChildItem '$(System.ArtifactsDirectory)\thirdPartySigned\*' diff --git a/tools/releaseBuild/setReleaseTag.ps1 b/tools/releaseBuild/setReleaseTag.ps1 index 1927eb7ae60..121425d963b 100644 --- a/tools/releaseBuild/setReleaseTag.ps1 +++ b/tools/releaseBuild/setReleaseTag.ps1 @@ -79,7 +79,7 @@ if($ReleaseTag -eq 'fromBranch' -or !$ReleaseTag) New-BuildInfoJson -ReleaseTag $releaseTag } } - elseif($branchOnly -eq 'master' -or $branchOnly -like '*dailytest*') + elseif(($branchOnly -eq 'master' -and $env:BUILD_REASON -ne 'Manual') -or $branchOnly -like '*dailytest*') { $isDaily = $true Write-Verbose "daily build" -Verbose diff --git a/tools/releaseBuild/signing.xml b/tools/releaseBuild/signing.xml index 017dc425e0a..11f63fe69cc 100644 --- a/tools/releaseBuild/signing.xml +++ b/tools/releaseBuild/signing.xml @@ -8,7 +8,6 @@ - diff --git a/tools/releaseTools.psm1 b/tools/releaseTools.psm1 index 7f181c3f522..1ea38df348c 100644 --- a/tools/releaseTools.psm1 +++ b/tools/releaseTools.psm1 @@ -352,7 +352,7 @@ function Get-ChangeLog PrintChangeLog -clSection $clBuildPackage -sectionTitle 'Build and Packaging Improvements' -Compress PrintChangeLog -clSection $clDocs -sectionTitle 'Documentation and Help Content' - Write-Output "[${version}]: https://github.com/PowerShell/PowerShell/compare/${$LastReleaseTag}...${ThisReleaseTag}`n" + Write-Output "[${version}]: https://github.com/PowerShell/PowerShell/compare/${LastReleaseTag}...${ThisReleaseTag}`n" } function PrintChangeLog($clSection, $sectionTitle, [switch] $Compress) { diff --git a/tools/windows/Reset-PWSHSystemPath.ps1 b/tools/windows/Reset-PWSHSystemPath.ps1 index 7a6a6d9e451..4b98e714525 100644 --- a/tools/windows/Reset-PWSHSystemPath.ps1 +++ b/tools/windows/Reset-PWSHSystemPath.ps1 @@ -32,11 +32,13 @@ Removes ALL PowerShell paths from the Machine level path. Good for running right before upgrading PowerShell. + .EXAMPLE .\Reset-PWSHSystemPath.ps1 -PathScope Machine, User, Process Removes all paths but the very last one when sorted in ascending order. Processes all path scopes including current process. + .EXAMPLE .\Reset-PWSHSystemPath.ps1 -PathScope Machine, User, Process -RemoveAllOccurencs @@ -53,7 +55,7 @@ ForEach ($PathScopeItem in $PathScope) { $AssembledNewPath = $NewPath = '' #From the current path scope. retrieve the array of paths that match the pathspec of PowerShell (to use as a filter) - $pathstoremove = @([Environment]::GetEnvironmentVariable("PATH","$PathScopeItem").split(';') | where { $_ -ilike "*\Program Files\Powershell\6*"}) + $pathstoremove = @([Environment]::GetEnvironmentVariable("PATH","$PathScopeItem").split(';') | Where-Object { $_ -ilike "*\Program Files\Powershell\6*"}) If (!$RemoveAllOccurences) { #If we are not removing all occurances of PowerShell paths, then remove the highest sorted path from the filter