This commit is contained in:
Justin Perez 2023-01-31 08:43:20 -08:00 коммит произвёл GitHub
Родитель cf622c7950
Коммит 4e49e43c89
Не найден ключ, соответствующий данной подписи
Идентификатор ключа GPG: 4AEE18F83AFDEB23
265 изменённых файлов: 1591 добавлений и 1775 удалений

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

@ -459,10 +459,6 @@ dotnet_naming_rule.parameters_rule.severity = warning
# https://github.com/DotNetAnalyzers/StyleCopAnalyzers
##########################################
# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1200.md
# Using directive should appear within a namespace declaration
dotnet_diagnostic.SA1200.severity = suggestion
# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1600.md
# Elements should be documented
dotnet_diagnostic.SA1600.severity = suggestion
@ -500,10 +496,6 @@ dotnet_diagnostic.VSTHRD101.severity = suggestion
# Add .ConfigureAwait(bool) to your await expression
dotnet_diagnostic.VSTHRD111.severity = suggestion
# https://github.com/microsoft/vs-threading/blob/main/doc/analyzers/VSTHRD200.md
# Use "Async" suffix in names of methods that return an awaitable type
dotnet_diagnostic.VSTHRD200.severity = suggestion
##########################################
# Provided by Roslyn
# https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/compiler-messages/
@ -517,9 +509,6 @@ dotnet_diagnostic.CS0618.severity = suggestion
# Missing XML comment for publicly visible type or member '...'
dotnet_diagnostic.CS1591.severity = suggestion
# IDE0003: Remove qualification
dotnet_diagnostic.IDE0003.severity = suggestion
# CA2007: Consider calling ConfigureAwait on the awaited task
dotnet_diagnostic.CA2007.severity = suggestion
@ -538,45 +527,21 @@ dotnet_diagnostic.CA1031.severity = suggestion
# CA1711: Identifiers should not have incorrect suffix
dotnet_diagnostic.CA1711.severity = suggestion
# CA1018: Mark attributes with AttributeUsageAttribute
dotnet_diagnostic.CA1018.severity = suggestion
# CA1813: Avoid unsealed attributes
dotnet_diagnostic.CA1813.severity = suggestion
# CA2227: Collection properties should be read only
dotnet_diagnostic.CA2227.severity = suggestion
# CA1825: Avoid zero-length array allocations
dotnet_diagnostic.CA1825.severity = suggestion
# CA1310: Specify StringComparison for correctness
dotnet_diagnostic.CA1310.severity = suggestion
# CA1002: Do not expose generic lists
dotnet_diagnostic.CA1002.severity = suggestion
# IDE0008: Use explicit type
dotnet_diagnostic.IDE0008.severity = suggestion
# CA1305: Specify IFormatProvider
dotnet_diagnostic.CA1305.severity = suggestion
# CA1032: Implement standard exception constructors
dotnet_diagnostic.CA1032.severity = suggestion
# CA1051: Do not declare visible instance fields
dotnet_diagnostic.CA1051.severity = suggestion
# CA1401: P/Invokes should not be visible
dotnet_diagnostic.CA1401.severity = suggestion
# CA5392: Use DefaultDllImportSearchPaths attribute for P/Invokes
dotnet_diagnostic.CA5392.severity = suggestion
# CA2101: Specify marshaling for P/Invoke string arguments
dotnet_diagnostic.CA2101.severity = suggestion
# CA2211: Non-constant fields should not be visible
dotnet_diagnostic.CA2211.severity = suggestion
@ -592,42 +557,18 @@ dotnet_diagnostic.CA1822.severity = suggestion
# CA1307: Specify StringComparison for clarity
dotnet_diagnostic.CA1307.severity = suggestion
# CA1052: Static holder types should be Static or NotInheritable
dotnet_diagnostic.CA1052.severity = suggestion
# CA1725: Parameter names should match base declaration
dotnet_diagnostic.CA1725.severity = suggestion
# CA1805: Do not initialize unnecessarily
dotnet_diagnostic.CA1805.severity = suggestion
# CA1806: Do not ignore method results
dotnet_diagnostic.CA1806.severity = suggestion
# CA1303: Do not pass literals as localized parameters
dotnet_diagnostic.CA1303.severity = suggestion
# CA1816: Dispose methods should call SuppressFinalize
dotnet_diagnostic.CA1816.severity = suggestion
# CA2249: Consider using 'string.Contains' instead of 'string.IndexOf'
dotnet_diagnostic.CA2249.severity = suggestion
# CA1836: Prefer IsEmpty over Count
dotnet_diagnostic.CA1836.severity = suggestion
# CA2208: Instantiate argument exceptions correctly
dotnet_diagnostic.CA2208.severity = suggestion
# CA1028: Enum Storage should be Int32
dotnet_diagnostic.CA1028.severity = suggestion
# CA1034: Nested types should not be visible
dotnet_diagnostic.CA1034.severity = suggestion
# CA1033: Interface methods should be callable by child types
dotnet_diagnostic.CA1033.severity = suggestion
# CA1054: URI-like parameters should not be strings
dotnet_diagnostic.CA1054.severity = suggestion
@ -637,42 +578,18 @@ dotnet_diagnostic.CA1027.severity = suggestion
# CA1056: URI-like properties should not be strings
dotnet_diagnostic.CA1056.severity = suggestion
# CA1838: Avoid 'StringBuilder' parameters for P/Invokes
dotnet_diagnostic.CA1838.severity = suggestion
# CA2000: Dispose objects before losing scope
dotnet_diagnostic.CA2000.severity = suggestion
# CA2016: Forward the 'CancellationToken' parameter to methods
dotnet_diagnostic.CA2016.severity = suggestion
# CA1014: Mark assemblies with CLSCompliantAttribute
dotnet_diagnostic.CA1014.severity = none
# CA1824: Mark assemblies with NeutralResourcesLanguageAttribute
dotnet_diagnostic.CA1824.severity = none
# CA1508: Avoid dead conditional code
dotnet_diagnostic.CA1508.severity = suggestion
# CA1823: Avoid unused private fields
dotnet_diagnostic.CA1823.severity = suggestion
# CA2234: Pass system uri objects instead of strings
dotnet_diagnostic.CA2234.severity = suggestion
# SA1101: Prefix local calls with this
dotnet_diagnostic.SA1101.severity = suggestion
# CA2219: Do not raise exceptions in finally clauses
dotnet_diagnostic.CA2219.severity = suggestion
# CA2201: Exception type System.Exception is not sufficiently specific
dotnet_diagnostic.CA2201.severity = suggestion
# CA1835: Prefer the 'Memory'-based overloads for 'ReadAsync' and 'WriteAsync'
dotnet_diagnostic.CA1835.severity = suggestion
# CA1036: Override methods on comparable types
dotnet_diagnostic.CA1036.severity = suggestion

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

