Skip to content

Commit

Permalink
fix: analyzer warnings IDE0019, IDE0021, IDE0037 (#326)
Browse files Browse the repository at this point in the history
  • Loading branch information
daniel-akili authored Oct 28, 2022
1 parent 1b5f53a commit 2e911a5
Show file tree
Hide file tree
Showing 35 changed files with 77 additions and 141 deletions.
12 changes: 0 additions & 12 deletions .editorconfig
Original file line number Diff line number Diff line change
Expand Up @@ -744,12 +744,6 @@ dotnet_diagnostic.IDE0090.severity = suggestion
# IDE0065: 'using' directive placement
dotnet_diagnostic.IDE0065.severity = suggestion

# IDE0021: Use expression body for constructors
dotnet_diagnostic.IDE0021.severity = suggestion

# IDE0019: Use pattern matching to avoid 'as' followed by a 'null' check
dotnet_diagnostic.IDE0019.severity = suggestion

# IDE0160 and IDE0161: Namespace declaration preferences
dotnet_diagnostic.IDE0160.severity = suggestion
dotnet_diagnostic.IDE0161.severity = suggestion
Expand All @@ -760,9 +754,6 @@ dotnet_diagnostic.IDE1006.severity = suggestion
# IDE0060: Remove unused parameter
dotnet_diagnostic.IDE0060.severity = suggestion

# IDE0055: Formatting rule
dotnet_diagnostic.IDE0055.severity = suggestion

# IDE0025: Use expression body for properties
dotnet_diagnostic.IDE0025.severity = suggestion

Expand All @@ -772,9 +763,6 @@ dotnet_diagnostic.IDE0034.severity = suggestion
# IDE0036: Modifiers are not ordered
dotnet_diagnostic.IDE0036.severity = suggestion

# IDE0057: Substring can be simplified
dotnet_diagnostic.IDE0057.severity = suggestion

# IDE0078: Use pattern matching (may change code meaning)
dotnet_diagnostic.IDE0078.severity = suggestion

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ public static bool CheckDigest(string digest, bool throwError = true)
return false;
}

var algorithm = digest.Substring(0, indexOfColon);
var algorithm = digest[..indexOfColon];

if (!AlgorithmsSizes.ContainsKey(algorithm))
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -103,8 +103,8 @@ public static (string, string) SplitDockerDomain(string name)
}
else
{
domain = name.Substring(0, indexOfSlash);
reminder = name.Substring(indexOfSlash + 1);
domain = name[..indexOfSlash];
reminder = name[(indexOfSlash + 1)..];
}

