From ff3edaa2e38d715b287bbb7046fd75a5ba5d1061 Mon Sep 17 00:00:00 2001 From: Ilya Date: Wed, 13 Feb 2019 16:51:05 +0500 Subject: [PATCH] Fix lgtm issues (#8843) Add some null checks Remove unused code --- .../commands/management/Navigation.cs | 2 +- .../Common/WebRequestPSCmdlet.Common.cs | 18 +++----- .../commands/utility/convert-HTML.cs | 4 +- .../common/BaseOutputtingCommand.cs | 46 +++++++++---------- .../common/DisplayDatabase/typeDataQuery.cs | 6 --- .../cimSupport/cmdletization/ScriptWriter.cs | 10 ---- .../engine/CoreAdapter.cs | 2 +- .../engine/InitialSessionState.cs | 3 +- .../engine/debugger/debugger.cs | 2 +- .../remoting/commands/PSRemotingCmdlet.cs | 3 +- .../help/DefaultCommandHelpObjectBuilder.cs | 6 +-- .../help/HelpSystem.cs | 1 - .../help/UpdatableHelpCommandBase.cs | 2 +- .../namespaces/FileSystemProvider.cs | 10 ++-- 14 files changed, 43 insertions(+), 72 deletions(-) diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/Navigation.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/Navigation.cs index 1144f536eb..0258181ec0 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/Navigation.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/Navigation.cs @@ -1451,7 +1451,7 @@ namespace Microsoft.PowerShell.Commands } else { - if (nameMatcher.IsMatch(drive.Name)) + if (nameMatcher != null && nameMatcher.IsMatch(drive.Name)) addDrive = true; } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs index a669a3123d..1a23725416 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs @@ -1193,29 +1193,24 @@ namespace Microsoft.PowerShell.Commands content = psBody.BaseObject; } - if (content is FormObject) + if (content is FormObject form) { - FormObject form = content as FormObject; SetRequestContent(request, form.Fields); } - else if (content is IDictionary && request.Method != HttpMethod.Get) + else if (content is IDictionary dictionary && request.Method != HttpMethod.Get) { - IDictionary dictionary = content as IDictionary; SetRequestContent(request, dictionary); } - else if (content is XmlNode) + else if (content is XmlNode xmlNode) { - XmlNode xmlNode = content as XmlNode; SetRequestContent(request, xmlNode); } - else if (content is Stream) + else if (content is Stream stream) { - Stream stream = content as Stream; SetRequestContent(request, stream); } - else if (content is byte[]) + else if (content is byte[] bytes) { - byte[] bytes = content as byte[]; SetRequestContent(request, bytes); } else if (content is MultipartFormDataContent multipartFormDataContent) @@ -1225,7 +1220,8 @@ namespace Microsoft.PowerShell.Commands } else { - SetRequestContent(request, + SetRequestContent( + request, (string)LanguagePrimitives.ConvertTo(content, typeof(string), CultureInfo.InvariantCulture)); } } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/convert-HTML.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/convert-HTML.cs index af48588e02..1fde5f1cf1 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/convert-HTML.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/convert-HTML.cs @@ -364,7 +364,7 @@ namespace Microsoft.PowerShell.Commands { string label = p.GetEntry(ConvertHTMLParameterDefinitionKeys.LabelEntryKey) as string; string alignment = p.GetEntry(ConvertHTMLParameterDefinitionKeys.AlignmentEntryKey) as string; - + // Accept the width both as a string and as an int. string width; int? widthNum = p.GetEntry(ConvertHTMLParameterDefinitionKeys.WidthEntryKey) as int?; @@ -542,7 +542,6 @@ namespace Microsoft.PowerShell.Commands WriteObject(""); _isTHWritten = false; - _propertyCollector = new StringCollection(); } /// @@ -760,7 +759,6 @@ namespace Microsoft.PowerShell.Commands /// List of incoming objects to compare. /// private bool _isTHWritten; - private StringCollection _propertyCollector; private List _propertyMshParameterList; private List _resolvedNameMshParameters; // private string ResourcesBaseName = "ConvertHTMLStrings"; diff --git a/src/System.Management.Automation/FormatAndOutput/common/BaseOutputtingCommand.cs b/src/System.Management.Automation/FormatAndOutput/common/BaseOutputtingCommand.cs index 0b5e3c238d..13b1194181 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/BaseOutputtingCommand.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/BaseOutputtingCommand.cs @@ -692,21 +692,19 @@ namespace Microsoft.PowerShell.Commands.Internal.Format int cellCount; // scratch variable foreach (PacketInfoData o in objects) { - FormatEntryData fed = o as FormatEntryData; - - if (fed == null) - continue; - - TableRowEntry tre = fed.formatEntryInfo as TableRowEntry; - int kk = 0; - - foreach (FormatPropertyField fpf in tre.formatPropertyFieldList) + if (o is FormatEntryData fed) { - cellCount = _lo.DisplayCells.Length(fpf.propertyValue); - if (widths[kk] < cellCount) - widths[kk] = cellCount; + TableRowEntry tre = fed.formatEntryInfo as TableRowEntry; + int kk = 0; - kk++; + foreach (FormatPropertyField fpf in tre.formatPropertyFieldList) + { + cellCount = _lo.DisplayCells.Length(fpf.propertyValue); + if (widths[kk] < cellCount) + widths[kk] = cellCount; + + kk++; + } } } @@ -729,19 +727,17 @@ namespace Microsoft.PowerShell.Commands.Internal.Format foreach (PacketInfoData o in objects) { - FormatEntryData fed = o as FormatEntryData; - - if (fed == null) - continue; - - WideViewEntry wve = fed.formatEntryInfo as WideViewEntry; - FormatPropertyField fpf = wve.formatPropertyField as FormatPropertyField; - - if (!string.IsNullOrEmpty(fpf.propertyValue)) + if (o is FormatEntryData fed) { - cellCount = _lo.DisplayCells.Length(fpf.propertyValue); - if (cellCount > maxLen) - maxLen = cellCount; + WideViewEntry wve = fed.formatEntryInfo as WideViewEntry; + FormatPropertyField fpf = wve.formatPropertyField as FormatPropertyField; + + if (!string.IsNullOrEmpty(fpf.propertyValue)) + { + cellCount = _lo.DisplayCells.Length(fpf.propertyValue); + if (cellCount > maxLen) + maxLen = cellCount; + } } } diff --git a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataQuery.cs b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataQuery.cs index bd682da287..6eb86bc7e4 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataQuery.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataQuery.cs @@ -226,10 +226,6 @@ namespace Microsoft.PowerShell.Commands.Internal.Format PSPropertyExpressionResult expressionResult; bool retVal = DisplayCondition.Evaluate(currentObject, ex, out expressionResult); - if (expressionResult != null && expressionResult.Exception != null) - { - _failedResultsList.Add(expressionResult); - } return retVal; } @@ -239,8 +235,6 @@ namespace Microsoft.PowerShell.Commands.Internal.Format private Collection _typeNameHierarchy; private bool _useInheritance; - private List _failedResultsList = new List(); - private int _bestMatchIndex = BestMatchIndexUndefined; private TypeMatchItem _bestMatchItem; diff --git a/src/System.Management.Automation/cimSupport/cmdletization/ScriptWriter.cs b/src/System.Management.Automation/cimSupport/cmdletization/ScriptWriter.cs index 0b9225dd5e..4f75164db8 100644 --- a/src/System.Management.Automation/cimSupport/cmdletization/ScriptWriter.cs +++ b/src/System.Management.Automation/cimSupport/cmdletization/ScriptWriter.cs @@ -237,9 +237,6 @@ function __cmdletization_BindCommonParameters return verb + "-" + noun; } - private readonly List _aliasesToExport = new List(); - private readonly List _functionsToExport = new List(); - private string GetCmdletAttributes(CommonCmdletMetadata cmdletMetadata) { // Generate the script for the Alias and Obsolete Attribute if any is declared in CDXML @@ -247,7 +244,6 @@ function __cmdletization_BindCommonParameters if (cmdletMetadata.Aliases != null) { attributes.Append("[Alias('" + string.Join("','", cmdletMetadata.Aliases.Select(alias => CodeGeneration.EscapeSingleQuotedStringContent(alias))) + "')]"); - _aliasesToExport.AddRange(cmdletMetadata.Aliases); } if (cmdletMetadata.Obsolete != null) @@ -1924,8 +1920,6 @@ Microsoft.PowerShell.Core\Export-ModuleMember -Function '{1}' -Alias '*' CmdletEndBlockTemplate, /* 0 */ this.GetHelpDirectiveForExternalHelp(), /* 1 */ CodeGeneration.EscapeSingleQuotedStringContent(commandMetadata.Name)); - - _functionsToExport.Add(commandMetadata.Name); } private static void AddPassThruParameter(IDictionary commonParameters, InstanceCmdletMetadata instanceCmdletMetadata) @@ -2022,8 +2016,6 @@ Microsoft.PowerShell.Core\Export-ModuleMember -Function '{1}' -Alias '*' CmdletEndBlockTemplate, /* 0 */ this.GetHelpDirectiveForExternalHelp(), /* 1 */ CodeGeneration.EscapeSingleQuotedStringContent(commandMetadata.Name)); - - _functionsToExport.Add(commandMetadata.Name); } private string GetOutputAttributeForGetCmdlet() @@ -2109,8 +2101,6 @@ Microsoft.PowerShell.Core\Export-ModuleMember -Function '{1}' -Alias '*' CmdletEndBlockTemplate, /* 0 */ this.GetHelpDirectiveForExternalHelp(), /* 1 */ CodeGeneration.EscapeSingleQuotedStringContent(commandMetadata.Name)); - - _functionsToExport.Add(commandMetadata.Name); } private static object s_enumCompilationLock = new object(); diff --git a/src/System.Management.Automation/engine/CoreAdapter.cs b/src/System.Management.Automation/engine/CoreAdapter.cs index dccdbb872b..1699a2374c 100644 --- a/src/System.Management.Automation/engine/CoreAdapter.cs +++ b/src/System.Management.Automation/engine/CoreAdapter.cs @@ -3793,7 +3793,7 @@ namespace System.Management.Automation FieldInfo field = adapterData.member as FieldInfo; if (adapterData.useReflection) { - return field.GetValue(property.baseObject); + return field?.GetValue(property.baseObject); } else { diff --git a/src/System.Management.Automation/engine/InitialSessionState.cs b/src/System.Management.Automation/engine/InitialSessionState.cs index f8dcd5e0d4..852c7e8815 100644 --- a/src/System.Management.Automation/engine/InitialSessionState.cs +++ b/src/System.Management.Automation/engine/InitialSessionState.cs @@ -1220,8 +1220,7 @@ namespace System.Management.Automation.Runspaces { foreach (var element in items) { - var typeEntry = element as SessionStateTypeEntry; - if (typeEntry.TypeData != null) + if (element is SessionStateTypeEntry typeEntry && typeEntry.TypeData != null) { // Skip type file entries. _internalCollection.Add(element); diff --git a/src/System.Management.Automation/engine/debugger/debugger.cs b/src/System.Management.Automation/engine/debugger/debugger.cs index 55889abc64..b78c8b66aa 100644 --- a/src/System.Management.Automation/engine/debugger/debugger.cs +++ b/src/System.Management.Automation/engine/debugger/debugger.cs @@ -1744,7 +1744,7 @@ namespace System.Management.Automation // Update the prompt to the debug prompt if (hadDefaultPrompt) { - int index = originalPromptString.IndexOf("\"", StringComparison.OrdinalIgnoreCase); + int index = originalPromptString.IndexOf('"', StringComparison.OrdinalIgnoreCase); if (index > -1) { // Fix up prompt. diff --git a/src/System.Management.Automation/engine/remoting/commands/PSRemotingCmdlet.cs b/src/System.Management.Automation/engine/remoting/commands/PSRemotingCmdlet.cs index 21edc96446..5f2ba937dc 100644 --- a/src/System.Management.Automation/engine/remoting/commands/PSRemotingCmdlet.cs +++ b/src/System.Management.Automation/engine/remoting/commands/PSRemotingCmdlet.cs @@ -3317,9 +3317,8 @@ namespace Microsoft.PowerShell.Commands try { - if (ShouldUseSteppablePipelineOnServer) + if (ShouldUseSteppablePipelineOnServer && pipeline is RemotePipeline rPipeline) { - RemotePipeline rPipeline = pipeline as RemotePipeline; rPipeline.SetIsNested(true); rPipeline.SetIsSteppable(true); } diff --git a/src/System.Management.Automation/help/DefaultCommandHelpObjectBuilder.cs b/src/System.Management.Automation/help/DefaultCommandHelpObjectBuilder.cs index 5d23c18800..335d37691a 100644 --- a/src/System.Management.Automation/help/DefaultCommandHelpObjectBuilder.cs +++ b/src/System.Management.Automation/help/DefaultCommandHelpObjectBuilder.cs @@ -63,9 +63,8 @@ namespace System.Management.Automation.Help obj.TypeNames.Add("CmdletHelpInfo"); obj.TypeNames.Add("HelpInfo"); - if (commandInfo is CmdletInfo) + if (commandInfo is CmdletInfo cmdletInfo) { - CmdletInfo cmdletInfo = commandInfo as CmdletInfo; bool common = false; if (cmdletInfo.Parameters != null) { @@ -101,9 +100,8 @@ namespace System.Management.Automation.Help obj.Properties.Add(new PSNoteProperty("PSSnapIn", cmdletInfo.PSSnapIn)); } - else if (commandInfo is FunctionInfo) + else if (commandInfo is FunctionInfo funcInfo) { - FunctionInfo funcInfo = commandInfo as FunctionInfo; bool common = HasCommonParameters(funcInfo.Parameters); obj.Properties.Add(new PSNoteProperty("CommonParameters", common)); diff --git a/src/System.Management.Automation/help/HelpSystem.cs b/src/System.Management.Automation/help/HelpSystem.cs index f0c00daf23..b36d5254a5 100644 --- a/src/System.Management.Automation/help/HelpSystem.cs +++ b/src/System.Management.Automation/help/HelpSystem.cs @@ -392,7 +392,6 @@ namespace System.Management.Automation /// helpInfos is not null or empty. private IEnumerable ForwardHelp(HelpInfo helpInfo, HelpRequest helpRequest) { - Collection result = new Collection(); // findout if this helpInfo needs to be processed further.. if (helpInfo.ForwardHelpCategory == HelpCategory.None && string.IsNullOrEmpty(helpInfo.ForwardTarget)) { diff --git a/src/System.Management.Automation/help/UpdatableHelpCommandBase.cs b/src/System.Management.Automation/help/UpdatableHelpCommandBase.cs index b3f8654d4e..05634917a5 100644 --- a/src/System.Management.Automation/help/UpdatableHelpCommandBase.cs +++ b/src/System.Management.Automation/help/UpdatableHelpCommandBase.cs @@ -823,10 +823,10 @@ namespace Microsoft.PowerShell.Commands /// Message to log. internal void LogMessage(string message) { +#if !CORECLR // TODO:CORECLR Uncomment when we add PSEtwLog support List details = new List(); details.Add(message); -#if !CORECLR // TODO:CORECLR Uncomment when we add PSEtwLog support PSEtwLog.LogPipelineExecutionDetailEvent(MshLog.GetLogContext(Context, Context.CurrentCommandProcessor.Command.MyInvocation), details); #endif } diff --git a/src/System.Management.Automation/namespaces/FileSystemProvider.cs b/src/System.Management.Automation/namespaces/FileSystemProvider.cs index a9794b2c2e..b46bc33546 100644 --- a/src/System.Management.Automation/namespaces/FileSystemProvider.cs +++ b/src/System.Management.Automation/namespaces/FileSystemProvider.cs @@ -2136,7 +2136,7 @@ namespace Microsoft.PowerShell.Commands if (ShouldProcess(resource, action)) { bool isDirectory = false; - string strTargetPath = value.ToString(); + string strTargetPath = value?.ToString(); if (string.IsNullOrEmpty(strTargetPath)) { @@ -2310,7 +2310,7 @@ namespace Microsoft.PowerShell.Commands if (ShouldProcess(resource, action)) { bool isDirectory = false; - string strTargetPath = value.ToString(); + string strTargetPath = value?.ToString(); bool exists = false; @@ -4383,7 +4383,7 @@ namespace Microsoft.PowerShell.Commands fStream = AlternateDataStreamUtilities.CreateFileStream(file.FullName, streamName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); } #endif - long remainingFileSize = fStream.Length; + long remainingFileSize = fStream != null ? fStream.Length : 0; do { if (Stopping) @@ -8071,8 +8071,10 @@ namespace Microsoft.PowerShell.Commands targetDir = Encoding.Unicode.GetString(reparseDataBufferMountPoint.PathBuffer, reparseDataBufferMountPoint.SubstituteNameOffset, reparseDataBufferMountPoint.SubstituteNameLength); } - if (targetDir.StartsWith(NonInterpretedPathPrefix, StringComparison.OrdinalIgnoreCase)) + if (targetDir != null && targetDir.StartsWith(NonInterpretedPathPrefix, StringComparison.OrdinalIgnoreCase)) + { targetDir = targetDir.Substring(NonInterpretedPathPrefix.Length); + } return targetDir; }