Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ Component Detection supports detecting libraries from the following ecosystems:
| Ecosystem | Scanning | Graph Creation |
| -------------------------------------------------------------------------------- | ----------------------------------------------- | -------------- |
| [CocoaPods](docs/detectors/cocoapods.md) | ✔ | ✔ |
| [Composer (PHP, experimental)](docs/detectors/composer.md) | ✔ | ✔ |
| [Conan](docs/detectors/conan.md) | ✔ | ❌ |
| [Conda (Python)](docs/detectors/conda.md) | ✔ | ✔ |
| [Docker Compose](docs/detectors/dockercompose.md) | ✔ | ❌ |
Expand Down
10 changes: 10 additions & 0 deletions docs/creating-a-new-detector.md
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,16 @@ The main parsing logic. Called once per matched file to:
- Extract component information
- Build the dependency graph via `ComponentRecorder`

For JSON formats where comments and trailing commas can be tolerated, derived
detectors can opt in to `FileComponentDetector.LenientJsonSerializerOptions`:

```csharp
var root = await JsonSerializer.DeserializeAsync<JsonElement>(stream, LenientJsonSerializerOptions, cancellationToken);
```

These options skip comments and allow trailing commas. They do not relax other
JSON syntax or package validation, and do not change parsing defaults automatically.

### 3. `OnDetectionFinishedAsync` (Optional)

Runs after all files are processed. Use this for:
Expand Down
6 changes: 6 additions & 0 deletions docs/detectors/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,12 @@
| -------------------- | ------ |
| PodComponentDetector | Stable |

- [Composer](composer.md)

| Detector | Status |
| ------------------------- | ------------ |
| ComposerComponentDetector | Experimental |

- [Conan](conan.md)

| Detector | Status |
Expand Down
45 changes: 45 additions & 0 deletions docs/detectors/composer.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
# Composer

The Composer detector finds packages used by PHP projects, including development
dependencies and the packages they depend on. PHP and Composer do not need to be
installed to scan the project's package files.

## How detection works

The detector looks for `composer.lock` and `composer.json` in your project:

1. **If a lockfile exists**, it uses the package versions recorded there.
The `composer.json` in the same folder helps identify which packages your
project uses directly.
2. **If there is no lockfile**, it looks for installed package information in
`vendor\composer\installed.json`.
3. **If only `composer.json` is available**, it reports dependencies pinned to
exact versions, such as `1.2.3`. Ranges such as `^1.2` are skipped with a warning,
because they do not tell us which version was actually installed.