@ -1,9 +1,8 @@
using System;
namespace Microsoft.ComponentDetection.Common;
using System;
using System.Threading;
using System.Threading.Tasks;
namespace Microsoft.ComponentDetection.Common;
public static class AsyncExecution
{
public static async Task<T> ExecuteWithTimeoutAsync<T>(Func<Task<T>> toExecute, TimeSpan timeout, CancellationToken cancellationToken)
@ -31,7 +30,7 @@ public static class AsyncExecution
throw new ArgumentNullException(nameof(toExecute));
}
var work = Task.Run(toExecute);
var work = Task.Run(toExecute, cancellationToken);
var completedInTime = await Task.Run(() => work.Wait(timeout));
if (!completedInTime)
{

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

@ -1,4 +1,5 @@
using System;
namespace Microsoft.ComponentDetection.Common;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.ComponentModel;
@ -10,17 +11,15 @@ using System.Threading.Tasks;
using Microsoft.ComponentDetection.Common.Telemetry.Records;
using Microsoft.ComponentDetection.Contracts;
namespace Microsoft.ComponentDetection.Common;
[Export(typeof(ICommandLineInvocationService))]
public class CommandLineInvocationService : ICommandLineInvocationService
{
private readonly IDictionary<string, string> commandLocatableCache = new ConcurrentDictionary<string, string>();
public async Task<bool> CanCommandBeLocated(string command, IEnumerable<string> additionalCandidateCommands = null, DirectoryInfo workingDirectory = null, params string[] parameters)
public async Task<bool> CanCommandBeLocatedAsync(string command, IEnumerable<string> additionalCandidateCommands = null, DirectoryInfo workingDirectory = null, params string[] parameters)
{
additionalCandidateCommands ??= Enumerable.Empty<string>();
parameters ??= new string[0];
parameters ??= Array.Empty<string>();
var allCommands = new[] { command }.Concat(additionalCandidateCommands);
if (!this.commandLocatableCache.TryGetValue(command, out var validCommand))
{
@ -51,19 +50,19 @@ public class CommandLineInvocationService : ICommandLineInvocationService
return !string.IsNullOrWhiteSpace(validCommand);
}
public async Task<CommandLineExecutionResult> ExecuteCommand(string command, IEnumerable<string> additionalCandidateCommands = null, DirectoryInfo workingDirectory = null, params string[] parameters)
public async Task<CommandLineExecutionResult> ExecuteCommandAsync(string command, IEnumerable<string> additionalCandidateCommands = null, DirectoryInfo workingDirectory = null, params string[] parameters)
{
var isCommandLocatable = await this.CanCommandBeLocated(command, additionalCandidateCommands);
var isCommandLocatable = await this.CanCommandBeLocatedAsync(command, additionalCandidateCommands);
if (!isCommandLocatable)
{
throw new InvalidOperationException(
$"{nameof(this.ExecuteCommand)} was called with a command that could not be located: `{command}`!");
$"{nameof(this.ExecuteCommandAsync)} was called with a command that could not be located: `{command}`!");
}
if (workingDirectory != null && !Directory.Exists(workingDirectory.FullName))
{
throw new InvalidOperationException(
$"{nameof(this.ExecuteCommand)} was called with a working directory that could not be located: `{workingDirectory.FullName}`");
$"{nameof(this.ExecuteCommandAsync)} was called with a working directory that could not be located: `{workingDirectory.FullName}`");
}
using var record = new CommandLineInvocationTelemetryRecord();
@ -88,14 +87,14 @@ public class CommandLineInvocationService : ICommandLineInvocationService
return true;
}
public async Task<bool> CanCommandBeLocated(string command, IEnumerable<string> additionalCandidateCommands = null, params string[] parameters)
public async Task<bool> CanCommandBeLocatedAsync(string command, IEnumerable<string> additionalCandidateCommands = null, params string[] parameters)
{
return await this.CanCommandBeLocated(command, additionalCandidateCommands, workingDirectory: null, parameters);
return await this.CanCommandBeLocatedAsync(command, additionalCandidateCommands, workingDirectory: null, parameters);
}
public async Task<CommandLineExecutionResult> ExecuteCommand(string command, IEnumerable<string> additionalCandidateCommands = null, params string[] parameters)
public async Task<CommandLineExecutionResult> ExecuteCommandAsync(string command, IEnumerable<string> additionalCandidateCommands = null, params string[] parameters)
{
return await this.ExecuteCommand(command, additionalCandidateCommands, workingDirectory: null, parameters);
return await this.ExecuteCommandAsync(command, additionalCandidateCommands, workingDirectory: null, parameters);
}
private static Task<CommandLineExecutionResult> RunProcessAsync(string fileName, string parameters, DirectoryInfo workingDirectory = null)

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

@ -1,17 +1,16 @@
using System.Collections.Generic;
namespace Microsoft.ComponentDetection.Common;
using System.Collections.Generic;
using Microsoft.ComponentDetection.Contracts.TypedComponent;
namespace Microsoft.ComponentDetection.Common;
public class ComponentComparer : EqualityComparer<TypedComponent>
{
public override bool Equals(TypedComponent t0, TypedComponent t1)
public override bool Equals(TypedComponent x, TypedComponent y)
{
return t0.Id.Equals(t1.Id);
return x.Id.Equals(y.Id);
}
public override int GetHashCode(TypedComponent typedComponent)
public override int GetHashCode(TypedComponent obj)
{
return typedComponent.Id.GetHashCode();
return obj.Id.GetHashCode();
}
}

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

@ -1,8 +1,7 @@
using System.IO;
namespace Microsoft.ComponentDetection.Common;
using System.IO;
using Microsoft.ComponentDetection.Contracts;
namespace Microsoft.ComponentDetection.Common;
public class ComponentStream : IComponentStream
{
public Stream Stream { get; set; }

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

@ -1,11 +1,10 @@
using System;
namespace Microsoft.ComponentDetection.Common;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using Microsoft.ComponentDetection.Contracts;
namespace Microsoft.ComponentDetection.Common;
public class ComponentStreamEnumerable : IEnumerable<IComponentStream>
{
public ComponentStreamEnumerable(IEnumerable<MatchedFile> fileEnumerable, ILogger logger)

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

@ -1,11 +1,10 @@
using System;
namespace Microsoft.ComponentDetection.Common;
using System;
using System.Collections.Generic;
using System.Composition;
using System.IO;
using Microsoft.ComponentDetection.Contracts;
namespace Microsoft.ComponentDetection.Common;
[Export(typeof(IComponentStreamEnumerableFactory))]
[Shared]
public class ComponentStreamEnumerableFactory : IComponentStreamEnumerableFactory

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

@ -1,8 +1,7 @@
using System;
namespace Microsoft.ComponentDetection.Common;
using System;
using System.Composition;
namespace Microsoft.ComponentDetection.Common;
[Export(typeof(IConsoleWritingService))]
public class ConsoleWritingService : IConsoleWritingService
{

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

@ -90,7 +90,7 @@ public class ComponentRecorder : IComponentRecorder
return this.singleFileRecorders.Single(x => x.ManifestFileLocation == location).DependencyGraph;
}
public class SingleFileComponentRecorder : ISingleFileComponentRecorder
public sealed class SingleFileComponentRecorder : ISingleFileComponentRecorder
{
private readonly ILogger log;

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

@ -34,7 +34,7 @@ internal class DependencyGraph : IDependencyGraph
if (string.IsNullOrWhiteSpace(componentNode.Id))
{
throw new ArgumentNullException(nameof(componentNode.Id));
throw new ArgumentNullException(nameof(componentNode.Id), "Invalid component node id");
}
this.componentNodes.AddOrUpdate(componentNode.Id, componentNode, (key, currentNode) =>
@ -99,7 +99,7 @@ internal class DependencyGraph : IDependencyGraph
public bool HasComponents()
{
return this.componentNodes.Count > 0;
return !this.componentNodes.IsEmpty;
}
public bool? IsDevelopmentDependency(string componentId)

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

@ -1,12 +1,11 @@
using Microsoft.ComponentDetection.Contracts.BcdeModels;
namespace Microsoft.ComponentDetection.Common;
namespace Microsoft.ComponentDetection.Common;
using Microsoft.ComponentDetection.Contracts.BcdeModels;
/// <summary>
/// Merges dependnecy Scope in their order of Priority.
/// Higher priority scope, as indicated by its lower enum value is given precendence.
/// </summary>
public class DependencyScopeComparer
public static class DependencyScopeComparer
{
public static DependencyScope? GetMergedDependencyScope(DependencyScope? scope1, DependencyScope? scope2)
{

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

@ -1,8 +1,7 @@
using System.Composition;
namespace Microsoft.ComponentDetection.Common;
using System.Composition;
using Microsoft.ComponentDetection.Contracts;
namespace Microsoft.ComponentDetection.Common;
[Export(typeof(IDetectorDependencies))]
public class DetectorDependencies : IDetectorDependencies
{

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

@ -1,9 +1,8 @@
using System.Collections.Generic;
namespace Microsoft.ComponentDetection.Common;
using System.Collections.Generic;
using System.Diagnostics;
using Microsoft.ComponentDetection.Contracts;
namespace Microsoft.ComponentDetection.Common;
[DebuggerDisplay("{Name}")]
public class DirectoryItemFacade
{

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

@ -1,8 +1,7 @@
namespace Microsoft.ComponentDetection.Common;
using System.Collections.Generic;
namespace Microsoft.ComponentDetection.Common;
public class DigestUtility
public static class DigestUtility
{
private static readonly Dictionary<string, int> AlgorithmsSizes = new Dictionary<string, int>()
{

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

@ -1,7 +1,6 @@
using System;
#pragma warning disable SA1402
namespace Microsoft.ComponentDetection.Common;
using System;
public class DockerReferenceException : Exception
{
@ -9,6 +8,20 @@ public class DockerReferenceException : Exception
: base($"Error while parsing docker reference {reference} : {exceptionErrorMessage}")
{
}
public DockerReferenceException()
{
}
public DockerReferenceException(string message)
: base(message)
{
}
public DockerReferenceException(string message, Exception innerException)
: base(message, innerException)
{
}
}
// ReferenceInvalidFormat represents an error while trying to parse a string as a reference.
@ -20,6 +33,15 @@ public class ReferenceInvalidFormatException : DockerReferenceException
: base(reference, ErrorMessage)
{
}
public ReferenceInvalidFormatException()
{
}
public ReferenceInvalidFormatException(string message, Exception innerException)
: base(message, innerException)
{
}
}
// TagInvalidFormat represents an error while trying to parse a string as a tag.
@ -31,6 +53,15 @@ public class ReferenceTagInvalidFormatException : DockerReferenceException
: base(reference, ErrorMessage)
{
}
public ReferenceTagInvalidFormatException()
{
}
public ReferenceTagInvalidFormatException(string message, Exception innerException)
: base(message, innerException)
{
}
}
// DigestInvalidFormat represents an error while trying to parse a string as a tag.
@ -42,6 +73,15 @@ public class ReferenceDigestInvalidFormatException : DockerReferenceException
: base(reference, ErrorMessage)
{
}
public ReferenceDigestInvalidFormatException()
{
}
public ReferenceDigestInvalidFormatException(string message, Exception innerException)
: base(message, innerException)
{
}
}
// NameContainsUppercase is returned for invalid repository names that contain uppercase characters.
@ -53,6 +93,15 @@ public class ReferenceNameContainsUppercaseException : DockerReferenceException
: base(reference, ErrorMessage)
{
}
public ReferenceNameContainsUppercaseException()
{
}
public ReferenceNameContainsUppercaseException(string message, Exception innerException)
: base(message, innerException)
{
}
}
// NameEmpty is returned for empty, invalid repository names.
@ -64,6 +113,15 @@ public class ReferenceNameEmptyException : DockerReferenceException
: base(reference, ErrorMessage)
{
}
public ReferenceNameEmptyException()
{
}
public ReferenceNameEmptyException(string message, Exception innerException)
: base(message, innerException)
{
}
}
// ErrNameTooLong is returned when a repository name is longer than NameTotalLengthMax.
@ -75,6 +133,15 @@ public class ReferenceNameTooLongException : DockerReferenceException
: base(reference, ErrorMessage)
{
}
public ReferenceNameTooLongException()
{
}
public ReferenceNameTooLongException(string message, Exception innerException)
: base(message, innerException)
{
}
}
// ErrNameNotCanonical is returned when a name is not canonical.
@ -86,6 +153,15 @@ public class ReferenceNameNotCanonicalException : DockerReferenceException
: base(reference, ErrorMessage)
{
}
public ReferenceNameNotCanonicalException()
{
}
public ReferenceNameNotCanonicalException(string message, Exception innerException)
: base(message, innerException)
{
}
}
public class InvalidDigestFormatError : DockerReferenceException
@ -96,6 +172,15 @@ public class InvalidDigestFormatError : DockerReferenceException
: base(reference, ErrorMessage)
{
}
public InvalidDigestFormatError()
{
}
public InvalidDigestFormatError(string message, Exception innerException)
: base(message, innerException)
{
}
}
public class UnsupportedAlgorithmError : DockerReferenceException
@ -106,6 +191,15 @@ public class UnsupportedAlgorithmError : DockerReferenceException
: base(reference, ErrorMessage)
{
}
public UnsupportedAlgorithmError()
{
}
public UnsupportedAlgorithmError(string message, Exception innerException)
: base(message, innerException)
{
}
}
public class InvalidDigestLengthError : DockerReferenceException
@ -116,4 +210,13 @@ public class InvalidDigestLengthError : DockerReferenceException
: base(reference, ErrorMessage)
{
}
public InvalidDigestLengthError()
{
}
public InvalidDigestLengthError(string message, Exception innerException)
: base(message, innerException)
{
}
}

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

@ -1,5 +1,3 @@
using Microsoft.ComponentDetection.Contracts;
// transcribed from https://github.com/containers/image/blob/c1a5f92d0ebbf9e0bf187b3353dd400472b388eb/docker/reference/reference.go
// Package reference provides a general type to represent any way of referencing images within the registry.
@ -27,8 +25,9 @@ using Microsoft.ComponentDetection.Contracts;
// identifier := /[a-f0-9]{64}/
// short-identifier := /[a-f0-9]{6,64}/
namespace Microsoft.ComponentDetection.Common;
using Microsoft.ComponentDetection.Contracts;
public class DockerReferenceUtility
public static class DockerReferenceUtility
{
// NameTotalLengthMax is the maximum total number of characters in a repository name.
private const int NameTotalLengthMax = 255;
@ -112,7 +111,7 @@ public class DockerReferenceUtility
domain = DEFAULTDOMAIN;
}
if (domain == DEFAULTDOMAIN && remainder.IndexOf('/') == -1)
if (domain == DEFAULTDOMAIN && indexOfSlash == -1)
{
remainder = $"{OFFICIALREPOSITORYNAME}/{remainder}";
}

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

@ -1,9 +1,8 @@
namespace Microsoft.ComponentDetection.Common;
using System.Linq;
using System.Text.RegularExpressions;
namespace Microsoft.ComponentDetection.Common;
public class DockerRegex
public static class DockerRegex
{
public static readonly Regex AlphaNumericRegexp = new Regex("[a-z0-9]+");
public static readonly Regex SeparatorRegexp = new Regex("(?:[._]|__|[-]*)");

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

@ -1,3 +1,4 @@
namespace Microsoft.ComponentDetection.Common;
using System;
using System.Collections.Generic;
using System.Composition;
@ -12,8 +13,6 @@ using Microsoft.ComponentDetection.Contracts;
using Microsoft.ComponentDetection.Contracts.BcdeModels;
using Newtonsoft.Json;
namespace Microsoft.ComponentDetection.Common;
[Export(typeof(IDockerService))]
public class DockerService : IDockerService
{

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

@ -1,10 +1,9 @@
namespace Microsoft.ComponentDetection.Common;
using System;
using System.Composition;
using System.Linq;
using Microsoft.ComponentDetection.Contracts;
namespace Microsoft.ComponentDetection.Common;
[Export(typeof(IEnvironmentVariableService))]
public class EnvironmentVariableService : IEnvironmentVariableService
{

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

@ -1,6 +1,5 @@
using System;
namespace Microsoft.ComponentDetection.Common.Exceptions;
using System;
public class InvalidUserInputException : Exception
{
@ -8,4 +7,13 @@ public class InvalidUserInputException : Exception
: base(message, innerException)
{
}
public InvalidUserInputException()
{
}
public InvalidUserInputException(string message)
: base(message)
{
}
}

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

@ -1,4 +1,5 @@
using System;
namespace Microsoft.ComponentDetection.Common;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Composition;
@ -13,8 +14,6 @@ using System.Threading.Tasks.Dataflow;
using Microsoft.ComponentDetection.Contracts;
using Microsoft.ComponentDetection.Contracts.Internal;
namespace Microsoft.ComponentDetection.Common;
[Export(typeof(IObservableDirectoryWalkerFactory))]
[Export(typeof(FastDirectoryWalkerFactory))]
[Shared]
@ -201,11 +200,11 @@ public class FastDirectoryWalkerFactory : IObservableDirectoryWalkerFactory
/// </summary>
/// <param name="root">Root directory to scan.</param>
/// <param name="directoryExclusionPredicate">predicate for excluding directories.</param>
/// <param name="minimumConnectionCount">Number of observers that need to subscribe before the observable connects and starts enumerating.</param>
/// <param name="count">Number of observers that need to subscribe before the observable connects and starts enumerating.</param>
/// <param name="filePatterns">Pattern used to filter files.</param>
public void Initialize(DirectoryInfo root, ExcludeDirectoryPredicate directoryExclusionPredicate, int minimumConnectionCount, IEnumerable<string> filePatterns = null)
public void Initialize(DirectoryInfo root, ExcludeDirectoryPredicate directoryExclusionPredicate, int count, IEnumerable<string> filePatterns = null)
{
this.pendingScans.GetOrAdd(root, new Lazy<IObservable<FileSystemInfo>>(() => this.CreateDirectoryWalker(root, directoryExclusionPredicate, minimumConnectionCount, filePatterns)));
this.pendingScans.GetOrAdd(root, new Lazy<IObservable<FileSystemInfo>>(() => this.CreateDirectoryWalker(root, directoryExclusionPredicate, count, filePatterns)));
}
public IObservable<FileSystemInfo> Subscribe(DirectoryInfo root, IEnumerable<string> patterns)

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

@ -1,9 +1,8 @@
using System.Composition;
namespace Microsoft.ComponentDetection.Common;
using System.Composition;
using System.IO;
using Microsoft.ComponentDetection.Contracts;
namespace Microsoft.ComponentDetection.Common;
/// <summary>
/// Wraps some common file operations for easier testability. This interface is *only used by the command line driven app*.
/// </summary>

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

@ -1,10 +1,9 @@
using System;
namespace Microsoft.ComponentDetection.Common;
using System;
using System.Composition;
using System.IO;
using Microsoft.ComponentDetection.Common.Exceptions;
namespace Microsoft.ComponentDetection.Common;
[Export(typeof(IFileWritingService))]
[Export(typeof(FileWritingService))]
[Shared]
@ -47,9 +46,9 @@ public class FileWritingService : IFileWritingService
}
}
public void WriteFile(FileInfo absolutePath, string text)
public void WriteFile(FileInfo relativeFilePath, string text)
{
File.WriteAllText(absolutePath.FullName, text);
File.WriteAllText(relativeFilePath.FullName, text);
}
public string ResolveFilePath(string relativeFilePath)

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

@ -1,6 +1,5 @@
using System.IO;
namespace Microsoft.ComponentDetection.Common;
namespace Microsoft.ComponentDetection.Common;
using System.IO;
// All file paths are relative and will replace occurrences of {timestamp} with the shared file timestamp.
public interface IFileWritingService

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

@ -1,9 +1,8 @@
using System.Collections.Generic;
namespace Microsoft.ComponentDetection.Common;
using System.Collections.Generic;
using System.IO;
using Microsoft.ComponentDetection.Contracts;
namespace Microsoft.ComponentDetection.Common;
/// <summary>Factory for generating safe file enumerables.</summary>
public interface ISafeFileEnumerableFactory
{

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

@ -1,9 +1,8 @@
using System;
namespace Microsoft.ComponentDetection.Common;
using System;
using System.IO;
using Microsoft.ComponentDetection.Contracts;
namespace Microsoft.ComponentDetection.Common;
public class LazyComponentStream : IComponentStream
{
private readonly FileInfo fileInfo;
@ -46,6 +45,6 @@ public class LazyComponentStream : IComponentStream
this.logger?.LogException(e, isError: false);
}
return new byte[0];
return Array.Empty<byte>();
}
}

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

@ -1,4 +1,5 @@
using System;
namespace Microsoft.ComponentDetection.Common;
using System;
using System.Composition;
using System.Runtime.CompilerServices;
using Microsoft.ComponentDetection.Common.Telemetry.Records;
@ -6,8 +7,6 @@ using Microsoft.ComponentDetection.Contracts;
using static System.Environment;
namespace Microsoft.ComponentDetection.Common;
[Export(typeof(ILogger))]
[Export(typeof(Logger))]
[Shared]

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

@ -1,6 +1,5 @@
using System.IO;
namespace Microsoft.ComponentDetection.Common;
namespace Microsoft.ComponentDetection.Common;
using System.IO;
public class MatchedFile
{

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

@ -1,4 +1,5 @@
using System;
namespace Microsoft.ComponentDetection.Common;
using System;
using System.Collections.Concurrent;
using System.Composition;
using System.Diagnostics;
@ -9,8 +10,6 @@ using System.Text;
using Microsoft.ComponentDetection.Contracts;
using Microsoft.Win32.SafeHandles;
namespace Microsoft.ComponentDetection.Common;
// We may want to consider breaking this class into Win/Mac/Linux variants if it gets bigger
[Export(typeof(IPathUtilityService))]
[Export(typeof(PathUtilityService))]
@ -32,7 +31,7 @@ public class PathUtilityService : IPathUtilityService
private readonly ConcurrentDictionary<string, string> resolvedPaths = new ConcurrentDictionary<string, string>();
private readonly object isRunningOnWindowsContainerLock = new object();
private bool? isRunningOnWindowsContainer = null;
private bool? isRunningOnWindowsContainer;
public bool IsRunningOnWindowsContainer
{
@ -65,7 +64,10 @@ public class PathUtilityService : IPathUtilityService
/// <param name="output"> The pointer output. </param>
/// <returns> A pointer <see cref= "IntPtr"/> to the absolute path of a file. </returns>
[DllImport("libc", EntryPoint = "realpath")]
public static extern IntPtr RealPathLinux([MarshalAs(UnmanagedType.LPStr)] string path, IntPtr output);
[DefaultDllImportSearchPaths(DllImportSearchPath.SafeDirectories)]
#pragma warning disable CA2101 // Specify marshaling for P/Invoke string arguments. libc expects a null-terminated ANSI string.
private static extern IntPtr RealPathLinux([MarshalAs(UnmanagedType.LPStr)] string path, IntPtr output);
#pragma warning restore CA2101 // Specify marshaling for P/Invoke string arguments
/// <summary>
/// Use this function to free memory and prevent memory leaks.
@ -74,7 +76,8 @@ public class PathUtilityService : IPathUtilityService
/// </summary>
/// <param name="toFree">Pointer to the memory space to free. </param>
[DllImport("libc", EntryPoint = "free")]
public static extern void FreeMemoryLinux([In] IntPtr toFree);
[DefaultDllImportSearchPaths(DllImportSearchPath.SafeDirectories)]
private static extern void FreeMemoryLinux([In] IntPtr toFree);
public static bool MatchesPattern(string searchPattern, ref FileSystemEntry fse)
{
@ -170,14 +173,14 @@ public class PathUtilityService : IPathUtilityService
return path;
}
var resultBuilder = new StringBuilder(InitalPathBufferSize);
var mResult = GetFinalPathNameByHandle(directoryHandle.DangerousGetHandle(), resultBuilder, resultBuilder.Capacity, 0);
var resultBuf = new char[InitalPathBufferSize];
var mResult = GetFinalPathNameByHandle(directoryHandle.DangerousGetHandle(), resultBuf, InitalPathBufferSize, 0);
// If GetFinalPathNameByHandle needs a bigger buffer, it will tell us the size it needs (including the null terminator) in finalPathNameResultCode
if (mResult > InitalPathBufferSize)
{
resultBuilder = new StringBuilder(mResult);
mResult = GetFinalPathNameByHandle(directoryHandle.DangerousGetHandle(), resultBuilder, resultBuilder.Capacity, 0);
resultBuf = new char[mResult];
mResult = GetFinalPathNameByHandle(directoryHandle.DangerousGetHandle(), resultBuf, mResult, 0);
}
if (mResult < 0)
@ -185,7 +188,7 @@ public class PathUtilityService : IPathUtilityService
return path;
}
var result = resultBuilder.ToString();
var result = resultBuf.ToString();
result = result.StartsWith(LongPathPrefix) ? result[LongPathPrefix.Length..] : result;
@ -231,6 +234,7 @@ public class PathUtilityService : IPathUtilityService
}
[DllImport("kernel32.dll", EntryPoint = "CreateFileW", CharSet = CharSet.Unicode, SetLastError = true)]
[DefaultDllImportSearchPaths(DllImportSearchPath.System32)]
private static extern SafeFileHandle CreateFile(
[In] string lpFileName,
[In] uint dwDesiredAccess,
@ -241,7 +245,8 @@ public class PathUtilityService : IPathUtilityService
[In] IntPtr hTemplateFile);
[DllImport("kernel32.dll", EntryPoint = "GetFinalPathNameByHandleW", CharSet = CharSet.Unicode, SetLastError = true)]
private static extern int GetFinalPathNameByHandle([In] IntPtr hFile, [Out] StringBuilder lpszFilePath, [In] int cchFilePath, [In] int dwFlags);
[DefaultDllImportSearchPaths(DllImportSearchPath.System32)]
private static extern int GetFinalPathNameByHandle([In] IntPtr hFile, [Out] char[] lpszFilePath, [In] int cchFilePath, [In] int dwFlags);
private bool CheckIfRunningOnWindowsContainer()
{

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

@ -1,11 +1,10 @@
using System;
namespace Microsoft.ComponentDetection.Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
namespace Microsoft.ComponentDetection.Common;
public static class PatternMatchingUtility
{
public delegate bool FilePatternMatcher(ReadOnlySpan<char> span);
@ -13,10 +12,10 @@ 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, new[] { typeof(string) }, new ParameterModifier[0]);
var equals = typeof(MemoryExtensions).GetMethod("Equals", BindingFlags.Public | BindingFlags.Static, null, CallingConventions.Standard, new[] { typeof(ReadOnlySpan<char>), typeof(ReadOnlySpan<char>), typeof(StringComparison) }, new ParameterModifier[0]);
var startsWith = typeof(MemoryExtensions).GetMethod("StartsWith", BindingFlags.Public | BindingFlags.Static, null, CallingConventions.Standard, new[] { typeof(ReadOnlySpan<char>), typeof(ReadOnlySpan<char>), typeof(StringComparison) }, new ParameterModifier[0]);
var endsWith = typeof(MemoryExtensions).GetMethod("EndsWith", BindingFlags.Public | BindingFlags.Static, null, CallingConventions.Standard, new[] { typeof(ReadOnlySpan<char>), typeof(ReadOnlySpan<char>), typeof(StringComparison) }, new ParameterModifier[0]);
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");

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

@ -1,12 +1,11 @@
using System;
namespace Microsoft.ComponentDetection.Common;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.IO.Enumeration;
using Microsoft.ComponentDetection.Contracts;
namespace Microsoft.ComponentDetection.Common;
public class SafeFileEnumerable : IEnumerable<MatchedFile>
{
private readonly IEnumerable<string> searchPatterns;

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

@ -1,10 +1,9 @@
namespace Microsoft.ComponentDetection.Common;
using System.Collections.Generic;
using System.Composition;
using System.IO;
using Microsoft.ComponentDetection.Contracts;
namespace Microsoft.ComponentDetection.Common;
[Export(typeof(ISafeFileEnumerableFactory))]
[Shared]
public class SafeFileEnumerableFactory : ISafeFileEnumerableFactory

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

@ -1,10 +1,9 @@
using System;
namespace Microsoft.ComponentDetection.Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Microsoft.ComponentDetection.Common;
public class TabularStringFormat
{
public const char DefaultVerticalLineChar = '|';

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

@ -1,12 +1,12 @@
using System;
namespace Microsoft.ComponentDetection.Common.Telemetry.Attributes;
namespace Microsoft.ComponentDetection.Common.Telemetry.Attributes;
using System;
/// <summary>
/// Denotes that a telemetry property should be treated as a Metric (numeric) value
///
/// It is up to the implementing Telemetry Service to interpret this value.
/// </summary>
public class MetricAttribute : Attribute
[AttributeUsage(AttributeTargets.Property)]
public sealed class MetricAttribute : Attribute
{
}

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

@ -1,8 +1,8 @@
using System;
namespace Microsoft.ComponentDetection.Common.Telemetry.Attributes;
using System;
namespace Microsoft.ComponentDetection.Common.Telemetry.Attributes;
public class TelemetryServiceAttribute : Attribute
[AttributeUsage(AttributeTargets.Class)]
public sealed class TelemetryServiceAttribute : Attribute
{
public TelemetryServiceAttribute(string serviceType) => this.ServiceType = serviceType;

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

@ -1,4 +1,5 @@
using System;
namespace Microsoft.ComponentDetection.Common.Telemetry;
using System;
using System.Collections.Concurrent;
using System.Composition;
using Microsoft.ComponentDetection.Common.Telemetry.Attributes;
@ -7,8 +8,6 @@ using Microsoft.ComponentDetection.Contracts;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace Microsoft.ComponentDetection.Common.Telemetry;
[Export(typeof(ITelemetryService))]
[TelemetryService(nameof(CommandLineTelemetryService))]
internal class CommandLineTelemetryService : ITelemetryService

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

@ -1,6 +1,5 @@
using Microsoft.ComponentDetection.Common.Telemetry.Records;
namespace Microsoft.ComponentDetection.Common.Telemetry;
namespace Microsoft.ComponentDetection.Common.Telemetry;
using Microsoft.ComponentDetection.Common.Telemetry.Records;
public interface ITelemetryService
{

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

@ -1,14 +1,13 @@
using System;
namespace Microsoft.ComponentDetection.Common.Telemetry.Records;
using System;
using System.Diagnostics;
using Microsoft.ComponentDetection.Common.Telemetry.Attributes;
namespace Microsoft.ComponentDetection.Common.Telemetry.Records;
public abstract class BaseDetectionTelemetryRecord : IDetectionTelemetryRecord
{
private readonly Stopwatch stopwatch = new Stopwatch();
private bool disposedValue = false;
private bool disposedValue;
protected BaseDetectionTelemetryRecord() => this.stopwatch.Start();
@ -29,6 +28,7 @@ public abstract class BaseDetectionTelemetryRecord : IDetectionTelemetryRecord
public void Dispose()
{
this.Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)

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

@ -1,6 +1,5 @@
using System;
namespace Microsoft.ComponentDetection.Common.Telemetry.Records;
namespace Microsoft.ComponentDetection.Common.Telemetry.Records;
using System;
using System.Threading;
using System.Threading.Tasks;

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

@ -1,8 +1,7 @@
using System;
namespace Microsoft.ComponentDetection.Common.Telemetry.Records;
using System;
using Microsoft.ComponentDetection.Contracts;
namespace Microsoft.ComponentDetection.Common.Telemetry.Records;
public class CommandLineInvocationTelemetryRecord : BaseDetectionTelemetryRecord
{
public override string RecordName => "CommandLineInvocation";

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

@ -1,6 +1,5 @@
using System.Runtime.CompilerServices;
namespace Microsoft.ComponentDetection.Common.Telemetry.Records;
namespace Microsoft.ComponentDetection.Common.Telemetry.Records;
using System.Runtime.CompilerServices;
public class DetectedComponentScopeRecord : BaseDetectionTelemetryRecord
{

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

@ -1,6 +1,5 @@
using System;
namespace Microsoft.ComponentDetection.Common.Telemetry.Records;
namespace Microsoft.ComponentDetection.Common.Telemetry.Records;
using System;
public interface IDetectionTelemetryRecord : IDisposable
{

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

@ -1,10 +1,9 @@
using System;
namespace Microsoft.ComponentDetection.Common.Telemetry.Records;
namespace Microsoft.ComponentDetection.Common.Telemetry.Records;
using System;
public class NuGetProjectAssetsTelemetryRecord : IDetectionTelemetryRecord, IDisposable
{
private bool disposedValue = false;
private bool disposedValue;
public string RecordName => "NuGetProjectAssets";
@ -17,6 +16,7 @@ public class NuGetProjectAssetsTelemetryRecord : IDetectionTelemetryRecord, IDis
public void Dispose()
{
this.Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)

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

@ -1,6 +1,5 @@
using System.Net;
namespace Microsoft.ComponentDetection.Common.Telemetry.Records;
namespace Microsoft.ComponentDetection.Common.Telemetry.Records;
using System.Net;
public class PypiFailureTelemetryRecord : BaseDetectionTelemetryRecord
{

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

@ -1,6 +1,5 @@
using System.Net;
namespace Microsoft.ComponentDetection.Common.Telemetry.Records;
namespace Microsoft.ComponentDetection.Common.Telemetry.Records;
using System.Net;
public class PypiRetryTelemetryRecord : BaseDetectionTelemetryRecord
{

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

@ -1,4 +1,6 @@
using System;
namespace Microsoft.ComponentDetection.Common.Telemetry;
using System;
using System.Collections.Generic;
using System.Composition;
using System.Linq;
@ -6,8 +8,6 @@ using System.Threading;
using System.Threading.Tasks;
using Microsoft.ComponentDetection.Common.Telemetry.Records;
namespace Microsoft.ComponentDetection.Common.Telemetry;
/// <summary>
/// Singleton that is responsible for relaying telemetry records to Telemetry Services.
/// </summary>

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

@ -1,10 +1,9 @@
using System;
namespace Microsoft.ComponentDetection.Contracts.BcdeModels;
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
namespace Microsoft.ComponentDetection.Contracts.BcdeModels;
// Summary:
// Details for a docker container
[JsonObject(MemberSerialization.OptOut, NamingStrategyType = typeof(CamelCaseNamingStrategy))]

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

@ -1,8 +1,7 @@
using Newtonsoft.Json;
namespace Microsoft.ComponentDetection.Contracts.BcdeModels;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
namespace Microsoft.ComponentDetection.Contracts.BcdeModels;
[JsonObject(MemberSerialization.OptOut, NamingStrategyType = typeof(CamelCaseNamingStrategy))]
public class DefaultGraphScanResult : ScanResult
{

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

@ -1,6 +1,5 @@
using System.Collections.Generic;
namespace Microsoft.ComponentDetection.Contracts.BcdeModels;
namespace Microsoft.ComponentDetection.Contracts.BcdeModels;
using System.Collections.Generic;
public class DependencyGraph : Dictionary<string, HashSet<string>>
{

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

@ -1,6 +1,5 @@
using System.Collections.Generic;
namespace Microsoft.ComponentDetection.Contracts.BcdeModels;
namespace Microsoft.ComponentDetection.Contracts.BcdeModels;
using System.Collections.Generic;
public class DependencyGraphCollection : Dictionary<string, DependencyGraphWithMetadata>
{

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

@ -1,9 +1,8 @@
using System.Collections.Generic;
namespace Microsoft.ComponentDetection.Contracts.BcdeModels;
using System.Collections.Generic;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
namespace Microsoft.ComponentDetection.Contracts.BcdeModels;
[JsonObject(MemberSerialization.OptOut, NamingStrategyType = typeof(CamelCaseNamingStrategy))]
public class DependencyGraphWithMetadata
{

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

@ -1,11 +1,10 @@
using System.Collections.Generic;
namespace Microsoft.ComponentDetection.Contracts.BcdeModels;
using System.Collections.Generic;
using Microsoft.ComponentDetection.Contracts.TypedComponent;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Serialization;
namespace Microsoft.ComponentDetection.Contracts.BcdeModels;
[JsonObject(MemberSerialization.OptOut, NamingStrategyType = typeof(CamelCaseNamingStrategy))]
public class Detector
{

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

@ -1,8 +1,7 @@
namespace Microsoft.ComponentDetection.Contracts.BcdeModels;
using System.Collections.Generic;
using Microsoft.ComponentDetection.Contracts.TypedComponent;
namespace Microsoft.ComponentDetection.Contracts.BcdeModels;
public class LayerMappedLinuxComponents
{
public IEnumerable<LinuxComponent> LinuxComponents { get; set; }

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

@ -1,10 +1,9 @@
using System.Collections.Generic;
namespace Microsoft.ComponentDetection.Contracts.BcdeModels;
using System.Collections.Generic;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Serialization;
namespace Microsoft.ComponentDetection.Contracts.BcdeModels;
[JsonObject(MemberSerialization.OptOut, NamingStrategyType = typeof(CamelCaseNamingStrategy))]
public class ScanResult
{

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

@ -1,10 +1,9 @@
using System.Collections.Generic;
namespace Microsoft.ComponentDetection.Contracts.BcdeModels;
using System.Collections.Generic;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Serialization;
namespace Microsoft.ComponentDetection.Contracts.BcdeModels;
[JsonObject(MemberSerialization.OptOut, NamingStrategyType = typeof(CamelCaseNamingStrategy))]
public class ScannedComponent
{

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

@ -1,11 +1,10 @@
using System;
namespace Microsoft.ComponentDetection.Contracts.BcdeModels;
using System;
using System.Collections.Generic;
using Microsoft.ComponentDetection.Contracts.TypedComponent;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace Microsoft.ComponentDetection.Contracts.BcdeModels;
public class TypedComponentConverter : JsonConverter
{
private readonly Dictionary<ComponentType, Type> componentTypesToTypes = new Dictionary<ComponentType, Type>
@ -35,7 +34,7 @@ public class TypedComponentConverter : JsonConverter
public override bool CanConvert(Type objectType)
{
return objectType == typeof(TypedComponent.TypedComponent);
return objectType == typeof(TypedComponent);
}
public override object ReadJson(

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

@ -1,9 +1,8 @@
namespace Microsoft.ComponentDetection.Contracts;
using System.Collections.Generic;
using System.Diagnostics;
using Microsoft.ComponentDetection.Contracts.BcdeModels;
namespace Microsoft.ComponentDetection.Contracts;
/// <summary>A detected component, found during component detection scans. This is the container for all metadata gathered during detection.</summary>
[DebuggerDisplay("{DebuggerDisplay,nq}")]
public class DetectedComponent

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

@ -1,4 +1,5 @@
using System;
namespace Microsoft.ComponentDetection.Contracts;
using System;
using System.Collections.Generic;
using System.Composition;
using System.IO;
@ -8,8 +9,6 @@ using System.Threading.Tasks.Dataflow;
using Microsoft.ComponentDetection.Contracts.Internal;
using Microsoft.ComponentDetection.Contracts.TypedComponent;
namespace Microsoft.ComponentDetection.Contracts;
/// <summary>Specialized base class for file based component detection.</summary>
public abstract class FileComponentDetector : IComponentDetector
{
@ -91,9 +90,9 @@ public abstract class FileComponentDetector : IComponentDetector
private async Task<IndividualDetectorScanResult> ProcessAsync(IObservable<ProcessRequest> processRequests, IDictionary<string, string> detectorArgs)
{
var processor = new ActionBlock<ProcessRequest>(async processRequest => await this.OnFileFound(processRequest, detectorArgs));
var processor = new ActionBlock<ProcessRequest>(async processRequest => await this.OnFileFoundAsync(processRequest, detectorArgs));
var preprocessedObserbable = await this.OnPrepareDetection(processRequests, detectorArgs);
var preprocessedObserbable = await this.OnPrepareDetectionAsync(processRequests, detectorArgs);
await preprocessedObserbable.ForEachAsync(processRequest => processor.Post(processRequest));
@ -101,7 +100,7 @@ public abstract class FileComponentDetector : IComponentDetector
await processor.Completion;
await this.OnDetectionFinished();
await this.OnDetectionFinishedAsync();
return new IndividualDetectorScanResult
{
@ -110,14 +109,14 @@ public abstract class FileComponentDetector : IComponentDetector
};
}
protected virtual Task<IObservable<ProcessRequest>> OnPrepareDetection(IObservable<ProcessRequest> processRequests, IDictionary<string, string> detectorArgs)
protected virtual Task<IObservable<ProcessRequest>> OnPrepareDetectionAsync(IObservable<ProcessRequest> processRequests, IDictionary<string, string> detectorArgs)
{
return Task.FromResult(processRequests);
}
protected abstract Task OnFileFound(ProcessRequest processRequest, IDictionary<string, string> detectorArgs);
protected abstract Task OnFileFoundAsync(ProcessRequest processRequest, IDictionary<string, string> detectorArgs);
protected virtual Task OnDetectionFinished()
protected virtual Task OnDetectionFinishedAsync()
{
return Task.CompletedTask;
}

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

@ -1,9 +1,8 @@
using System.Collections.Generic;
namespace Microsoft.ComponentDetection.Contracts;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
namespace Microsoft.ComponentDetection.Contracts;
/// <summary>
/// Service for managing execution on a command line. Generally, methods on this service expect a command line environment to be
/// where the detection tool is running, so all logic relying on them should gate on .IsCommandLineExecution().
@ -24,7 +23,7 @@ public interface ICommandLineInvocationService
/// <param name="workingDirectory">The directory under which to execute the command.</param>
/// <param name="parameters">The parameters that should be passed to the command. The parameters will be space-joined.</param>
/// <returns>Awaitable task with true if the command can be found in the local environment, false otherwise.</returns>
Task<bool> CanCommandBeLocated(string command, IEnumerable<string> additionalCandidateCommands = null, DirectoryInfo workingDirectory = null, params string[] parameters);
Task<bool> CanCommandBeLocatedAsync(string command, IEnumerable<string> additionalCandidateCommands = null, DirectoryInfo workingDirectory = null, params string[] parameters);
/// <summary>
/// Checks to see if the given command can be located -- in cases of absolute paths, this is a simple File.Exists. For non-absolute paths, all PATH entries are checked.
@ -33,7 +32,7 @@ public interface ICommandLineInvocationService
/// <param name="additionalCandidateCommands">Other commands that could satisfy the need for the first command. Assumption is that they all share similar calling patterns.</param>
/// <param name="parameters">The parameters that should be passed to the command. The parameters will be space-joined.</param>
/// <returns>Awaitable task with true if the command can be found in the local environment, false otherwise.</returns>
Task<bool> CanCommandBeLocated(string command, IEnumerable<string> additionalCandidateCommands = null, params string[] parameters);
Task<bool> CanCommandBeLocatedAsync(string command, IEnumerable<string> additionalCandidateCommands = null, params string[] parameters);
/// <summary>
/// Executes a command line command. If the command has not been located yet, CanCommandBeLocated will be invoked without the submitted parameters.
@ -43,7 +42,7 @@ public interface ICommandLineInvocationService
/// <param name="workingDirectory">The directory under which to run the command.</param>
/// <param name="parameters">The parameters that should be passed to the command. The parameters will be space-joined.</param>
/// <returns>Awaitable task with the result of executing the command, including exit code.</returns>
Task<CommandLineExecutionResult> ExecuteCommand(string command, IEnumerable<string> additionalCandidateCommands = null, DirectoryInfo workingDirectory = null, params string[] parameters);
Task<CommandLineExecutionResult> ExecuteCommandAsync(string command, IEnumerable<string> additionalCandidateCommands = null, DirectoryInfo workingDirectory = null, params string[] parameters);
/// <summary>
/// Executes a command line command. If the command has not been located yet, CanCommandBeLocated will be invoked without the submitted parameters.
@ -52,7 +51,7 @@ public interface ICommandLineInvocationService
/// <param name="additionalCandidateCommands">Other commands that could satisfy the need for the first command. Assumption is that they all share similar calling patterns.</param>
/// <param name="parameters">The parameters that should be passed to the command. The parameters will be space-joined.</param>
/// <returns>Awaitable task with the result of executing the command, including exit code.</returns>
Task<CommandLineExecutionResult> ExecuteCommand(string command, IEnumerable<string> additionalCandidateCommands = null, params string[] parameters);
Task<CommandLineExecutionResult> ExecuteCommandAsync(string command, IEnumerable<string> additionalCandidateCommands = null, params string[] parameters);
}
public class CommandLineExecutionResult

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

@ -1,9 +1,8 @@
using System.Collections.Generic;
namespace Microsoft.ComponentDetection.Contracts;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.ComponentDetection.Contracts.TypedComponent;
namespace Microsoft.ComponentDetection.Contracts;
/// <summary>
/// Basic interface required for something to satisfy component detection.
/// If you are writing a File based component detector, you may prefer the<see cref="FileComponentDetector" /> class.

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

@ -1,8 +1,7 @@
using System.Collections.Generic;
namespace Microsoft.ComponentDetection.Contracts;
using System.Collections.Generic;
using Microsoft.ComponentDetection.Contracts.BcdeModels;
namespace Microsoft.ComponentDetection.Contracts;
public interface IComponentRecorder
{
TypedComponent.TypedComponent GetComponent(string componentId);

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

@ -1,6 +1,5 @@
using System.IO;
namespace Microsoft.ComponentDetection.Contracts;
namespace Microsoft.ComponentDetection.Contracts;
using System.IO;
public interface IComponentStream
{

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

@ -1,9 +1,8 @@
using System;
namespace Microsoft.ComponentDetection.Contracts;
using System;
using System.Collections.Generic;
using System.IO;
namespace Microsoft.ComponentDetection.Contracts;
public interface IComponentStreamEnumerableFactory
{
/// <summary>

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

@ -1,10 +1,9 @@
namespace Microsoft.ComponentDetection.Contracts;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.ComponentDetection.Contracts.BcdeModels;
namespace Microsoft.ComponentDetection.Contracts;
public interface IDockerService
{
Task<bool> CanRunLinuxContainersAsync(CancellationToken cancellationToken = default);

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

@ -1,6 +1,5 @@
using System.IO;
namespace Microsoft.ComponentDetection.Contracts;
namespace Microsoft.ComponentDetection.Contracts;
using System.IO;
/// <summary>
/// Wraps some common file operations for easier testability. This interface is *only used by the command line driven app*.

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

@ -1,8 +1,7 @@
using System;
namespace Microsoft.ComponentDetection.Contracts;
using System;
using System.Runtime.CompilerServices;
namespace Microsoft.ComponentDetection.Contracts;
/// <summary>Simple abstraction around console/output file logging for component detection.</summary>
public interface ILogger
{

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

@ -1,10 +1,9 @@
using System;
namespace Microsoft.ComponentDetection.Contracts;
using System;
using System.Collections.Generic;
using System.IO;
using Microsoft.ComponentDetection.Contracts.Internal;
namespace Microsoft.ComponentDetection.Contracts;
public delegate bool ExcludeDirectoryPredicate(ReadOnlySpan<char> nameOfDirectoryToConsider, ReadOnlySpan<char> pathOfParentOfDirectoryToConsider);
public interface IObservableDirectoryWalkerFactory

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

@ -1,9 +1,8 @@
namespace Microsoft.ComponentDetection.Contracts;
using System.Collections.Generic;
using System.Linq;
using Microsoft.ComponentDetection.Contracts.BcdeModels;
namespace Microsoft.ComponentDetection.Contracts;
/// <summary>Results object for a component scan.</summary>
public class IndividualDetectorScanResult
{

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

@ -1,6 +1,5 @@
using System;
namespace Microsoft.ComponentDetection.Contracts.Internal;
namespace Microsoft.ComponentDetection.Contracts.Internal;
using System;
public class NpmAuthor
{

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

@ -1,8 +1,7 @@
using System.Collections.Generic;
namespace Microsoft.ComponentDetection.Contracts;
using System.Collections.Generic;
using System.IO;
namespace Microsoft.ComponentDetection.Contracts;
/// <summary>Request object for a component scan.</summary>
public class ScanRequest
{

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

@ -1,6 +1,5 @@
using PackageUrl;
namespace Microsoft.ComponentDetection.Contracts.TypedComponent;
using PackageUrl;
public class CargoComponent : TypedComponent
{

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

@ -1,6 +1,5 @@
using System.Runtime.Serialization;
namespace Microsoft.ComponentDetection.Contracts.TypedComponent;
namespace Microsoft.ComponentDetection.Contracts.TypedComponent;
using System.Runtime.Serialization;
// This is used in BcdeModels as well
[DataContract]

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

@ -1,6 +1,5 @@
using System;
namespace Microsoft.ComponentDetection.Contracts.TypedComponent;
namespace Microsoft.ComponentDetection.Contracts.TypedComponent;
using System;
public class GitComponent : TypedComponent
{

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

@ -1,8 +1,7 @@
using System;
namespace Microsoft.ComponentDetection.Contracts.TypedComponent;
using System;
using PackageUrl;
namespace Microsoft.ComponentDetection.Contracts.TypedComponent;
public class GoComponent : TypedComponent, IEquatable<GoComponent>
{
public GoComponent(string name, string version)
@ -38,9 +37,9 @@ public class GoComponent : TypedComponent, IEquatable<GoComponent>
public override string Id => $"{this.Name} {this.Version} - {this.Type}";
public override bool Equals(object other)
public override bool Equals(object obj)
{
return other is GoComponent otherComponent && this.Equals(otherComponent);
return obj is GoComponent otherComponent && this.Equals(otherComponent);
}
public bool Equals(GoComponent other)

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

@ -1,6 +1,5 @@
using PackageUrl;
namespace Microsoft.ComponentDetection.Contracts.TypedComponent;
namespace Microsoft.ComponentDetection.Contracts.TypedComponent;
using PackageUrl;
public class LinuxComponent : TypedComponent
{

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

@ -1,6 +1,5 @@
using PackageUrl;
namespace Microsoft.ComponentDetection.Contracts.TypedComponent;
namespace Microsoft.ComponentDetection.Contracts.TypedComponent;
using PackageUrl;
public class MavenComponent : TypedComponent
{

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

@ -1,8 +1,7 @@
using Microsoft.ComponentDetection.Contracts.Internal;
namespace Microsoft.ComponentDetection.Contracts.TypedComponent;
using Microsoft.ComponentDetection.Contracts.Internal;
using PackageUrl;
namespace Microsoft.ComponentDetection.Contracts.TypedComponent;
public class NpmComponent : TypedComponent
{
private NpmComponent()

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

@ -1,6 +1,5 @@
using PackageUrl;
namespace Microsoft.ComponentDetection.Contracts.TypedComponent;
namespace Microsoft.ComponentDetection.Contracts.TypedComponent;
using PackageUrl;
public class NuGetComponent : TypedComponent
{

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

@ -1,6 +1,5 @@
using System;
namespace Microsoft.ComponentDetection.Contracts.TypedComponent;
using System;
public class OtherComponent : TypedComponent
{

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

@ -1,8 +1,7 @@
namespace Microsoft.ComponentDetection.Contracts.TypedComponent;
using System.Diagnostics.CodeAnalysis;
using PackageUrl;
namespace Microsoft.ComponentDetection.Contracts.TypedComponent;
public class PipComponent : TypedComponent
{
private PipComponent()

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

@ -1,8 +1,7 @@
using System.Collections.Generic;
namespace Microsoft.ComponentDetection.Contracts.TypedComponent;
using System.Collections.Generic;
using PackageUrl;
namespace Microsoft.ComponentDetection.Contracts.TypedComponent;
public class PodComponent : TypedComponent
{
private PodComponent()

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

@ -1,6 +1,5 @@
using PackageUrl;
namespace Microsoft.ComponentDetection.Contracts.TypedComponent;
using PackageUrl;
public class RubyGemsComponent : TypedComponent
{

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

@ -1,6 +1,5 @@
using System;
namespace Microsoft.ComponentDetection.Contracts.TypedComponent;
namespace Microsoft.ComponentDetection.Contracts.TypedComponent;
using System;
public class SpdxComponent : TypedComponent
{

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

@ -1,4 +1,6 @@
using System;
namespace Microsoft.ComponentDetection.Contracts.TypedComponent;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using Microsoft.ComponentDetection.Contracts.BcdeModels;
@ -7,8 +9,6 @@ using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Serialization;
using PackageUrl;
namespace Microsoft.ComponentDetection.Contracts.TypedComponent;
[JsonObject(MemberSerialization.OptOut, NamingStrategyType = typeof(CamelCaseNamingStrategy))]
[JsonConverter(typeof(TypedComponentConverter))]
[DebuggerDisplay("{DebuggerDisplay,nq}")]

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

@ -1,6 +1,5 @@
using PackageUrl;
namespace Microsoft.ComponentDetection.Contracts.TypedComponent;
namespace Microsoft.ComponentDetection.Contracts.TypedComponent;
using PackageUrl;
public class VcpkgComponent : TypedComponent
{

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

@ -1,3 +1,4 @@
namespace Microsoft.ComponentDetection.Detectors.CocoaPods;
using System;
using System.Collections.Generic;
using System.Composition;
@ -12,8 +13,6 @@ using YamlDotNet.Core;
using YamlDotNet.Core.Events;
using YamlDotNet.Serialization;
namespace Microsoft.ComponentDetection.Detectors.CocoaPods;
[Export(typeof(IComponentDetector))]
public class PodComponentDetector : FileComponentDetector
{
@ -27,7 +26,7 @@ public class PodComponentDetector : FileComponentDetector
public override int Version { get; } = 2;
protected override async Task OnFileFound(ProcessRequest processRequest, IDictionary<string, string> detectorArgs)
protected override async Task OnFileFoundAsync(ProcessRequest processRequest, IDictionary<string, string> detectorArgs)
{
var singleFileComponentRecorder = processRequest.SingleFileComponentRecorder;
var file = processRequest.ComponentStream;
@ -36,7 +35,7 @@ public class PodComponentDetector : FileComponentDetector
try
{
var podfileLock = await ParsePodfileLock(file);
var podfileLock = await ParsePodfileLockAsync(file);
this.ProcessPodfileLock(singleFileComponentRecorder, podfileLock);
}
@ -46,7 +45,7 @@ public class PodComponentDetector : FileComponentDetector
}
}
private static async Task<PodfileLock> ParsePodfileLock(IComponentStream file)
private static async Task<PodfileLock> ParsePodfileLockAsync(IComponentStream file)
{
var fileContent = await new StreamReader(file.Stream).ReadToEndAsync();
var input = new StringReader(fileContent);

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

@ -1,4 +1,5 @@
using System;
namespace Microsoft.ComponentDetection.Detectors.Dockerfile;
using System;
using System.Collections.Generic;
using System.Composition;
using System.IO;
@ -11,8 +12,6 @@ using Microsoft.ComponentDetection.Contracts.Internal;
using Microsoft.ComponentDetection.Contracts.TypedComponent;
using Valleysoft.DockerfileModel;
namespace Microsoft.ComponentDetection.Detectors.Dockerfile;
[Export(typeof(IComponentDetector))]
public class DockerfileComponentDetector : FileComponentDetector, IDefaultOffComponentDetector
{
@ -32,7 +31,7 @@ public class DockerfileComponentDetector : FileComponentDetector, IDefaultOffCom
public override int Version => 1;
protected override async Task OnFileFound(ProcessRequest processRequest, IDictionary<string, string> detectorArgs)
protected override async Task OnFileFoundAsync(ProcessRequest processRequest, IDictionary<string, string> detectorArgs)
{
var singleFileComponentRecorder = processRequest.SingleFileComponentRecorder;
var file = processRequest.ComponentStream;
@ -48,7 +47,7 @@ public class DockerfileComponentDetector : FileComponentDetector, IDefaultOffCom
}
var stageNameMap = new Dictionary<string, string>();
var dockerFileComponent = this.ParseDockerFile(contents, file.Location, singleFileComponentRecorder, stageNameMap);
var dockerFileComponent = this.ParseDockerFileAsync(contents, file.Location, singleFileComponentRecorder, stageNameMap);
}
catch (Exception e)
{
@ -57,7 +56,7 @@ public class DockerfileComponentDetector : FileComponentDetector, IDefaultOffCom
}
}
private Task ParseDockerFile(string fileContents, string fileLocation, ISingleFileComponentRecorder singleFileComponentRecorder, Dictionary<string, string> stageNameMap)
private Task ParseDockerFileAsync(string fileContents, string fileLocation, ISingleFileComponentRecorder singleFileComponentRecorder, Dictionary<string, string> stageNameMap)
{
var dockerfileModel = Valleysoft.DockerfileModel.Dockerfile.Parse(fileContents);
var instructions = dockerfileModel.Items;

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

@ -1,4 +1,5 @@
using System;
namespace Microsoft.ComponentDetection.Detectors.Go;
using System;
using System.Collections.Generic;
using System.Composition;
using System.IO;
@ -11,8 +12,6 @@ using Microsoft.ComponentDetection.Contracts.Internal;
using Microsoft.ComponentDetection.Contracts.TypedComponent;
using Newtonsoft.Json;
namespace Microsoft.ComponentDetection.Detectors.Go;
[Export(typeof(IComponentDetector))]
public class GoComponentDetector : FileComponentDetector
{
@ -38,7 +37,7 @@ public class GoComponentDetector : FileComponentDetector
public override int Version => 6;
protected override async Task OnFileFound(ProcessRequest processRequest, IDictionary<string, string> detectorArgs)
protected override async Task OnFileFoundAsync(ProcessRequest processRequest, IDictionary<string, string> detectorArgs)
{
var singleFileComponentRecorder = processRequest.SingleFileComponentRecorder;
var file = processRequest.ComponentStream;
@ -54,7 +53,7 @@ public class GoComponentDetector : FileComponentDetector
{
if (!this.IsGoCliManuallyDisabled())
{
wasGoCliScanSuccessful = await this.UseGoCliToScan(file.Location, singleFileComponentRecorder);
wasGoCliScanSuccessful = await this.UseGoCliToScanAsync(file.Location, singleFileComponentRecorder);
}
else
{
@ -94,14 +93,14 @@ public class GoComponentDetector : FileComponentDetector
default:
{
throw new Exception("Unexpected file type detected in go detector");
throw new InvalidOperationException("Unexpected file type detected in go detector");
}
}
}
}
}
private async Task<bool> UseGoCliToScan(string location, ISingleFileComponentRecorder singleFileComponentRecorder)
private async Task<bool> UseGoCliToScanAsync(string location, ISingleFileComponentRecorder singleFileComponentRecorder)
{
using var record = new GoGraphTelemetryRecord();
record.WasGraphSuccessful = false;
@ -109,7 +108,7 @@ public class GoComponentDetector : FileComponentDetector
var projectRootDirectory = Directory.GetParent(location);
record.ProjectRoot = projectRootDirectory.FullName;
var isGoAvailable = await this.CommandLineInvocationService.CanCommandBeLocated("go", null, workingDirectory: projectRootDirectory, new[] { "version" });
var isGoAvailable = await this.CommandLineInvocationService.CanCommandBeLocatedAsync("go", null, workingDirectory: projectRootDirectory, new[] { "version" });
record.IsGoAvailable = isGoAvailable;
if (!isGoAvailable)
@ -121,7 +120,7 @@ public class GoComponentDetector : FileComponentDetector
this.Logger.LogInfo("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.ExecuteCommand("go", null, workingDirectory: projectRootDirectory, new[] { "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:\n {goDependenciesProcess.StdErr}");
@ -131,7 +130,7 @@ public class GoComponentDetector : FileComponentDetector
this.RecordBuildDependencies(goDependenciesProcess.StdOut, singleFileComponentRecorder);
var generateGraphProcess = await this.CommandLineInvocationService.ExecuteCommand("go", null, workingDirectory: projectRootDirectory, new List<string> { "mod", "graph" }.ToArray());
var generateGraphProcess = await this.CommandLineInvocationService.ExecuteCommandAsync("go", null, workingDirectory: projectRootDirectory, new List<string> { "mod", "graph" }.ToArray());
if (generateGraphProcess.ExitCode == 0)
{
this.PopulateDependencyGraph(generateGraphProcess.StdOut, singleFileComponentRecorder);

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

@ -1,3 +1,4 @@
namespace Microsoft.ComponentDetection.Detectors.Gradle;
using System;
using System.Collections.Generic;
using System.Composition;
@ -8,8 +9,6 @@ using Microsoft.ComponentDetection.Contracts;
using Microsoft.ComponentDetection.Contracts.Internal;
using Microsoft.ComponentDetection.Contracts.TypedComponent;
namespace Microsoft.ComponentDetection.Detectors.Gradle;
[Export(typeof(IComponentDetector))]
public class GradleComponentDetector : FileComponentDetector, IComponentDetector
{
@ -25,7 +24,7 @@ public class GradleComponentDetector : FileComponentDetector, IComponentDetector
public override int Version { get; } = 2;
protected override Task OnFileFound(ProcessRequest processRequest, IDictionary<string, string> detectorArgs)
protected override Task OnFileFoundAsync(ProcessRequest processRequest, IDictionary<string, string> detectorArgs)
{
var singleFileComponentRecorder = processRequest.SingleFileComponentRecorder;
var file = processRequest.ComponentStream;

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

@ -1,4 +1,5 @@
using System;
namespace Microsoft.ComponentDetection.Detectors.Ivy;
using System;
using System.Collections.Generic;
using System.Composition;
using System.IO;
@ -12,8 +13,6 @@ using Microsoft.ComponentDetection.Contracts.Internal;
using Microsoft.ComponentDetection.Contracts.TypedComponent;
using Newtonsoft.Json.Linq;
namespace Microsoft.ComponentDetection.Detectors.Ivy;
/// <summary>
/// Detector for Maven components declared in ivy.xml files for Java projects that are built using Apache Ant
/// and Apache Ivy.
@ -58,7 +57,7 @@ public class IvyDetector : FileComponentDetector, IExperimentalDetector
[Import]
public ICommandLineInvocationService CommandLineInvocationService { get; set; }
protected override async Task<IObservable<ProcessRequest>> OnPrepareDetection(IObservable<ProcessRequest> processRequests, IDictionary<string, string> detectorArgs)
protected override async Task<IObservable<ProcessRequest>> OnPrepareDetectionAsync(IObservable<ProcessRequest> processRequests, IDictionary<string, string> detectorArgs)
{
if (await this.IsAntLocallyAvailableAsync())
{
@ -69,7 +68,7 @@ public class IvyDetector : FileComponentDetector, IExperimentalDetector
return Enumerable.Empty<ProcessRequest>().ToObservable();
}
protected override async Task OnFileFound(ProcessRequest processRequest, IDictionary<string, string> detectorArgs)
protected override async Task OnFileFoundAsync(ProcessRequest processRequest, IDictionary<string, string> detectorArgs)
{
var singleFileComponentRecorder = processRequest.SingleFileComponentRecorder;
var ivyXmlFile = processRequest.ComponentStream;
@ -169,14 +168,14 @@ public class IvyDetector : FileComponentDetector, IExperimentalDetector
{
// Note: calling CanCommandBeLocated populates a cache of valid commands. If it is not called before ExecuteCommand,
// ExecuteCommand calls CanCommandBeLocated with no arguments, which fails.
return await this.CommandLineInvocationService.CanCommandBeLocated(PrimaryCommand, AdditionalValidCommands, AntVersionArgument);
return await this.CommandLineInvocationService.CanCommandBeLocatedAsync(PrimaryCommand, AdditionalValidCommands, AntVersionArgument);
}
private async Task<bool> RunAntToDetectDependenciesAsync(string workingDirectory)
{
var ret = false;
this.Logger.LogVerbose($"Executing command `ant resolve-dependencies` in directory {workingDirectory}");
var result = await this.CommandLineInvocationService.ExecuteCommand(PrimaryCommand, additionalCandidateCommands: AdditionalValidCommands, "-buildfile", workingDirectory, "resolve-dependencies");
var result = await this.CommandLineInvocationService.ExecuteCommandAsync(PrimaryCommand, additionalCandidateCommands: AdditionalValidCommands, "-buildfile", workingDirectory, "resolve-dependencies");
if (result.ExitCode == 0)
{
this.Logger.LogVerbose("Ant command succeeded");

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

@ -1,9 +1,8 @@
namespace Microsoft.ComponentDetection.Detectors.Linux.Contracts;
using System.Collections.Generic;
using Microsoft.ComponentDetection.Contracts;
using Microsoft.ComponentDetection.Contracts.BcdeModels;
namespace Microsoft.ComponentDetection.Detectors.Linux.Contracts;
internal class ImageScanningResult
{
public ContainerDetails ContainerDetails { get; set; }

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

@ -1,6 +1,5 @@
using System;
namespace Microsoft.ComponentDetection.Detectors.Linux.Exceptions;
namespace Microsoft.ComponentDetection.Detectors.Linux.Exceptions;
using System;
public class MissingContainerDetailException : Exception
{
@ -8,4 +7,13 @@ public class MissingContainerDetailException : Exception
: base($"No container details information could be found for image ${imageId}")
{
}
public MissingContainerDetailException()
{
}
public MissingContainerDetailException(string message, Exception innerException)
: base(message, innerException)
{
}
}

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

@ -1,10 +1,9 @@
using System.Collections.Generic;
namespace Microsoft.ComponentDetection.Detectors.Linux;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.ComponentDetection.Contracts.BcdeModels;
namespace Microsoft.ComponentDetection.Detectors.Linux;
public interface ILinuxScanner
{
Task<IEnumerable<LayerMappedLinuxComponents>> ScanLinuxAsync(string imageHash, IEnumerable<DockerLayer> dockerLayers, int baseImageLayerCount, CancellationToken cancellationToken = default);

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

@ -1,3 +1,4 @@
namespace Microsoft.ComponentDetection.Detectors.Linux;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
@ -14,8 +15,6 @@ using Microsoft.ComponentDetection.Contracts.TypedComponent;
using Microsoft.ComponentDetection.Detectors.Linux.Contracts;
using Microsoft.ComponentDetection.Detectors.Linux.Exceptions;
namespace Microsoft.ComponentDetection.Detectors.Linux;
[Export(typeof(IComponentDetector))]
public class LinuxContainerDetector : IComponentDetector
{
@ -165,7 +164,7 @@ public class LinuxContainerDetector : IComponentDetector
{
var internalContainerDetails = kvp.Value;
var image = kvp.Key;
var baseImageLayerCount = await this.GetBaseImageLayerCount(internalContainerDetails, image, cancellationToken);
var baseImageLayerCount = await this.GetBaseImageLayerCountAsync(internalContainerDetails, image, cancellationToken);
// Update the layer information to specify if a layer was fond in the specified baseImage
internalContainerDetails.Layers = internalContainerDetails.Layers.Select(layer => new DockerLayer
@ -205,7 +204,7 @@ public class LinuxContainerDetector : IComponentDetector
return await Task.WhenAll(scanTasks);
}
private async Task<int> GetBaseImageLayerCount(ContainerDetails scannedImageDetails, string image, CancellationToken cancellationToken = default)
private async Task<int> GetBaseImageLayerCountAsync(ContainerDetails scannedImageDetails, string image, CancellationToken cancellationToken = default)
{
using var record = new LinuxContainerDetectorLayerAwareness
{

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

@ -1,3 +1,4 @@
namespace Microsoft.ComponentDetection.Detectors.Linux;
using System;
using System.Collections.Generic;
using System.Composition;
@ -11,8 +12,6 @@ using Microsoft.ComponentDetection.Contracts.TypedComponent;
using Microsoft.ComponentDetection.Detectors.Linux.Contracts;
using Newtonsoft.Json;
namespace Microsoft.ComponentDetection.Detectors.Linux;
[Export(typeof(ILinuxScanner))]
public class LinuxScanner : ILinuxScanner
{

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

@ -1,6 +1,5 @@
using System.Collections.Generic;
namespace Microsoft.ComponentDetection.Detectors.Maven;
namespace Microsoft.ComponentDetection.Detectors.Maven;
using System.Collections.Generic;
/// <summary>
/// Internal state holder used by Maven detector.

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

@ -1,15 +1,14 @@
using System.Threading.Tasks;
namespace Microsoft.ComponentDetection.Detectors.Maven;
using System.Threading.Tasks;
using Microsoft.ComponentDetection.Contracts.Internal;
namespace Microsoft.ComponentDetection.Detectors.Maven;
public interface IMavenCommandService
{
string BcdeMvnDependencyFileName { get; }
Task<bool> MavenCLIExists();
Task<bool> MavenCLIExistsAsync();
Task GenerateDependenciesFile(ProcessRequest processRequest);
Task GenerateDependenciesFileAsync(ProcessRequest processRequest);
void ParseDependenciesFile(ProcessRequest processRequest);
}

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

@ -1,6 +1,5 @@
using Microsoft.ComponentDetection.Contracts;
namespace Microsoft.ComponentDetection.Detectors.Maven;
namespace Microsoft.ComponentDetection.Detectors.Maven;
using Microsoft.ComponentDetection.Contracts;
public interface IMavenStyleDependencyGraphParserService
{

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

@ -1,12 +1,11 @@
using System;
namespace Microsoft.ComponentDetection.Detectors.Maven;
using System;
using System.Composition;
using System.IO;
using System.Threading.Tasks;
using Microsoft.ComponentDetection.Contracts;
using Microsoft.ComponentDetection.Contracts.Internal;
namespace Microsoft.ComponentDetection.Detectors.Maven;
[Export(typeof(IMavenCommandService))]
public class MavenCommandService : IMavenCommandService
{
@ -27,16 +26,16 @@ public class MavenCommandService : IMavenCommandService
public string BcdeMvnDependencyFileName => "bcde.mvndeps";
public async Task<bool> MavenCLIExists()
public async Task<bool> MavenCLIExistsAsync()
{
return await this.CommandLineInvocationService.CanCommandBeLocated(PrimaryCommand, AdditionalValidCommands, MvnVersionArgument);
return await this.CommandLineInvocationService.CanCommandBeLocatedAsync(PrimaryCommand, AdditionalValidCommands, MvnVersionArgument);
}
public async Task GenerateDependenciesFile(ProcessRequest processRequest)
public async Task GenerateDependenciesFileAsync(ProcessRequest processRequest)
{
var pomFile = processRequest.ComponentStream;
var cliParameters = new[] { "dependency:tree", "-B", $"-DoutputFile={this.BcdeMvnDependencyFileName}", "-DoutputType=text", $"-f{pomFile.Location}" };
var result = await this.CommandLineInvocationService.ExecuteCommand(PrimaryCommand, AdditionalValidCommands, cliParameters);
var result = await this.CommandLineInvocationService.ExecuteCommandAsync(PrimaryCommand, AdditionalValidCommands, cliParameters);
if (result.ExitCode != 0)
{
this.Logger.LogVerbose($"Mvn execution failed for pom file: {pomFile.Location}");

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

@ -1,12 +1,11 @@
using System;
namespace Microsoft.ComponentDetection.Detectors.Maven;
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using Microsoft.ComponentDetection.Contracts;
using Microsoft.ComponentDetection.Contracts.BcdeModels;
using Microsoft.ComponentDetection.Contracts.TypedComponent;
namespace Microsoft.ComponentDetection.Detectors.Maven;
public static class MavenParsingUtilities
{
private static readonly Dictionary<string, DependencyScope> MavenScopeToDependencyScopeMapping = new Dictionary<string, DependencyScope>()

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