if (domain == LEGACYDEFAULTDOMAIN)
Expand Down Expand Up @@ -133,7 +133,7 @@ public static DockerReference ParseFamiliarName(string name)
var tagSeparatorIndex = remainder.IndexOf(':');
if (tagSeparatorIndex > -1)
{
remoteName = remainder.Substring(0, tagSeparatorIndex);
remoteName = remainder[..tagSeparatorIndex];
}
else
{
Expand Down
10 changes: 5 additions & 5 deletions src/Microsoft.ComponentDetection.Common/PathUtilityService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -78,11 +78,11 @@ public bool IsRunningOnWindowsContainer

public static bool MatchesPattern(string searchPattern, ref FileSystemEntry fse)
{
if (searchPattern.StartsWith("*") && fse.FileName.EndsWith(searchPattern.Substring(1), StringComparison.OrdinalIgnoreCase))
if (searchPattern.StartsWith("*") && fse.FileName.EndsWith(searchPattern[1..], StringComparison.OrdinalIgnoreCase))
{
return true;
}
else if (searchPattern.EndsWith("*") && fse.FileName.StartsWith(searchPattern.Substring(0, searchPattern.Length - 1), StringComparison.OrdinalIgnoreCase))
else if (searchPattern.EndsWith("*") && fse.FileName.StartsWith(searchPattern[..^1], StringComparison.OrdinalIgnoreCase))
{
return true;
}
Expand Down Expand Up @@ -112,11 +112,11 @@ public bool IsFileBelowAnother(string aboveFilePath, string belowFilePath)

public bool MatchesPattern(string searchPattern, string fileName)
{
if (searchPattern.StartsWith("*") && fileName.EndsWith(searchPattern.Substring(1), StringComparison.OrdinalIgnoreCase))
if (searchPattern.StartsWith("*") && fileName.EndsWith(searchPattern[1..], StringComparison.OrdinalIgnoreCase))
{
return true;
}
else if (searchPattern.EndsWith("*") && fileName.StartsWith(searchPattern.Substring(0, searchPattern.Length - 1), StringComparison.OrdinalIgnoreCase))
else if (searchPattern.EndsWith("*") && fileName.StartsWith(searchPattern[..^1], StringComparison.OrdinalIgnoreCase))
{
return true;
}
Expand Down Expand Up @@ -187,7 +187,7 @@ public string ResolvePhysicalPathWindows(string path)

var result = resultBuilder.ToString();

result = result.StartsWith(LongPathPrefix) ? result.Substring(LongPathPrefix.Length) : result;
result = result.StartsWith(LongPathPrefix) ? result[LongPathPrefix.Length..] : result;

this.resolvedPaths.TryAdd(path, result);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,14 +25,14 @@ public static FilePatternMatcher GetFilePatternMatcher(IEnumerable<string> patte
{
if (pattern.StartsWith("*"))
{
var match = Expression.Constant(pattern.Substring(1), typeof(string));
var match = Expression.Constant(pattern[1..], typeof(string));
var right = Expression.Call(null, asSpan, match);
var combine = Expression.Call(null, endsWith, left, right, ordinalComparison);
predicates.Add(combine);
}
else if (pattern.EndsWith("*"))
{
var match = Expression.Constant(pattern.Substring(0, pattern.Length - 1), typeof(string));
var match = Expression.Constant(pattern[..^1], typeof(string));
var right = Expression.Call(null, asSpan, match);
var combine = Expression.Call(null, startsWith, left, right, ordinalComparison);
predicates.Add(combine);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,10 +41,7 @@ public SafeFileEnumerable(DirectoryInfo directory, IEnumerable<string> searchPat
}

public SafeFileEnumerable(DirectoryInfo directory, Func<FileInfo, bool> fileMatchingPredicate, ILogger logger, IPathUtilityService pathUtilityService, ExcludeDirectoryPredicate directoryExclusionPredicate, bool recursivelyScanDirectories = true, HashSet<string> previouslyEnumeratedDirectories = null)
: this(directory, new List<string> { "*" }, logger, pathUtilityService, directoryExclusionPredicate, recursivelyScanDirectories, previouslyEnumeratedDirectories)
{
this.fileMatchingPredicate = fileMatchingPredicate;
}
: this(directory, new List<string> { "*" }, logger, pathUtilityService, directoryExclusionPredicate, recursivelyScanDirectories, previouslyEnumeratedDirectories) => this.fileMatchingPredicate = fileMatchingPredicate;

public IEnumerator<MatchedFile> GetEnumerator()
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,7 @@ namespace Microsoft.ComponentDetection.Common.Telemetry.Attributes
{
public class TelemetryServiceAttribute : Attribute
{
public TelemetryServiceAttribute(string serviceType)
{
this.ServiceType = serviceType;
}
public TelemetryServiceAttribute(string serviceType) => this.ServiceType = serviceType;

public string ServiceType { get; }
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,7 @@ public abstract class BaseDetectionTelemetryRecord : IDetectionTelemetryRecord

private bool disposedValue = false;

protected BaseDetectionTelemetryRecord()
{
this.stopwatch.Start();
}
protected BaseDetectionTelemetryRecord() => this.stopwatch.Start();

public abstract string RecordName { get; }

Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
using System;
using System;
using System.Collections.Generic;
using System.Composition;
using System.Linq;
Expand All @@ -12,11 +12,9 @@ namespace Microsoft.ComponentDetection.Common.Telemetry
/// </summary>
public sealed class TelemetryRelay
{
private TelemetryRelay()
{
// For things not populating the telemetry services collection, let's not throw.
// For things not populating the telemetry services collection, let's not throw.
private TelemetryRelay() =>
TelemetryServices = Enumerable.Empty<ITelemetryService>();
}

[ImportMany]
public static IEnumerable<ITelemetryService> TelemetryServices { get; set; }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,10 @@

namespace Microsoft.ComponentDetection.Contracts.BcdeModels
{
public class LayerMappedLinuxComponents
{
public IEnumerable<LinuxComponent> LinuxComponents { get; set; }
public class LayerMappedLinuxComponents
{
public IEnumerable<LinuxComponent> LinuxComponents { get; set; }

public DockerLayer DockerLayer { get; set; }
}
public DockerLayer DockerLayer { get; set; }
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,7 @@ public GitComponent(Uri repositoryUrl, string commitHash)
}

public GitComponent(Uri repositoryUrl, string commitHash, string tag)
: this(repositoryUrl, commitHash)
{
this.Tag = tag;
}
: this(repositoryUrl, commitHash) => this.Tag = tag;

private GitComponent()
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,8 +40,7 @@ private GoComponent()

public override bool Equals(object other)
{
var otherComponent = other as GoComponent;
return otherComponent != null && this.Equals(otherComponent);
return other is GoComponent otherComponent && this.Equals(otherComponent);
}

public bool Equals(GoComponent other)
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
using System;
using System;
using System.Collections.Generic;
using System.Composition;
using System.IO;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -79,23 +79,23 @@ protected override async Task OnFileFound(ProcessRequest processRequest, IDictio
switch (fileExtension)
{
case ".mod":
{
this.Logger.LogVerbose("Found Go.mod: " + file.Location);
this.ParseGoModFile(singleFileComponentRecorder, file);
break;
}
{
this.Logger.LogVerbose("Found Go.mod: " + file.Location);
this.ParseGoModFile(singleFileComponentRecorder, file);
break;
}

case ".sum":
{
this.Logger.LogVerbose("Found Go.sum: " + file.Location);
this.ParseGoSumFile(singleFileComponentRecorder, file);
break;
}
{
this.Logger.LogVerbose("Found Go.sum: " + file.Location);
this.ParseGoSumFile(singleFileComponentRecorder, file);
break;
}

default:
{
throw new Exception("Unexpected file type detected in go detector");
}
{
throw new Exception("Unexpected file type detected in go detector");
}
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ private MavenComponent CreateMavenComponentFromFileLine(string line)
{
var equalsSeparatorIndex = line.IndexOf('=');
var isSingleLockfilePerProjectFormat = equalsSeparatorIndex != -1;
var componentDescriptor = isSingleLockfilePerProjectFormat ? line.Substring(0, equalsSeparatorIndex) : line;
var componentDescriptor = isSingleLockfilePerProjectFormat ? line[..equalsSeparatorIndex] : line;
var splits = componentDescriptor.Trim().Split(":");
var groupId = splits[0];
var artifactId = splits[1];
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -175,7 +175,7 @@ await this.DockerService.TryPullImageAsync(image, cancellationToken)))

var layers = await this.LinuxScanner.ScanLinuxAsync(kvp.Value.ImageId, internalContainerDetails.Layers, baseImageLayerCount, cancellationToken);

var components = layers.SelectMany(layer => layer.LinuxComponents.Select(linuxComponent => new DetectedComponent(linuxComponent, null, internalContainerDetails.Id, layer.DockerLayer.LayerIndex)));
var components = layers.SelectMany(layer => layer.LinuxComponents.Select(linuxComponent => new DetectedComponent(linuxComponent, null, internalContainerDetails.Id, layer.DockerLayer.LayerIndex)));
internalContainerDetails.Layers = layers.Select(layer => layer.DockerLayer);
var singleFileComponentRecorder = componentRecorder.CreateSingleFileComponentRecorder(kvp.Value.ImageId);
components.ToList().ForEach(detectedComponent => singleFileComponentRecorder.RegisterUsage(detectedComponent, true));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,7 @@ namespace Microsoft.ComponentDetection.Detectors.Maven
/// <typeparam name="T">Node type.</typeparam>
public class GraphNode<T>
{
public GraphNode(T value)
{
this.Value = value;
}
public GraphNode(T value) => this.Value = value;

public T Value { get; set; }

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -136,10 +136,7 @@ private void RecordDependencies(int position, string versionedComponent, ISingle
private class GraphNodeAtLevel<T> : GraphNode<T>
{
public GraphNodeAtLevel(int level, T value)
: base(value)
{
this.ParseLevel = level;
}
: base(value) => this.ParseLevel = level;

public int ParseLevel { get; }
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -122,11 +122,11 @@ private NpmAuthor GetAuthor(JToken authorToken, string packageName, string fileP
authorName = authorToken["name"]?.ToString();
authorEmail = authorToken["email"]?.ToString();

/*
* for parsing author in single string format.
* for e.g.
* "author": "John Doe <[email protected]> https://jd.com"
*/
/*
* for parsing author in single string format.
* for e.g.
* "author": "John Doe <[email protected]> https://jd.com"
*/
}
else if (authorMatch.Success)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,7 @@ public static class NpmComponentUtilities

public static void TraverseAndRecordComponents(JProperty currentDependency, ISingleFileComponentRecorder singleFileComponentRecorder, TypedComponent component, TypedComponent explicitReferencedDependency, string parentComponentId = null)
{
var devJValue = currentDependency.Value["dev"] as JValue;
var isDevDependency = devJValue != null && (bool)devJValue;
var isDevDependency = currentDependency.Value["dev"] is JValue devJValue && (bool)devJValue;
AddOrUpdateDetectedComponent(singleFileComponentRecorder, component, isDevDependency, parentComponentId, isExplicitReferencedDependency: string.Equals(component.Id, explicitReferencedDependency.Id));
}

Expand Down
11 changes: 4 additions & 7 deletions src/Microsoft.ComponentDetection.Detectors/pip/IPyPiClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -55,14 +55,11 @@ public class PyPiClient : IPyPiClient
/// </summary>
private MemoryCache cachedResponses = new MemoryCache(new MemoryCacheOptions { SizeLimit = DEFAULTCACHEENTRIES });

public PyPiClient()
public PyPiClient() => this.cacheTelemetry = new PypiCacheTelemetryRecord()
{
this.cacheTelemetry = new PypiCacheTelemetryRecord()
{
NumCacheHits = 0,
FinalCacheSize = 0,
};
}
NumCacheHits = 0,
FinalCacheSize = 0,
};

~PyPiClient()
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,7 @@ namespace Microsoft.ComponentDetection.Detectors.Pip
/// </summary>
public class PipGraphNode
{
public PipGraphNode(PipComponent value)
{
this.Value = value;
}
public PipGraphNode(PipComponent value) => this.Value = value;

public PipComponent Value { get; set; }

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -94,10 +94,10 @@ private static bool VersionValidForSpec(string version, string spec)
i++;
}

var op = spec.Substring(0, i);
var op = spec[..i];

var targetVer = new PythonVersion(version);
var specVer = new PythonVersion(spec.Substring(i));
var specVer = new PythonVersion(spec[i..]);

if (!targetVer.Valid)
{
Expand All @@ -106,7 +106,7 @@ private static bool VersionValidForSpec(string version, string spec)

if (!specVer.Valid)
{
throw new ArgumentException($"The version specification {spec.Substring(i)} is not a valid python version");
throw new ArgumentException($"The version specification {spec[i..]} is not a valid python version");
}

return op switch
Expand All @@ -118,7 +118,7 @@ private static bool VersionValidForSpec(string version, string spec)
"<=" => specVer >= targetVer,
">=" => targetVer >= specVer,
"!=" => targetVer.CompareTo(specVer) != 0,
"~=" => CheckEquality(version, spec.Substring(i), true),
"~=" => CheckEquality(version, spec[i..], true),
_ => false,
};
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,7 @@ namespace Microsoft.ComponentDetection.Detectors.Pnpm
[Export(typeof(IComponentDetector))]
public class PnpmComponentDetector : FileComponentDetector
{
public PnpmComponentDetector()
{
this.NeedsAutomaticRootDependencyCalculation = true;
}
public PnpmComponentDetector() => this.NeedsAutomaticRootDependencyCalculation = true;

public override string Id { get; } = "Pnpm";

Expand Down
Loading

0 comments on commit 2e911a5

Please sign in to comment.