For a custom vendor directory, the detector first checks the
[`COMPOSER_VENDOR_DIR` environment variable](https://getcomposer.org/doc/03-cli.md#composer_vendor_dir),
then `config.vendor-dir` in `composer.json`. Otherwise, it uses `vendor`.

For more accurate results, run `composer install` before scanning so the lockfile
and installed package information are available.

Results include dependency relationships and development flags when that
information is available. If your repository contains several PHP projects, each
is scanned separately. Vendor packages already covered by a parent project are
not scanned again.

## PHP environment

When PHP and Composer are available on `PATH`, the detector can also report the
local PHP version, Composer, extensions, and related libraries. It checks each
project separately and does not run this check inside vendor folders.

These entries use the `PhpSdk` component type and are marked as development
dependencies. They describe the machine running the scan, not necessarily the
environment where your application will run. Excluding development dependencies
also excludes these entries. Simulated versions from `config.platform` are not
reported as installed software.

Missing tools or a failed environment check do not stop package detection.
The scan does not install or update packages.
8 changes: 6 additions & 2 deletions docs/schema/manifest.schema.json
Original file line number Diff line number Diff line change
Expand Up @@ -154,7 +154,9 @@
"Conan",
"Swift",
"DotNet",
"CppSdk"
"CppSdk",
"Composer",
"PhpSdk"
]
}
}
Expand Down Expand Up @@ -428,7 +430,9 @@
"Conan",
"Swift",
"DotNet",
"CppSdk"
"CppSdk",
"Composer",
"PhpSdk"
]
},
"id": {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,19 +21,32 @@ internal class CommandLineInvocationService : ICommandLineInvocationService
/// <inheritdoc/>
public async Task<bool> CanCommandBeLocatedAsync(string command, IEnumerable<string> additionalCandidateCommands = null, DirectoryInfo workingDirectory = null, params string[] parameters)
{
return await this.CanCommandBeLocatedAsync(command, additionalCandidateCommands, workingDirectory, CancellationToken.None, parameters);
}

/// <inheritdoc/>
public async Task<bool> CanCommandBeLocatedAsync(
string command,
IEnumerable<string> additionalCandidateCommands,
DirectoryInfo workingDirectory,
CancellationToken cancellationToken,
params string[] parameters)
{
cancellationToken.ThrowIfCancellationRequested();
additionalCandidateCommands ??= [];
parameters ??= [];
var allCommands = new[] { command }.Concat(additionalCandidateCommands);
if (!this.commandLocatableCache.TryGetValue(command, out var validCommand))
{
foreach (var commandToTry in allCommands)
{
cancellationToken.ThrowIfCancellationRequested();
using var record = new CommandLineInvocationTelemetryRecord();

var joinedParameters = string.Join(" ", parameters);
try
{
var result = await RunProcessAsync(commandToTry, joinedParameters, workingDirectory);
var result = await RunProcessAsync(commandToTry, joinedParameters, workingDirectory, cancellationToken);
record.Track(result, commandToTry, joinedParameters);

if (result.ExitCode == 0)
Expand Down Expand Up @@ -61,7 +74,7 @@ public async Task<CommandLineExecutionResult> ExecuteCommandAsync(
CancellationToken cancellationToken = default,
params string[] parameters)
{
var isCommandLocatable = await this.CanCommandBeLocatedAsync(command, additionalCandidateCommands, workingDirectory, parameters);
var isCommandLocatable = await this.CanCommandBeLocatedAsync(command, additionalCandidateCommands, workingDirectory, cancellationToken, parameters);
if (!isCommandLocatable)
{
throw new InvalidOperationException(
Expand All @@ -80,7 +93,7 @@ public async Task<CommandLineExecutionResult> ExecuteCommandAsync(
var joinedParameters = string.Join(" ", parameters);
try
{
var result = await RunProcessAsync(pathToRun, joinedParameters, workingDirectory, cancellationToken);
var result = await RunProcessAsync(pathToRun, joinedParameters, workingDirectory, cancellationToken: cancellationToken);
record.Track(result, pathToRun, joinedParameters);
return result;
}
Expand Down Expand Up @@ -125,13 +138,9 @@ public async Task<CommandLineExecutionResult> ExecuteCommandAsync(string command
return await this.ExecuteCommandAsync(command, additionalCandidateCommands, workingDirectory: null, CancellationToken.None, parameters);
}

private static Task<CommandLineExecutionResult> RunProcessAsync(string fileName, string parameters, DirectoryInfo workingDirectory = null)
{
return RunProcessAsync(fileName, parameters, workingDirectory, CancellationToken.None);
}

private static Task<CommandLineExecutionResult> RunProcessAsync(string fileName, string parameters, DirectoryInfo workingDirectory = null, CancellationToken cancellationToken = default)
{
cancellationToken.ThrowIfCancellationRequested();
var tcs = new TaskCompletionSource<CommandLineExecutionResult>();

if (fileName.EndsWith(".cmd") || fileName.EndsWith(".bat"))
Expand Down Expand Up @@ -188,7 +197,7 @@ private static Task<CommandLineExecutionResult> RunProcessAsync(string fileName,
{
try
{
process.Kill();
process.Kill(entireProcessTree: true);
}
catch (InvalidOperationException)
{
Expand All @@ -199,6 +208,6 @@ private static Task<CommandLineExecutionResult> RunProcessAsync(string fileName,
}
});

return tcs.Task;
return tcs.Task.WaitAsync(cancellationToken);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,8 @@ internal static class TypedComponentMapping
{ nameof(ComponentType.DotNet), typeof(DotNetComponent) },
{ nameof(ComponentType.Swift), typeof(SwiftComponent) },
{ nameof(ComponentType.CppSdk), typeof(CppSdkComponent) },
{ nameof(ComponentType.Composer), typeof(ComposerComponent) },
{ nameof(ComponentType.PhpSdk), typeof(PhpSdkComponent) },
};

/// <summary>
Expand Down
3 changes: 3 additions & 0 deletions src/Microsoft.ComponentDetection.Contracts/DetectorClass.cs
Original file line number Diff line number Diff line change
Expand Up @@ -53,4 +53,7 @@ public enum DetectorClass

/// <summary>Indicates a detector applies to Helm chart image references.</summary>
Helm,

/// <summary>Indicates a detector applies to Composer packages.</summary>
Composer,
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ namespace Microsoft.ComponentDetection.Contracts;
using System.IO;
using System.Linq;
using System.Reactive.Linq;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using System.Threading.Tasks.Dataflow;
Expand All @@ -17,6 +18,15 @@ namespace Microsoft.ComponentDetection.Contracts;
/// <summary>Specialized base class for file based component detection.</summary>
public abstract class FileComponentDetector : IComponentDetector
{
/// <summary>
/// Gets opt-in JSON deserialization options that skip comments and allow trailing commas.
/// </summary>
protected static readonly JsonSerializerOptions LenientJsonSerializerOptions = new()
{
ReadCommentHandling = JsonCommentHandling.Skip,
AllowTrailingCommas = true,
};

/// <summary>
/// Gets or sets the factory for handing back component streams to File detectors.
/// </summary>
Expand Down Expand Up @@ -124,6 +134,8 @@ private async Task<IndividualDetectorScanResult> ProcessAsync(
async processRequest => await this.OnFileFoundAsync(processRequest, detectorArgs, cleanupCreatedFiles, cancellationToken),
new ExecutionDataflowBlockOptions
{
CancellationToken = cancellationToken,

// MaxDegreeOfParallelism is the lower of the processor count and the max threads arg that the customer passed in
MaxDegreeOfParallelism = threadsToUse,
});
Expand Down
Loading
Loading