This commit is contained in:
cobya 2024-09-16 09:27:20 -07:00
Родитель 48299d735d
Коммит 7528c8f4fd
267 изменённых файлов: 1205 добавлений и 1154 удалений

Просмотреть файл

@ -54,7 +54,7 @@ extends:
displayName: Install .NET
inputs:
packageType: 'sdk'
version: '8.0.x'
version: '6.0.x'
# https://eng.ms/docs/cloud-ai-platform/devdiv/one-engineering-system-1es/1es-docs/1es-security-configuration/configuration-guides/pat-burndown-guidance#workarounds-for-tasks-that-do-not-yet-support-wif-service-connection
- task: AzureCLI@2

Просмотреть файл

@ -1,7 +1,7 @@
{
"$schema": "https://raw.githubusercontent.com/devcontainers/spec/main/schemas/devContainer.base.schema.json",
"name": "Component Detection",
"image": "mcr.microsoft.com/vscode/devcontainers/dotnet:8.0",
"image": "mcr.microsoft.com/vscode/devcontainers/dotnet:6.0",
"runArgs": ["--init"],
"extensions": [
"eamodio.gitlens",

Просмотреть файл

@ -679,24 +679,6 @@ dotnet_diagnostic.CA1848.severity = suggestion
# JSON002: Probable JSON string detected
dotnet_diagnostic.JSON002.severity = suggestion
# IDE0290: Use primary constructor
dotnet_diagnostic.IDE0290.severity = suggestion
# IDE0305: Simplify collection initialization
dotnet_diagnostic.IDE0305.severity = suggestion
# SYSLIB1045: Convert to 'GeneratedRegexAttribute'.
dotnet_diagnostic.SYSLIB1045.severity = suggestion
# CA1859: Use concrete types when possible for improved performance
dotnet_diagnostic.CA1859.severity = suggestion
# CA1851: Possible multiple enumerations of 'IEnumerable' collection
dotnet_diagnostic.CA1851.severity = suggestion
# CA1861: Avoid constant arrays as arguments
dotnet_diagnostic.CA1861.severity = suggestion
# Workaround for https://github.com/dotnet/roslyn-analyzers/issues/5628
[Program.cs]
dotnet_diagnostic.ca1812.severity = none

Просмотреть файл

@ -1,7 +1,7 @@
<Project>
<PropertyGroup Label="Build">
<TargetFramework>net8.0</TargetFramework>
<TargetFramework>net6.0</TargetFramework>
<LangVersion>latest</LangVersion>
<ManagePackageVersionsCentrally>true</ManagePackageVersionsCentrally>
<EnforceCodeStyleInBuild>true</EnforceCodeStyleInBuild>

Просмотреть файл

@ -9,14 +9,14 @@
<PackageVersion Include="CommandLineParser" Version="2.9.1" />
<PackageVersion Include="Docker.DotNet" Version="3.125.15" />
<PackageVersion Include="FluentAssertions" Version="6.12.0" />
<PackageVersion Include="FluentAssertions.Analyzers" Version="0.32.0" />
<PackageVersion Include="Microsoft.Extensions.Caching.Memory" Version="8.0.0" />
<PackageVersion Include="Microsoft.Extensions.DependencyInjection" Version="8.0.0" />
<PackageVersion Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="8.0.1" />
<PackageVersion Include="Microsoft.Extensions.Http" Version="8.0.0" />
<PackageVersion Include="Microsoft.Extensions.Logging" Version="8.0.0" />
<PackageVersion Include="FluentAssertions.Analyzers" Version="0.26.0" />
<PackageVersion Include="Microsoft.Extensions.Caching.Memory" Version="7.0.0" />
<PackageVersion Include="Microsoft.Extensions.DependencyInjection" Version="7.0.0" />
<PackageVersion Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="7.0.0" />
<PackageVersion Include="Microsoft.Extensions.Http" Version="7.0.0" />
<PackageVersion Include="Microsoft.Extensions.Logging" Version="7.0.0" />
<PackageVersion Include="Microsoft.SourceLink.GitHub" Version="8.0.0" />
<PackageVersion Include="Microsoft.VisualStudio.Threading.Analyzers" Version="17.11.20" />
<PackageVersion Include="Microsoft.VisualStudio.Threading.Analyzers" Version="17.8.14" />
<PackageVersion Include="DotNet.Glob" Version="2.1.1" />
<PackageVersion Include="MinVer" Version="5.0.0" />
<PackageVersion Include="Moq" Version="4.18.4" />
@ -33,25 +33,26 @@
<PackageVersion Include="Polly" Version="8.4.0" />
<PackageVersion Include="SemanticVersioning" Version="2.0.2" />
<PackageVersion Include="Serilog" Version="4.0.0" />
<PackageVersion Include="Serilog.Extensions.Logging" Version="8.0.0" />
<PackageVersion Include="Serilog.Extensions.Logging" Version="7.0.0" />
<PackageVersion Include="Serilog.Sinks.Async" Version="1.5.0" />
<PackageVersion Include="Serilog.Sinks.Console" Version="5.0.1" />
<PackageVersion Include="Serilog.Sinks.File" Version="5.0.0" />
<PackageVersion Include="Serilog.Sinks.Map" Version="1.0.2" />
<PackageVersion Include="Spectre.Console" Version="0.49.1" />
<PackageVersion Include="Spectre.Console.Cli" Version="0.49.1" />
<PackageVersion Include="Spectre.Console" Version="0.48.0" />
<PackageVersion Include="Spectre.Console.Cli" Version="0.48.0" />
<PackageVersion Include="Spectre.Console.Cli.Extensions.DependencyInjection" Version="0.2.0" />
<PackageVersion Include="Spectre.Console.Testing" Version="0.49.1" />
<PackageVersion Include="Spectre.Console.Testing" Version="0.48.0" />
<PackageVersion Include="StyleCop.Analyzers" Version="1.2.0-beta.556" />
<PackageVersion Include="System.Memory" Version="4.5.5" />
<PackageVersion Include="System.Reactive" Version="6.0.1" />
<PackageVersion Include="System.Runtime.Loader" Version="4.3.0" />
<PackageVersion Include="System.Text.Json" Version="8.0.4" />
<PackageVersion Include="System.Threading.Tasks.Dataflow" Version="8.0.0" />
<PackageVersion Include="System.Text.Json" Version="6.0.9" />
<PackageVersion Include="System.Threading.Tasks.Dataflow" Version="7.0.0" />
<PackageVersion Include="Tomlyn.Signed" Version="0.17.0" />
<PackageVersion Include="yamldotnet" Version="15.1.6" />
<PackageVersion Include="Faker.net" Version="2.0.163" />
<PackageVersion Include="Valleysoft.DockerfileModel" Version="1.1.1" />
<!-- Fix security alerts -->
<PackageVersion Include="System.Formats.Asn1" Version="6.0.1" />
</ItemGroup>

Просмотреть файл

@ -1,6 +1,6 @@
{
"sdk": {
"version": "8.0.401",
"version": "6.0.422",
"rollForward": "latestMinor"
}
}

Просмотреть файл

@ -1,4 +1,4 @@
namespace Microsoft.ComponentDetection.Common;
namespace Microsoft.ComponentDetection.Common;
using System;
using System.Threading;
@ -21,7 +21,10 @@ public static class AsyncExecution
/// <exception cref="TimeoutException">Thrown when the execution does not complete within the timeout.</exception>
public static async Task<T> ExecuteWithTimeoutAsync<T>(Func<Task<T>> toExecute, TimeSpan timeout, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(toExecute);
if (toExecute == null)
{
throw new ArgumentNullException(nameof(toExecute));
}
var work = Task.Run(toExecute);
@ -45,7 +48,10 @@ public static class AsyncExecution
/// <exception cref="TimeoutException">Thrown when the execution does not complete within the timeout.</exception>
public static async Task ExecuteVoidWithTimeoutAsync(Action toExecute, TimeSpan timeout, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(toExecute);
if (toExecute == null)
{
throw new ArgumentNullException(nameof(toExecute));
}
var work = Task.Run(toExecute, cancellationToken);
var completedInTime = await Task.Run(() => work.Wait(timeout));

Просмотреть файл

@ -1,4 +1,4 @@
namespace Microsoft.ComponentDetection.Common;
namespace Microsoft.ComponentDetection.Common;
public class Column
{

Просмотреть файл

@ -20,8 +20,8 @@ public class CommandLineInvocationService : ICommandLineInvocationService
/// <inheritdoc/>
public async Task<bool> CanCommandBeLocatedAsync(string command, IEnumerable<string> additionalCandidateCommands = null, DirectoryInfo workingDirectory = null, params string[] parameters)
{
additionalCandidateCommands ??= [];
parameters ??= [];
additionalCandidateCommands ??= Enumerable.Empty<string>();
parameters ??= Array.Empty<string>();
var allCommands = new[] { command }.Concat(additionalCandidateCommands);
if (!this.commandLocatableCache.TryGetValue(command, out var validCommand))
{

Просмотреть файл

@ -1,4 +1,4 @@
namespace Microsoft.ComponentDetection.Common;
namespace Microsoft.ComponentDetection.Common;
using System.Collections.Generic;
using Microsoft.ComponentDetection.Contracts.TypedComponent;

Просмотреть файл

@ -1,4 +1,4 @@
namespace Microsoft.ComponentDetection.Common;
namespace Microsoft.ComponentDetection.Common;
using System.IO;
using Microsoft.ComponentDetection.Contracts;

Просмотреть файл

@ -1,4 +1,4 @@
namespace Microsoft.ComponentDetection.Common;
namespace Microsoft.ComponentDetection.Common;
using System;
using System.Collections;

Просмотреть файл

@ -1,4 +1,4 @@
namespace Microsoft.ComponentDetection.Common;
namespace Microsoft.ComponentDetection.Common;
using System;
using System.Collections.Generic;

Просмотреть файл

@ -16,7 +16,7 @@ using Microsoft.Extensions.Logging;
public class ComponentRecorder : IComponentRecorder
{
private readonly ConcurrentBag<SingleFileComponentRecorder> singleFileRecorders = [];
private readonly ConcurrentBag<SingleFileComponentRecorder> singleFileRecorders = new ConcurrentBag<SingleFileComponentRecorder>();
private readonly bool enableManualTrackingOfExplicitReferences;
@ -38,7 +38,7 @@ public class ComponentRecorder : IComponentRecorder
IEnumerable<DetectedComponent> detectedComponents;
if (this.singleFileRecorders == null)
{
return [];
return Enumerable.Empty<DetectedComponent>();
}
detectedComponents = this.singleFileRecorders
@ -68,7 +68,7 @@ public class ComponentRecorder : IComponentRecorder
{
if (this.singleFileRecorders == null)
{
return [];
return Enumerable.Empty<string>();
}
return this.singleFileRecorders
@ -162,7 +162,10 @@ public class ComponentRecorder : IComponentRecorder
bool? isDevelopmentDependency = null,
DependencyScope? dependencyScope = null)
{
ArgumentNullException.ThrowIfNull(detectedComponent);
if (detectedComponent == null)
{
throw new ArgumentNullException(paramName: nameof(detectedComponent));
}
if (detectedComponent.Component == null)
{
@ -170,14 +173,14 @@ public class ComponentRecorder : IComponentRecorder
}
#if DEBUG
if (detectedComponent.DependencyRoots?.Count == 0)
if (detectedComponent.DependencyRoots?.Any() ?? false)
{
this.logger?.LogWarning("Detector should not populate DetectedComponent.DependencyRoots!");
this.logger.LogWarning("Detector should not populate DetectedComponent.DependencyRoots!");
}
if (detectedComponent.DevelopmentDependency.HasValue)
{
this.logger?.LogWarning("Detector should not populate DetectedComponent.DevelopmentDependency!");
this.logger.LogWarning("Detector should not populate DetectedComponent.DevelopmentDependency!");
}
#endif
@ -192,7 +195,10 @@ public class ComponentRecorder : IComponentRecorder
public void RegisterPackageParseFailure(string skippedComponent)
{
ArgumentNullException.ThrowIfNull(skippedComponent);
if (skippedComponent == null)
{
throw new ArgumentNullException(paramName: nameof(skippedComponent));
}
_ = this.skippedComponentsInternal[skippedComponent] = default;
}

Просмотреть файл

@ -4,7 +4,6 @@ using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using Microsoft.ComponentDetection.Contracts;
using Microsoft.ComponentDetection.Contracts.BcdeModels;
@ -14,8 +13,6 @@ namespace Microsoft.ComponentDetection.Common.DependencyGraph;
internal class DependencyGraph : IDependencyGraph
{
private static readonly CompositeFormat MissingNodeFormat = CompositeFormat.Parse(Resources.MissingNodeInDependencyGraph);
private readonly ConcurrentDictionary<string, ComponentRefNode> componentNodes;
private readonly bool enableManualTrackingOfExplicitReferences;
@ -30,11 +27,14 @@ internal class DependencyGraph : IDependencyGraph
public void AddComponent(ComponentRefNode componentNode, string parentComponentId = null)
{
ArgumentNullException.ThrowIfNull(componentNode);
if (componentNode == null)
{
throw new ArgumentNullException(nameof(componentNode));
}
if (string.IsNullOrWhiteSpace(componentNode.Id))
{
throw new ArgumentNullException(nameof(componentNode), "Invalid component node id");
throw new ArgumentNullException(nameof(componentNode.Id), "Invalid component node id");
}
this.componentNodes.AddOrUpdate(componentNode.Id, componentNode, (key, currentNode) =>
@ -77,10 +77,10 @@ internal class DependencyGraph : IDependencyGraph
if (!this.componentNodes.TryGetValue(componentId, out var componentRef))
{
throw new ArgumentException(string.Format(null, MissingNodeFormat, componentId), paramName: nameof(componentId));
throw new ArgumentException(string.Format(Resources.MissingNodeInDependencyGraph, componentId), paramName: nameof(componentId));
}
IList<string> explicitReferencedDependencyIds = [];
IList<string> explicitReferencedDependencyIds = new List<string>();
this.GetExplicitReferencedDependencies(componentRef, explicitReferencedDependencyIds, new HashSet<string>());
@ -129,7 +129,7 @@ internal class DependencyGraph : IDependencyGraph
if (!this.componentNodes.TryGetValue(componentId, out var componentRef))
{
// this component isn't in the graph, so it has no ancestors
return [];
return new List<string>();
}
// store the component id and the depth we found it at
@ -189,7 +189,7 @@ internal class DependencyGraph : IDependencyGraph
if (!this.componentNodes.TryGetValue(parentComponentId, out var parentComponentRefNode))
{
throw new ArgumentException(string.Format(null, MissingNodeFormat, parentComponentId), nameof(parentComponentId));
throw new ArgumentException(string.Format(Resources.MissingNodeInDependencyGraph, parentComponentId), nameof(parentComponentId));
}
parentComponentRefNode.DependencyIds.Add(componentId);

Просмотреть файл

@ -1,4 +1,4 @@
namespace Microsoft.ComponentDetection.Common;
namespace Microsoft.ComponentDetection.Common;
using Microsoft.ComponentDetection.Contracts.BcdeModels;

Просмотреть файл

@ -1,4 +1,4 @@
namespace Microsoft.ComponentDetection.Common;
namespace Microsoft.ComponentDetection.Common;
using System.Collections.Generic;
using System.Diagnostics;

Просмотреть файл

@ -26,8 +26,6 @@
// short-identifier := /[a-f0-9]{6,64}/
namespace Microsoft.ComponentDetection.Common;
using System;
using System.Diagnostics.CodeAnalysis;
using Microsoft.ComponentDetection.Contracts;
public static class DockerReferenceUtility
@ -122,7 +120,6 @@ public static class DockerReferenceUtility
return (domain, remainder);
}
[SuppressMessage("Globalization", "CA1308:Normalize strings to uppercase", Justification = "Explicitly checks for character case.")]
public static DockerReference ParseFamiliarName(string name)
{
if (DockerRegex.AnchoredIdentifierRegexp.IsMatch(name))
@ -143,7 +140,7 @@ public static class DockerReferenceUtility
remoteName = remainder;
}
if (!string.Equals(remoteName.ToLowerInvariant(), remoteName, StringComparison.InvariantCulture))
if (remoteName.ToLower() != remoteName)
{
throw new ReferenceNameContainsUppercaseException(name);
}

Просмотреть файл

@ -171,7 +171,7 @@ public class DockerService : IDockerService
CreatedAt = imageInspectResponse.Created,
BaseImageDigest = baseImageDigest,
BaseImageRef = baseImageRef,
Layers = layers ?? [],
Layers = layers ?? Enumerable.Empty<DockerLayer>(),
};
}
catch (Exception e)
@ -212,19 +212,19 @@ public class DockerService : IDockerService
NetworkDisabled = true,
HostConfig = new HostConfig
{
CapDrop =
[
CapDrop = new List<string>
{
"all",
],
SecurityOpt =
[
},
SecurityOpt = new List<string>
{
"no-new-privileges",
],
Binds =
[
},
Binds = new List<string>
{
$"{Path.GetTempPath()}:/tmp",
"/var/run/docker.sock:/var/run/docker.sock",
],
},
},
};
return await Client.Containers.CreateContainerAsync(parameters, cancellationToken);

Просмотреть файл

@ -1,4 +1,4 @@
namespace Microsoft.ComponentDetection.Common;
namespace Microsoft.ComponentDetection.Common;
public interface IConsoleWritingService
{

Просмотреть файл

@ -1,4 +1,4 @@
namespace Microsoft.ComponentDetection.Common;
namespace Microsoft.ComponentDetection.Common;
using System.Collections.Generic;
using System.IO;

Просмотреть файл

@ -1,4 +1,4 @@
namespace Microsoft.ComponentDetection.Common;
namespace Microsoft.ComponentDetection.Common;
using System;
using System.IO;
@ -56,6 +56,6 @@ public class LazyComponentStream : IComponentStream
this.logger.LogWarning(e, "Unhandled exception caught when trying to open {FileName}", this.fileInfo.FullName);
}
return [];
return Array.Empty<byte>();
}
}

Просмотреть файл

@ -1,4 +1,4 @@
namespace Microsoft.ComponentDetection.Common;
namespace Microsoft.ComponentDetection.Common;
using System.IO;

Просмотреть файл

@ -23,12 +23,12 @@ public class PathUtilityService : IPathUtilityService
public static bool MatchesPattern(string searchPattern, ref FileSystemEntry fse)
{
if (searchPattern.StartsWith('*') && fse.FileName.EndsWith(searchPattern.AsSpan()[1..], StringComparison.OrdinalIgnoreCase))
if (searchPattern.StartsWith("*") && fse.FileName.EndsWith(searchPattern.AsSpan()[1..], StringComparison.OrdinalIgnoreCase))
{
return true;
}
if (searchPattern.EndsWith('*') && fse.FileName.StartsWith(searchPattern.AsSpan()[..^1], StringComparison.OrdinalIgnoreCase))
if (searchPattern.EndsWith("*") && fse.FileName.StartsWith(searchPattern.AsSpan()[..^1], StringComparison.OrdinalIgnoreCase))
{
return true;
}
@ -49,12 +49,12 @@ public class PathUtilityService : IPathUtilityService
public bool MatchesPattern(string searchPattern, string fileName)
{
if (searchPattern.StartsWith('*') && fileName.EndsWith(searchPattern[1..], StringComparison.OrdinalIgnoreCase))
if (searchPattern.StartsWith("*") && fileName.EndsWith(searchPattern[1..], StringComparison.OrdinalIgnoreCase))
{
return true;
}
if (searchPattern.EndsWith('*') && fileName.StartsWith(searchPattern[..^1], StringComparison.OrdinalIgnoreCase))
if (searchPattern.EndsWith("*") && fileName.StartsWith(searchPattern[..^1], StringComparison.OrdinalIgnoreCase))
{
return true;
}

Просмотреть файл

@ -1,4 +1,4 @@
namespace Microsoft.ComponentDetection.Common;
namespace Microsoft.ComponentDetection.Common;
using System;
using System.Collections.Generic;
@ -13,24 +13,24 @@ public static class PatternMatchingUtility
public static FilePatternMatcher GetFilePatternMatcher(IEnumerable<string> patterns)
{
var ordinalComparison = Expression.Constant(StringComparison.Ordinal, typeof(StringComparison));
var asSpan = typeof(MemoryExtensions).GetMethod("AsSpan", BindingFlags.Public | BindingFlags.Static, null, CallingConventions.Standard, [typeof(string)], []);
var equals = typeof(MemoryExtensions).GetMethod("Equals", BindingFlags.Public | BindingFlags.Static, null, CallingConventions.Standard, [typeof(ReadOnlySpan<char>), typeof(ReadOnlySpan<char>), typeof(StringComparison)], []);
var startsWith = typeof(MemoryExtensions).GetMethod("StartsWith", BindingFlags.Public | BindingFlags.Static, null, CallingConventions.Standard, [typeof(ReadOnlySpan<char>), typeof(ReadOnlySpan<char>), typeof(StringComparison)], []);
var endsWith = typeof(MemoryExtensions).GetMethod("EndsWith", BindingFlags.Public | BindingFlags.Static, null, CallingConventions.Standard, [typeof(ReadOnlySpan<char>), typeof(ReadOnlySpan<char>), typeof(StringComparison)], []);
var asSpan = typeof(MemoryExtensions).GetMethod("AsSpan", BindingFlags.Public | BindingFlags.Static, null, CallingConventions.Standard, new[] { typeof(string) }, Array.Empty<ParameterModifier>());
var equals = typeof(MemoryExtensions).GetMethod("Equals", BindingFlags.Public | BindingFlags.Static, null, CallingConventions.Standard, new[] { typeof(ReadOnlySpan<char>), typeof(ReadOnlySpan<char>), typeof(StringComparison) }, Array.Empty<ParameterModifier>());
var startsWith = typeof(MemoryExtensions).GetMethod("StartsWith", BindingFlags.Public | BindingFlags.Static, null, CallingConventions.Standard, new[] { typeof(ReadOnlySpan<char>), typeof(ReadOnlySpan<char>), typeof(StringComparison) }, Array.Empty<ParameterModifier>());
var endsWith = typeof(MemoryExtensions).GetMethod("EndsWith", BindingFlags.Public | BindingFlags.Static, null, CallingConventions.Standard, new[] { typeof(ReadOnlySpan<char>), typeof(ReadOnlySpan<char>), typeof(StringComparison) }, Array.Empty<ParameterModifier>());
var predicates = new List<Expression>();
var left = Expression.Parameter(typeof(ReadOnlySpan<char>), "fileName");
foreach (var pattern in patterns)
{
if (pattern.StartsWith('*'))
if (pattern.StartsWith("*"))
{
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('*'))
else if (pattern.EndsWith("*"))
{
var match = Expression.Constant(pattern[..^1], typeof(string));
var right = Expression.Call(null, asSpan, match);

Просмотреть файл

@ -1,4 +1,4 @@
namespace Microsoft.ComponentDetection.Common;
namespace Microsoft.ComponentDetection.Common;
using System;
using System.Collections;
@ -42,11 +42,11 @@ public class SafeFileEnumerable : IEnumerable<MatchedFile>
}
public SafeFileEnumerable(DirectoryInfo directory, Func<FileInfo, bool> fileMatchingPredicate, ILogger logger, IPathUtilityService pathUtilityService, ExcludeDirectoryPredicate directoryExclusionPredicate, bool recursivelyScanDirectories = true, HashSet<string> previouslyEnumeratedDirectories = null)
: this(directory, ["*"], 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()
{
var previouslyEnumeratedDirectories = this.enumeratedDirectories ?? [];
var previouslyEnumeratedDirectories = this.enumeratedDirectories ?? new HashSet<string>();
var fse = new FileSystemEnumerable<MatchedFile>(
this.directory.FullName,

Просмотреть файл

@ -1,4 +1,4 @@
namespace Microsoft.ComponentDetection.Common;
namespace Microsoft.ComponentDetection.Common;
public enum ScanType
{

Просмотреть файл

@ -1,4 +1,4 @@
namespace Microsoft.ComponentDetection.Common;
namespace Microsoft.ComponentDetection.Common;
using System;
using System.Collections.Generic;

Просмотреть файл

@ -1,4 +1,4 @@
namespace Microsoft.ComponentDetection.Common.Telemetry.Attributes;
namespace Microsoft.ComponentDetection.Common.Telemetry.Attributes;
using System;

Просмотреть файл

@ -1,4 +1,4 @@
namespace Microsoft.ComponentDetection.Common.Telemetry;
namespace Microsoft.ComponentDetection.Common.Telemetry;
using System;
using System.Collections.Concurrent;

Просмотреть файл

@ -1,4 +1,4 @@
namespace Microsoft.ComponentDetection.Common.Telemetry;
namespace Microsoft.ComponentDetection.Common.Telemetry;
using Microsoft.ComponentDetection.Common.Telemetry.Records;

Просмотреть файл

@ -1,4 +1,4 @@
namespace Microsoft.ComponentDetection.Common.Telemetry.Records;
namespace Microsoft.ComponentDetection.Common.Telemetry.Records;
using System;
using System.Diagnostics;

Просмотреть файл

@ -1,4 +1,4 @@
namespace Microsoft.ComponentDetection.Common.Telemetry.Records;
namespace Microsoft.ComponentDetection.Common.Telemetry.Records;
using System;

Просмотреть файл

@ -1,4 +1,4 @@
namespace Microsoft.ComponentDetection.Common.Telemetry.Records;
namespace Microsoft.ComponentDetection.Common.Telemetry.Records;
using System;
using Microsoft.ComponentDetection.Contracts;

Просмотреть файл

@ -1,4 +1,4 @@
namespace Microsoft.ComponentDetection.Common.Telemetry.Records;
namespace Microsoft.ComponentDetection.Common.Telemetry.Records;
using System.Runtime.CompilerServices;

Просмотреть файл

@ -1,4 +1,4 @@
namespace Microsoft.ComponentDetection.Common.Telemetry.Records;
namespace Microsoft.ComponentDetection.Common.Telemetry.Records;
public class DetectorExecutionTelemetryRecord : BaseDetectionTelemetryRecord
{

Просмотреть файл

@ -1,4 +1,4 @@
namespace Microsoft.ComponentDetection.Common.Telemetry.Records;
namespace Microsoft.ComponentDetection.Common.Telemetry.Records;
public class GoGraphTelemetryRecord : BaseDetectionTelemetryRecord
{

Просмотреть файл

@ -1,4 +1,4 @@
namespace Microsoft.ComponentDetection.Common.Telemetry.Records;
namespace Microsoft.ComponentDetection.Common.Telemetry.Records;
using System;

Просмотреть файл

@ -1,4 +1,4 @@
namespace Microsoft.ComponentDetection.Common.Telemetry.Records;
namespace Microsoft.ComponentDetection.Common.Telemetry.Records;
public class LinuxContainerDetectorImageDetectionFailed : BaseDetectionTelemetryRecord
{

Просмотреть файл

@ -1,4 +1,4 @@
namespace Microsoft.ComponentDetection.Common.Telemetry.Records;
namespace Microsoft.ComponentDetection.Common.Telemetry.Records;
public class LinuxContainerDetectorMissingRepoNameAndTagRecord : BaseDetectionTelemetryRecord
{

Просмотреть файл

@ -1,4 +1,4 @@
namespace Microsoft.ComponentDetection.Common.Telemetry.Records;
namespace Microsoft.ComponentDetection.Common.Telemetry.Records;
public class LinuxContainerDetectorMissingVersion : BaseDetectionTelemetryRecord
{

Просмотреть файл

@ -1,4 +1,4 @@
namespace Microsoft.ComponentDetection.Common.Telemetry.Records;
namespace Microsoft.ComponentDetection.Common.Telemetry.Records;
public class LinuxContainerDetectorTimeout : BaseDetectionTelemetryRecord
{

Просмотреть файл

@ -1,4 +1,4 @@
namespace Microsoft.ComponentDetection.Common.Telemetry.Records;
namespace Microsoft.ComponentDetection.Common.Telemetry.Records;
public class LinuxContainerDetectorUnsupportedOs : BaseDetectionTelemetryRecord
{

Просмотреть файл

@ -1,4 +1,4 @@
namespace Microsoft.ComponentDetection.Common.Telemetry.Records;
namespace Microsoft.ComponentDetection.Common.Telemetry.Records;
public class LinuxScannerTelemetryRecord : BaseDetectionTelemetryRecord
{

Просмотреть файл

@ -1,4 +1,4 @@
namespace Microsoft.ComponentDetection.Common.Telemetry.Records;
namespace Microsoft.ComponentDetection.Common.Telemetry.Records;
public class LoadComponentDetectorsTelemetryRecord : BaseDetectionTelemetryRecord
{

Просмотреть файл

@ -1,4 +1,4 @@
namespace Microsoft.ComponentDetection.Common.Telemetry.Records;
namespace Microsoft.ComponentDetection.Common.Telemetry.Records;
using System;

Просмотреть файл

@ -1,4 +1,4 @@
namespace Microsoft.ComponentDetection.Common.Telemetry.Records;
namespace Microsoft.ComponentDetection.Common.Telemetry.Records;
public class PypiCacheTelemetryRecord : BaseDetectionTelemetryRecord
{

Просмотреть файл

@ -1,4 +1,4 @@
namespace Microsoft.ComponentDetection.Common.Telemetry.Records;
namespace Microsoft.ComponentDetection.Common.Telemetry.Records;
using System.Net;

Просмотреть файл

@ -1,4 +1,4 @@
namespace Microsoft.ComponentDetection.Common.Telemetry.Records;
namespace Microsoft.ComponentDetection.Common.Telemetry.Records;
public class PypiMaxRetriesReachedTelemetryRecord : BaseDetectionTelemetryRecord
{

Просмотреть файл

@ -1,4 +1,4 @@
namespace Microsoft.ComponentDetection.Common.Telemetry.Records;
namespace Microsoft.ComponentDetection.Common.Telemetry.Records;
using System.Net;

Просмотреть файл

@ -1,4 +1,4 @@
namespace Microsoft.ComponentDetection.Common.Telemetry.Records;
namespace Microsoft.ComponentDetection.Common.Telemetry.Records;
public class RustCrateDetectorTelemetryRecord : BaseDetectionTelemetryRecord
{

Просмотреть файл

@ -1,4 +1,4 @@
namespace Microsoft.ComponentDetection.Common.Telemetry.Records;
namespace Microsoft.ComponentDetection.Common.Telemetry.Records;
public class RustGraphTelemetryRecord : BaseDetectionTelemetryRecord
{

Просмотреть файл

@ -1,4 +1,4 @@
using System;
using System;
using System.Runtime.CompilerServices;
[assembly: InternalsVisibleTo("Microsoft.ComponentDetection.Orchestrator")]

Просмотреть файл

@ -1,4 +1,4 @@
namespace Microsoft.ComponentDetection.Common.Telemetry;
namespace Microsoft.ComponentDetection.Common.Telemetry;
public enum TelemetryMode
{

Просмотреть файл

@ -1,7 +1,8 @@
namespace Microsoft.ComponentDetection.Common.Telemetry;
namespace Microsoft.ComponentDetection.Common.Telemetry;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.ComponentDetection.Common.Telemetry.Records;
@ -15,7 +16,7 @@ public sealed class TelemetryRelay
// For things not populating the telemetry services collection, let's not throw.
private TelemetryRelay() =>
this.telemetryServices = [];
this.telemetryServices = Enumerable.Empty<ITelemetryService>();
/// <summary>
/// Gets a value indicating whether or not the telemetry relay has been shutdown.
@ -75,7 +76,7 @@ public sealed class TelemetryRelay
public void SetTelemetryMode(TelemetryMode mode)
{
foreach (var telemetryService in this.telemetryServices ?? [])
foreach (var telemetryService in this.telemetryServices ?? Enumerable.Empty<ITelemetryService>())
{
telemetryService.SetMode(mode);
}

Просмотреть файл

@ -1,4 +1,4 @@
namespace Microsoft.ComponentDetection.Common;
namespace Microsoft.ComponentDetection.Common;
public enum WarnOnAlertSeverity
{

Просмотреть файл

@ -1,4 +1,4 @@
namespace Microsoft.ComponentDetection.Contracts.BcdeModels;
namespace Microsoft.ComponentDetection.Contracts.BcdeModels;
using System;
using System.Collections.Generic;

Просмотреть файл

@ -1,4 +1,4 @@
namespace Microsoft.ComponentDetection.Contracts.BcdeModels;
namespace Microsoft.ComponentDetection.Contracts.BcdeModels;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;

Просмотреть файл

@ -1,4 +1,4 @@
namespace Microsoft.ComponentDetection.Contracts.BcdeModels;
namespace Microsoft.ComponentDetection.Contracts.BcdeModels;
using System.Collections.Generic;

Просмотреть файл

@ -1,4 +1,4 @@
namespace Microsoft.ComponentDetection.Contracts.BcdeModels;
namespace Microsoft.ComponentDetection.Contracts.BcdeModels;
using System.Collections.Generic;

Просмотреть файл

@ -1,4 +1,4 @@
namespace Microsoft.ComponentDetection.Contracts.BcdeModels;
namespace Microsoft.ComponentDetection.Contracts.BcdeModels;
using System.Collections.Generic;
using Newtonsoft.Json;

Просмотреть файл

@ -1,4 +1,4 @@
namespace Microsoft.ComponentDetection.Contracts.BcdeModels;
namespace Microsoft.ComponentDetection.Contracts.BcdeModels;
/// <summary>Used to communicate Dependency Scope of Component.
/// Currently only populated for Maven component.

Просмотреть файл

@ -1,4 +1,4 @@
namespace Microsoft.ComponentDetection.Contracts.BcdeModels;
namespace Microsoft.ComponentDetection.Contracts.BcdeModels;
using System.Collections.Generic;
using Microsoft.ComponentDetection.Contracts.TypedComponent;

Просмотреть файл

@ -1,4 +1,4 @@
namespace Microsoft.ComponentDetection.Contracts.BcdeModels;
namespace Microsoft.ComponentDetection.Contracts.BcdeModels;
using System;
using System.Collections.Generic;

Просмотреть файл

@ -18,16 +18,16 @@ public class DetectedComponent
public DetectedComponent(TypedComponent.TypedComponent component, IComponentDetector detector = null, int? containerDetailsId = null, int? containerLayerId = null)
{
this.Component = component;
this.FilePaths = [];
this.FilePaths = new HashSet<string>();
this.DetectedBy = detector;
this.ContainerDetailIds = [];
this.ContainerDetailIds = new HashSet<int>();
this.ContainerLayerIds = new Dictionary<int, IEnumerable<int>>();
if (containerDetailsId.HasValue)
{
this.ContainerDetailIds.Add(containerDetailsId.Value);
if (containerLayerId.HasValue)
{
this.ContainerLayerIds.Add(containerDetailsId.Value, [containerLayerId.Value]);
this.ContainerLayerIds.Add(containerDetailsId.Value, new List<int>() { containerLayerId.Value });
}
}
}

Просмотреть файл

@ -1,4 +1,4 @@
namespace Microsoft.ComponentDetection.Contracts;
namespace Microsoft.ComponentDetection.Contracts;
/// <summary>Class of detector, the names of which are converted into categories for all default detectors.</summary>
public enum DetectorClass

Просмотреть файл

@ -46,7 +46,7 @@ public abstract class FileComponentDetector : IComponentDetector
/// <summary>
/// Gets the folder names that will be skipped by the Component Detector.
/// </summary>
protected virtual IList<string> SkippedFolders => [];
protected virtual IList<string> SkippedFolders => new List<string> { };
/// <summary>
/// Gets or sets the active scan request -- only populated after a ScanDirectoryAsync is invoked. If ScanDirectoryAsync is overridden,
@ -56,12 +56,12 @@ public abstract class FileComponentDetector : IComponentDetector
public virtual bool NeedsAutomaticRootDependencyCalculation { get; protected set; }
protected Dictionary<string, string> Telemetry { get; set; } = [];
protected Dictionary<string, string> Telemetry { get; set; } = new Dictionary<string, string>();
/// <summary>
/// List of any any additional properties as key-value pairs that we would like to capture for the detector.
/// </summary>
public List<(string PropertyKey, string PropertyValue)> AdditionalProperties { get; set; } = [];
public List<(string PropertyKey, string PropertyValue)> AdditionalProperties { get; set; } = new List<(string PropertyKey, string PropertyValue)>();
protected IObservable<IComponentStream> ComponentStreams { get; private set; }

Просмотреть файл

@ -1,4 +1,4 @@
namespace Microsoft.ComponentDetection.Contracts;
namespace Microsoft.ComponentDetection.Contracts;
using System.IO;

Просмотреть файл

@ -1,4 +1,4 @@
namespace Microsoft.ComponentDetection.Contracts;
namespace Microsoft.ComponentDetection.Contracts;
using System;
using System.Collections.Generic;

Просмотреть файл

@ -1,4 +1,4 @@
namespace Microsoft.ComponentDetection.Contracts;
namespace Microsoft.ComponentDetection.Contracts;
using System;
using System.Collections.Generic;

Просмотреть файл

@ -1,6 +1,7 @@
namespace Microsoft.ComponentDetection.Contracts;
using System.Collections.Generic;
using System.Linq;
using Microsoft.ComponentDetection.Contracts.BcdeModels;
/// <summary>
@ -16,7 +17,7 @@ public class IndividualDetectorScanResult
/// <summary>
/// Gets or sets the list of containers found during the scan.
/// </summary>
public IEnumerable<ContainerDetails> ContainerDetails { get; set; } = [];
public IEnumerable<ContainerDetails> ContainerDetails { get; set; } = Enumerable.Empty<ContainerDetails>();
/// <summary>
/// Gets or sets any additional telemetry details for the scan.

Просмотреть файл

@ -1,4 +1,4 @@
namespace Microsoft.ComponentDetection.Contracts.Internal;
namespace Microsoft.ComponentDetection.Contracts.Internal;
using System;

Просмотреть файл

@ -1,4 +1,4 @@
namespace Microsoft.ComponentDetection.Contracts.Internal;
namespace Microsoft.ComponentDetection.Contracts.Internal;
public class ProcessRequest
{

Просмотреть файл

@ -1,4 +1,4 @@
namespace Microsoft.ComponentDetection.Contracts;
namespace Microsoft.ComponentDetection.Contracts;
/// <summary>
/// Represents the configuration for the kill switch.

Просмотреть файл

@ -1,4 +1,4 @@
namespace Microsoft.ComponentDetection.Contracts;
namespace Microsoft.ComponentDetection.Contracts;
/// <summary>Code used to communicate the state of a scan after completion.</summary>
public enum ProcessingResultCode

Просмотреть файл

@ -1,4 +1,4 @@
namespace Microsoft.ComponentDetection.Contracts.TypedComponent;
namespace Microsoft.ComponentDetection.Contracts.TypedComponent;
using System.Runtime.Serialization;

Просмотреть файл

@ -1,4 +1,4 @@
namespace Microsoft.ComponentDetection.Contracts.TypedComponent;
namespace Microsoft.ComponentDetection.Contracts.TypedComponent;
public class CondaComponent : TypedComponent
{

Просмотреть файл

@ -1,4 +1,4 @@
namespace Microsoft.ComponentDetection.Contracts.TypedComponent;
namespace Microsoft.ComponentDetection.Contracts.TypedComponent;
using System;

Просмотреть файл

@ -1,4 +1,4 @@
namespace Microsoft.ComponentDetection.Contracts.TypedComponent;
namespace Microsoft.ComponentDetection.Contracts.TypedComponent;
using System;
using PackageUrl;

Просмотреть файл

@ -1,6 +1,5 @@
namespace Microsoft.ComponentDetection.Contracts.TypedComponent;
using System;
using PackageUrl;
public class LinuxComponent : TypedComponent
@ -64,26 +63,26 @@ public class LinuxComponent : TypedComponent
private bool IsUbuntu()
{
return this.Distribution.Equals("UBUNTU", StringComparison.OrdinalIgnoreCase);
return this.Distribution.ToUpperInvariant() == "UBUNTU";
}
private bool IsDebian()
{
return this.Distribution.Equals("DEBIAN", StringComparison.OrdinalIgnoreCase);
return this.Distribution.ToUpperInvariant() == "DEBIAN";
}
private bool IsCentOS()
{
return this.Distribution.Equals("CENTOS", StringComparison.OrdinalIgnoreCase);
return this.Distribution.ToUpperInvariant() == "CENTOS";
}
private bool IsFedora()
{
return this.Distribution.Equals("FEDORA", StringComparison.OrdinalIgnoreCase);
return this.Distribution.ToUpperInvariant() == "FEDORA";
}
private bool IsRHEL()
{
return this.Distribution.Equals("RED HAT ENTERPRISE LINUX", StringComparison.OrdinalIgnoreCase);
return this.Distribution.ToUpperInvariant() == "RED HAT ENTERPRISE LINUX";
}
}

Просмотреть файл

@ -1,4 +1,4 @@
namespace Microsoft.ComponentDetection.Contracts.TypedComponent;
namespace Microsoft.ComponentDetection.Contracts.TypedComponent;
using PackageUrl;

Просмотреть файл

@ -1,4 +1,4 @@
namespace Microsoft.ComponentDetection.Contracts.TypedComponent;
namespace Microsoft.ComponentDetection.Contracts.TypedComponent;
using Microsoft.ComponentDetection.Contracts.Internal;
using PackageUrl;

Просмотреть файл

@ -1,4 +1,4 @@
namespace Microsoft.ComponentDetection.Contracts.TypedComponent;
namespace Microsoft.ComponentDetection.Contracts.TypedComponent;
using PackageUrl;

Просмотреть файл

@ -1,4 +1,4 @@
namespace Microsoft.ComponentDetection.Contracts.TypedComponent;
namespace Microsoft.ComponentDetection.Contracts.TypedComponent;
using System.Collections.Generic;
using PackageUrl;

Просмотреть файл

@ -1,4 +1,4 @@
namespace Microsoft.ComponentDetection.Contracts.TypedComponent;
namespace Microsoft.ComponentDetection.Contracts.TypedComponent;
using System;

Просмотреть файл

@ -29,11 +29,11 @@ public class PodComponentDetector : FileComponentDetector
public override string Id { get; } = "CocoaPods";
public override IEnumerable<string> Categories => [Enum.GetName(typeof(DetectorClass), DetectorClass.CocoaPods)];
public override IEnumerable<string> Categories => new[] { Enum.GetName(typeof(DetectorClass), DetectorClass.CocoaPods) };
public override IList<string> SearchPatterns { get; } = ["Podfile.lock"];
public override IList<string> SearchPatterns { get; } = new List<string> { "Podfile.lock" };
public override IEnumerable<ComponentType> SupportedComponentTypes { get; } = [ComponentType.Pod, ComponentType.Git];
public override IEnumerable<ComponentType> SupportedComponentTypes { get; } = new[] { ComponentType.Pod, ComponentType.Git };
public override int Version { get; } = 2;
@ -225,7 +225,7 @@ public class PodComponentDetector : FileComponentDetector
foreach (var pod in podDependencies)
{
// Add all the dependencies to the map, without duplicates
dependenciesMap.TryAdd(pod.Key, []);
dependenciesMap.TryAdd(pod.Key, new HashSet<string>());
foreach (var dependency in pod.Value)
{

Просмотреть файл

@ -26,13 +26,13 @@ public class ConanLockComponentDetector : FileComponentDetector, IDefaultOffComp
public override string Id => "ConanLock";
public override IList<string> SearchPatterns => ["conan.lock"];
public override IList<string> SearchPatterns => new List<string> { "conan.lock" };
public override IEnumerable<ComponentType> SupportedComponentTypes => [ComponentType.Conan];
public override IEnumerable<ComponentType> SupportedComponentTypes => new[] { ComponentType.Conan };
public override int Version { get; } = 1;
public override IEnumerable<string> Categories => ["Conan"];
public override IEnumerable<string> Categories => new List<string> { "Conan" };
protected override async Task OnFileFoundAsync(ProcessRequest processRequest, IDictionary<string, string> detectorArgs, CancellationToken cancellationToken = default)
{
@ -52,8 +52,9 @@ public class ConanLockComponentDetector : FileComponentDetector, IDefaultOffComp
var packagesDictionary = conanLock.GraphLock.Nodes;
var explicitReferencedDependencies = new HashSet<string>();
var developmentDependencies = new HashSet<string>();
if (packagesDictionary.Remove("0", out var rootNode))
if (packagesDictionary.ContainsKey("0"))
{
packagesDictionary.Remove("0", out var rootNode);
if (rootNode?.Requires != null)
{
explicitReferencedDependencies = new HashSet<string>(rootNode.Requires);

Просмотреть файл

@ -28,7 +28,7 @@ public static class CondaDependencyResolver
public static void UpdateDirectlyReferencedPackages(ISingleFileComponentRecorder singleFileComponentRecorder)
=> singleFileComponentRecorder.GetDetectedComponents().Keys.ForEach(componentId =>
{
if (singleFileComponentRecorder.DependencyGraph.GetAncestors(componentId).Count == 0)
if (!singleFileComponentRecorder.DependencyGraph.GetAncestors(componentId).Any())
{
singleFileComponentRecorder.RegisterUsage(
singleFileComponentRecorder.GetComponent(componentId),
@ -100,7 +100,7 @@ public static class CondaDependencyResolver
/// <returns>A list of packages without dependencies.</returns>
private static List<CondaPackage> GetPackages(CondaLock condaLock)
=> condaLock?.Package == null
? []
? new List<CondaPackage>()
: condaLock.Package;
/// <summary>

Просмотреть файл

@ -27,13 +27,13 @@ public class CondaLockComponentDetector : FileComponentDetector, IDefaultOffComp
public override string Id => "CondaLock";
public override IList<string> SearchPatterns { get; } = ["conda-lock.yml", "*.conda-lock.yml"];
public override IList<string> SearchPatterns { get; } = new List<string> { "conda-lock.yml", "*.conda-lock.yml" };
public override IEnumerable<ComponentType> SupportedComponentTypes => [ComponentType.Conda, ComponentType.Pip];
public override IEnumerable<ComponentType> SupportedComponentTypes => new[] { ComponentType.Conda, ComponentType.Pip };
public override int Version { get; } = 2;
public override IEnumerable<string> Categories => ["Python"];
public override IEnumerable<string> Categories => new List<string> { "Python" };
/// <inheritdoc/>
protected override Task OnFileFoundAsync(ProcessRequest processRequest, IDictionary<string, string> detectorArgs, CancellationToken cancellationToken = default)

Просмотреть файл

@ -35,11 +35,11 @@ public class DockerfileComponentDetector : FileComponentDetector, IDefaultOffCom
public override string Id { get; } = "DockerReference";
public override IEnumerable<string> Categories => [Enum.GetName(typeof(DetectorClass), DetectorClass.DockerReference)];
public override IEnumerable<string> Categories => new[] { Enum.GetName(typeof(DetectorClass), DetectorClass.DockerReference) };
public override IList<string> SearchPatterns { get; } = ["dockerfile", "dockerfile.*", "*.dockerfile"];
public override IList<string> SearchPatterns { get; } = new List<string> { "dockerfile", "dockerfile.*", "*.dockerfile" };
public override IEnumerable<ComponentType> SupportedComponentTypes { get; } = [ComponentType.DockerReference];
public override IEnumerable<ComponentType> SupportedComponentTypes { get; } = new[] { ComponentType.DockerReference };
public override int Version => 1;
@ -55,7 +55,7 @@ public class DockerfileComponentDetector : FileComponentDetector, IDefaultOffCom
string contents;
using (var reader = new StreamReader(file.Stream))
{
contents = await reader.ReadToEndAsync(cancellationToken);
contents = await reader.ReadToEndAsync();
}
var stageNameMap = new Dictionary<string, string>();
@ -69,7 +69,7 @@ public class DockerfileComponentDetector : FileComponentDetector, IDefaultOffCom
private Task ParseDockerFileAsync(string fileContents, string fileLocation, ISingleFileComponentRecorder singleFileComponentRecorder, Dictionary<string, string> stageNameMap)
{
var dockerfileModel = Dockerfile.Parse(fileContents);
var dockerfileModel = Valleysoft.DockerfileModel.Dockerfile.Parse(fileContents);
var instructions = dockerfileModel.Items;
foreach (var instruction in instructions)
{

Просмотреть файл

@ -23,7 +23,7 @@ public class GoComponentDetector : FileComponentDetector
@"(?<name>.*)\s+(?<version>.*?)(/go\.mod)?\s+(?<hash>.*)",
RegexOptions.Compiled | RegexOptions.ExplicitCapture | RegexOptions.IgnoreCase);
private readonly HashSet<string> projectRoots = [];
private readonly HashSet<string> projectRoots = new();
private readonly ICommandLineInvocationService commandLineInvocationService;
private readonly IEnvironmentVariableService envVarService;
@ -44,11 +44,11 @@ public class GoComponentDetector : FileComponentDetector
public override string Id => "Go";
public override IEnumerable<string> Categories => [Enum.GetName(typeof(DetectorClass), DetectorClass.GoMod)];
public override IEnumerable<string> Categories => new[] { Enum.GetName(typeof(DetectorClass), DetectorClass.GoMod) };
public override IList<string> SearchPatterns { get; } = ["go.mod", "go.sum"];
public override IList<string> SearchPatterns { get; } = new List<string> { "go.mod", "go.sum" };
public override IEnumerable<ComponentType> SupportedComponentTypes { get; } = [ComponentType.Go];
public override IEnumerable<ComponentType> SupportedComponentTypes { get; } = new[] { ComponentType.Go };
public override int Version => 7;
@ -90,7 +90,7 @@ public class GoComponentDetector : FileComponentDetector
private IEnumerable<ComponentStream> FindAdjacentGoModComponentStreams(ProcessRequest processRequest) =>
this.ComponentStreamEnumerableFactory.GetComponentStreams(
new FileInfo(processRequest.ComponentStream.Location).Directory,
["go.mod"],
new[] { "go.mod" },
(_, _) => false,
false)
.Select(x =>
@ -224,7 +224,7 @@ public class GoComponentDetector : FileComponentDetector
var projectRootDirectory = Directory.GetParent(location);
record.ProjectRoot = projectRootDirectory.FullName;
var isGoAvailable = await this.commandLineInvocationService.CanCommandBeLocatedAsync("go", null, workingDirectory: projectRootDirectory, ["version"]);
var isGoAvailable = await this.commandLineInvocationService.CanCommandBeLocatedAsync("go", null, workingDirectory: projectRootDirectory, new[] { "version" });
record.IsGoAvailable = isGoAvailable;
if (!isGoAvailable)
@ -236,7 +236,7 @@ public class GoComponentDetector : FileComponentDetector
this.Logger.LogInformation("Go CLI was found in system and will be used to generate dependency graph. " +
"Detection time may be improved by activating fallback strategy (https://github.com/microsoft/component-detection/blob/main/docs/detectors/go.md#fallback-detection-strategy). " +
"But, it will introduce noise into the detected components.");
var goDependenciesProcess = await this.commandLineInvocationService.ExecuteCommandAsync("go", null, workingDirectory: projectRootDirectory, ["list", "-mod=readonly", "-m", "-json", "all"]);
var goDependenciesProcess = await this.commandLineInvocationService.ExecuteCommandAsync("go", null, workingDirectory: projectRootDirectory, new[] { "list", "-mod=readonly", "-m", "-json", "all" });
if (goDependenciesProcess.ExitCode != 0)
{
this.Logger.LogError("Go CLI command \"go list -m -json all\" failed with error: {GoDependenciesProcessStdErr}", goDependenciesProcess.StdErr);
@ -308,7 +308,7 @@ public class GoComponentDetector : FileComponentDetector
}
// Stopping at the first ) restrict the detection to only the require section.
while ((line = await reader.ReadLineAsync()) != null && !line.EndsWith(')'))
while ((line = await reader.ReadLineAsync()) != null && !line.EndsWith(")"))
{
this.TryRegisterDependencyFromModLine(line, singleFileComponentRecorder);
}

Просмотреть файл

@ -23,7 +23,7 @@ public class GoComponentWithReplaceDetector : FileComponentDetector, IExperiment
@"(?<name>.*)\s+(?<version>.*?)(/go\.mod)?\s+(?<hash>.*)",
RegexOptions.Compiled | RegexOptions.ExplicitCapture | RegexOptions.IgnoreCase);
private readonly HashSet<string> projectRoots = [];
private readonly HashSet<string> projectRoots = new();
private readonly ICommandLineInvocationService commandLineInvocationService;
private readonly IEnvironmentVariableService envVarService;
@ -44,11 +44,11 @@ public class GoComponentWithReplaceDetector : FileComponentDetector, IExperiment
public override string Id => "GoWithReplace";
public override IEnumerable<string> Categories => [Enum.GetName(typeof(DetectorClass), DetectorClass.GoMod)];
public override IEnumerable<string> Categories => new[] { Enum.GetName(typeof(DetectorClass), DetectorClass.GoMod) };
public override IList<string> SearchPatterns { get; } = ["go.mod", "go.sum"];
public override IList<string> SearchPatterns { get; } = new List<string> { "go.mod", "go.sum" };
public override IEnumerable<ComponentType> SupportedComponentTypes { get; } = [ComponentType.Go];
public override IEnumerable<ComponentType> SupportedComponentTypes { get; } = new[] { ComponentType.Go };
public override int Version => 1;
@ -90,7 +90,7 @@ public class GoComponentWithReplaceDetector : FileComponentDetector, IExperiment
private IEnumerable<ComponentStream> FindAdjacentGoModComponentStreams(ProcessRequest processRequest) =>
this.ComponentStreamEnumerableFactory.GetComponentStreams(
new FileInfo(processRequest.ComponentStream.Location).Directory,
["go.mod"],
new[] { "go.mod" },
(_, _) => false,
false)
.Select(x =>
@ -224,7 +224,7 @@ public class GoComponentWithReplaceDetector : FileComponentDetector, IExperiment
var projectRootDirectory = Directory.GetParent(location);
record.ProjectRoot = projectRootDirectory.FullName;
var isGoAvailable = await this.commandLineInvocationService.CanCommandBeLocatedAsync("go", null, workingDirectory: projectRootDirectory, ["version"]);
var isGoAvailable = await this.commandLineInvocationService.CanCommandBeLocatedAsync("go", null, workingDirectory: projectRootDirectory, new[] { "version" });
record.IsGoAvailable = isGoAvailable;
if (!isGoAvailable)
@ -236,7 +236,7 @@ public class GoComponentWithReplaceDetector : FileComponentDetector, IExperiment
this.Logger.LogInformation("Go CLI was found in system and will be used to generate dependency graph. " +
"Detection time may be improved by activating fallback strategy (https://github.com/microsoft/component-detection/blob/main/docs/detectors/go.md#fallback-detection-strategy). " +
"But, it will introduce noise into the detected components.");
var goDependenciesProcess = await this.commandLineInvocationService.ExecuteCommandAsync("go", null, workingDirectory: projectRootDirectory, ["list", "-mod=readonly", "-m", "-json", "all"]);
var goDependenciesProcess = await this.commandLineInvocationService.ExecuteCommandAsync("go", null, workingDirectory: projectRootDirectory, new[] { "list", "-mod=readonly", "-m", "-json", "all" });
if (goDependenciesProcess.ExitCode != 0)
{
this.Logger.LogError("Go CLI command \"go list -m -json all\" failed with error: {GoDependenciesProcessStdErr}", goDependenciesProcess.StdErr);
@ -309,7 +309,7 @@ public class GoComponentWithReplaceDetector : FileComponentDetector, IExperiment
}
// Stopping at the first ) restrict the detection to only the require section.
while ((line = await reader.ReadLineAsync()) != null && !line.EndsWith(')'))
while ((line = await reader.ReadLineAsync()) != null && !line.EndsWith(")"))
{
this.TryRegisterDependencyFromModLine(line, singleFileComponentRecorder);
}

Просмотреть файл

@ -31,19 +31,19 @@ public class GradleComponentDetector : FileComponentDetector, IComponentDetector
this.Scanner = walkerFactory;
this.Logger = logger;
this.devLockfiles = envVarService.GetListEnvironmentVariable(DevLockfilesEnvVar) ?? [];
this.devConfigurations = envVarService.GetListEnvironmentVariable(DevConfigurationsEnvVar) ?? [];
this.devLockfiles = envVarService.GetListEnvironmentVariable(DevLockfilesEnvVar) ?? new List<string>();
this.devConfigurations = envVarService.GetListEnvironmentVariable(DevConfigurationsEnvVar) ?? new List<string>();
this.Logger.LogDebug("Gradle dev-only lockfiles {Lockfiles}", string.Join(", ", this.devLockfiles));
this.Logger.LogDebug("Gradle dev-only configurations {Configurations}", string.Join(", ", this.devConfigurations));
}
public override string Id { get; } = "Gradle";
public override IEnumerable<string> Categories => [Enum.GetName(typeof(DetectorClass), DetectorClass.Maven)];
public override IEnumerable<string> Categories => new[] { Enum.GetName(typeof(DetectorClass), DetectorClass.Maven) };
public override IList<string> SearchPatterns { get; } = ["*.lockfile"];
public override IList<string> SearchPatterns { get; } = new List<string> { "*.lockfile" };
public override IEnumerable<ComponentType> SupportedComponentTypes { get; } = [ComponentType.Maven];
public override IEnumerable<ComponentType> SupportedComponentTypes { get; } = new[] { ComponentType.Maven };
public override int Version { get; } = 3;

Просмотреть файл

@ -43,7 +43,7 @@ public class IvyDetector : FileComponentDetector, IExperimentalDetector
internal const string AntVersionArgument = "-version";
internal static readonly string[] AdditionalValidCommands = ["ant"];
internal static readonly string[] AdditionalValidCommands = { "ant" };
private readonly ICommandLineInvocationService commandLineInvocationService;
@ -61,13 +61,13 @@ public class IvyDetector : FileComponentDetector, IExperimentalDetector
public override string Id => "Ivy";
public override IList<string> SearchPatterns => ["ivy.xml"];
public override IList<string> SearchPatterns => new List<string> { "ivy.xml" };
public override IEnumerable<ComponentType> SupportedComponentTypes => [ComponentType.Maven];
public override IEnumerable<ComponentType> SupportedComponentTypes => new[] { ComponentType.Maven };
public override int Version => 2;
public override IEnumerable<string> Categories => [Enum.GetName(typeof(DetectorClass), DetectorClass.Maven)];
public override IEnumerable<string> Categories => new[] { Enum.GetName(typeof(DetectorClass), DetectorClass.Maven) };
protected override async Task<IObservable<ProcessRequest>> OnPrepareDetectionAsync(
IObservable<ProcessRequest> processRequests,

Просмотреть файл

@ -1,4 +1,4 @@
namespace Microsoft.ComponentDetection.Detectors.Linux.Exceptions;
namespace Microsoft.ComponentDetection.Detectors.Linux.Exceptions;
using System;

Просмотреть файл

@ -1,4 +1,4 @@
namespace Microsoft.ComponentDetection.Detectors.Linux;
namespace Microsoft.ComponentDetection.Detectors.Linux;
using System.Collections.Generic;
using System.Threading;

Просмотреть файл

@ -31,9 +31,9 @@ public class LinuxContainerDetector : IComponentDetector
public string Id => "Linux";
public IEnumerable<string> Categories => [Enum.GetName(typeof(DetectorClass), DetectorClass.Linux)];
public IEnumerable<string> Categories => new[] { Enum.GetName(typeof(DetectorClass), DetectorClass.Linux) };
public IEnumerable<ComponentType> SupportedComponentTypes => [ComponentType.Linux];
public IEnumerable<ComponentType> SupportedComponentTypes => new[] { ComponentType.Linux };
public int Version => 4;
@ -47,7 +47,7 @@ public class LinuxContainerDetector : IComponentDetector
.ToList();
#pragma warning restore CA1308
if (imagesToProcess == null || imagesToProcess.Count == 0)
if (imagesToProcess == null || !imagesToProcess.Any())
{
this.logger.LogInformation("No instructions received to scan docker images.");
return EmptySuccessfulScan();
@ -110,7 +110,7 @@ public class LinuxContainerDetector : IComponentDetector
return new ImageScanningResult
{
ContainerDetails = null,
Components = [],
Components = Enumerable.Empty<DetectedComponent>(),
};
}
@ -135,7 +135,13 @@ public class LinuxContainerDetector : IComponentDetector
null);
}
var imageDetails = await this.dockerService.InspectImageAsync(image, cancellationToken) ?? throw new MissingContainerDetailException(image);
var imageDetails = await this.dockerService.InspectImageAsync(image, cancellationToken);
// Unable to fetch image details
if (imageDetails == null)
{
throw new MissingContainerDetailException(image);
}
processedImages.TryAdd(imageDetails.ImageId, imageDetails);
}

Просмотреть файл

@ -17,16 +17,12 @@ public class LinuxScanner : ILinuxScanner
{
private const string ScannerImage = "governancecontainerregistry.azurecr.io/syft:v0.100.0@sha256:df7b07bfadff45e0135d74f22478f47b16ac6aff4e8dbd93133fcae3bbbb790d";
private static readonly IList<string> CmdParameters =
[
"--quiet",
"--scope",
"all-layers",
"--output",
"json",
];
private static readonly IList<string> CmdParameters = new List<string>
{
"--quiet", "--scope", "all-layers", "--output", "json",
};
private static readonly IEnumerable<string> AllowedArtifactTypes = ["apk", "deb", "rpm"];
private static readonly IEnumerable<string> AllowedArtifactTypes = new[] { "apk", "deb", "rpm" };
private static readonly SemaphoreSlim DockerSemaphore = new SemaphoreSlim(2);
@ -167,7 +163,7 @@ public class LinuxScanner : ILinuxScanner
}
var licenses = artifact.Licenses;
if (licenses != null && licenses.Length != 0)
if (licenses != null && licenses.Any())
{
return string.Join(", ", licenses.Select(l => l.Value));
}

Просмотреть файл

@ -1,4 +1,4 @@
namespace Microsoft.ComponentDetection.Detectors.Maven;
namespace Microsoft.ComponentDetection.Detectors.Maven;
using System.Collections.Generic;
@ -12,7 +12,7 @@ public class GraphNode<T>
public T Value { get; set; }
public List<GraphNode<T>> Children { get; } = [];
public List<GraphNode<T>> Children { get; } = new List<GraphNode<T>>();
public List<GraphNode<T>> Parents { get; } = [];
public List<GraphNode<T>> Parents { get; } = new List<GraphNode<T>>();
}

Просмотреть файл

@ -16,7 +16,7 @@ public class MavenCommandService : IMavenCommandService
internal const string MvnVersionArgument = "--version";
internal static readonly string[] AdditionalValidCommands = ["mvn.cmd"];
internal static readonly string[] AdditionalValidCommands = new[] { "mvn.cmd" };
private readonly ICommandLineInvocationService commandLineInvocationService;
private readonly IMavenStyleDependencyGraphParserService parserService;

Некоторые файлы не были показаны из-за слишком большого количества измененных файлов Показать больше