-
Notifications
You must be signed in to change notification settings - Fork 104
Users/jcfiorenzano23/go 117 experiment #1359
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
88bb9fb
Created experimental go detector
jcfiorenzano 198c540
Created experiment configuration
jcfiorenzano a6e6433
Added unit tests
jcfiorenzano c99d4eb
Registered the interfaces
jcfiorenzano 0b28def
Resolved issue resolving ILogger
jcfiorenzano de101b3
Updated detector version and using the env var to determine if the gr…
jcfiorenzano File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
201 changes: 201 additions & 0 deletions
201
src/Microsoft.ComponentDetection.Detectors/go/Go117ComponentDetector.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,201 @@ | ||
namespace Microsoft.ComponentDetection.Detectors.Go; | ||
|
||
using System; | ||
using System.Collections.Generic; | ||
using System.IO; | ||
using System.Linq; | ||
using System.Reactive.Linq; | ||
using System.Text.RegularExpressions; | ||
using System.Threading; | ||
using System.Threading.Tasks; | ||
using Microsoft.ComponentDetection.Common; | ||
using Microsoft.ComponentDetection.Common.Telemetry.Records; | ||
using Microsoft.ComponentDetection.Contracts; | ||
using Microsoft.ComponentDetection.Contracts.Internal; | ||
using Microsoft.ComponentDetection.Contracts.TypedComponent; | ||
using Microsoft.Extensions.Logging; | ||
|
||
public class Go117ComponentDetector : FileComponentDetector, IExperimentalDetector | ||
{ | ||
private readonly HashSet<string> projectRoots = []; | ||
|
||
private readonly ICommandLineInvocationService commandLineInvocationService; | ||
private readonly IGoParserFactory goParserFactory; | ||
private readonly IEnvironmentVariableService envVarService; | ||
|
||
public Go117ComponentDetector( | ||
IComponentStreamEnumerableFactory componentStreamEnumerableFactory, | ||
IObservableDirectoryWalkerFactory walkerFactory, | ||
ICommandLineInvocationService commandLineInvocationService, | ||
IEnvironmentVariableService envVarService, | ||
ILogger<GoComponentDetector> logger, | ||
IFileUtilityService fileUtilityService, | ||
IGoParserFactory goParserFactory) | ||
{ | ||
this.ComponentStreamEnumerableFactory = componentStreamEnumerableFactory; | ||
this.Scanner = walkerFactory; | ||
this.commandLineInvocationService = commandLineInvocationService; | ||
this.Logger = logger; | ||
this.goParserFactory = goParserFactory; | ||
this.envVarService = envVarService; | ||
} | ||
|
||
public override string Id => "Go117"; | ||
|
||
public override IEnumerable<string> Categories => [Enum.GetName(typeof(DetectorClass), DetectorClass.GoMod)]; | ||
|
||
public override IList<string> SearchPatterns { get; } = ["go.mod", "go.sum"]; | ||
|
||
public override IEnumerable<ComponentType> SupportedComponentTypes { get; } = [ComponentType.Go]; | ||
|
||
public override int Version => 1; | ||
|
||
protected override Task<IObservable<ProcessRequest>> OnPrepareDetectionAsync( | ||
IObservable<ProcessRequest> processRequests, | ||
IDictionary<string, string> detectorArgs, | ||
CancellationToken cancellationToken = default) | ||
{ | ||
var goModProcessRequests = processRequests.Where(processRequest => | ||
{ | ||
if (Path.GetFileName(processRequest.ComponentStream.Location) != "go.sum") | ||
{ | ||
return true; | ||
} | ||
|
||
var goModFile = this.FindAdjacentGoModComponentStreams(processRequest).FirstOrDefault(); | ||
|
||
try | ||
{ | ||
if (goModFile == null) | ||
{ | ||
this.Logger.LogDebug( | ||
"go.sum file found without an adjacent go.mod file. Location: {Location}", | ||
processRequest.ComponentStream.Location); | ||
|
||
return true; | ||
} | ||
|
||
return GoDetectorUtils.ShouldRemoveGoSumFromDetection(goSumFilePath: processRequest.ComponentStream.Location, goModFile, this.Logger); | ||
} | ||
finally | ||
{ | ||
goModFile?.Stream.Dispose(); | ||
} | ||
}); | ||
|
||
return Task.FromResult(goModProcessRequests); | ||
} | ||
|
||
protected override async Task OnFileFoundAsync(ProcessRequest processRequest, IDictionary<string, string> detectorArgs, CancellationToken cancellationToken = default) | ||
{ | ||
var singleFileComponentRecorder = processRequest.SingleFileComponentRecorder; | ||
var file = processRequest.ComponentStream; | ||
|
||
var projectRootDirectory = Directory.GetParent(file.Location); | ||
if (this.projectRoots.Any(path => projectRootDirectory.FullName.StartsWith(path))) | ||
{ | ||
return; | ||
} | ||
|
||
var record = new GoGraphTelemetryRecord(); | ||
var fileExtension = Path.GetExtension(file.Location).ToUpperInvariant(); | ||
switch (fileExtension) | ||
{ | ||
case ".MOD": | ||
{ | ||
this.Logger.LogDebug("Found Go.mod: {Location}", file.Location); | ||
await this.goParserFactory.CreateParser(GoParserType.GoMod, this.Logger).ParseAsync(singleFileComponentRecorder, file, record); | ||
|
||
if (await this.ShouldRunGoGraphAsync()) | ||
{ | ||
await GoDependencyGraphUtility.GenerateAndPopulateDependencyGraphAsync( | ||
this.commandLineInvocationService, | ||
this.Logger, | ||
singleFileComponentRecorder, | ||
projectRootDirectory.FullName, | ||
record, | ||
cancellationToken); | ||
} | ||
|
||
break; | ||
} | ||
|
||
case ".SUM": | ||
{ | ||
this.Logger.LogDebug("Found Go.sum: {Location}", file.Location); | ||
await this.goParserFactory.CreateParser(GoParserType.GoSum, this.Logger).ParseAsync(singleFileComponentRecorder, file, record); | ||
break; | ||
} | ||
|
||
default: | ||
{ | ||
throw new InvalidOperationException("Unexpected file type detected in go detector"); | ||
} | ||
} | ||
} | ||
|
||
private bool IsGoCliManuallyDisabled() | ||
{ | ||
return this.envVarService.IsEnvironmentVariableValueTrue("DisableGoCliScan"); | ||
} | ||
|
||
private async Task<bool> ShouldRunGoGraphAsync() | ||
{ | ||
if (this.IsGoCliManuallyDisabled()) | ||
{ | ||
return false; | ||
} | ||
|
||
var goVersion = await this.GetGoVersionAsync(); | ||
if (goVersion == null) | ||
{ | ||
return false; | ||
} | ||
|
||
return goVersion >= new Version(1, 11); | ||
} | ||
|
||
private async Task<Version> GetGoVersionAsync() | ||
{ | ||
var processExecution = await this.commandLineInvocationService.ExecuteCommandAsync("go", null, null, cancellationToken: default, new List<string> { "version" }.ToArray()); | ||
if (processExecution.ExitCode != 0) | ||
{ | ||
return null; | ||
} | ||
|
||
// Define the regular expression pattern to match the version number | ||
var versionPattern = @"go version go(\d+\.\d+\.\d+)"; | ||
var match = Regex.Match(processExecution.StdOut, versionPattern); | ||
|
||
if (match.Success) | ||
{ | ||
// Extract the version number from the match | ||
var versionStr = match.Groups[1].Value; | ||
return new Version(versionStr); | ||
} | ||
|
||
return null; | ||
} | ||
|
||
private IEnumerable<ComponentStream> FindAdjacentGoModComponentStreams(ProcessRequest processRequest) => | ||
this.ComponentStreamEnumerableFactory.GetComponentStreams( | ||
new FileInfo(processRequest.ComponentStream.Location).Directory, | ||
["go.mod"], | ||
(_, _) => false, | ||
false) | ||
.Select(x => | ||
{ | ||
// The stream will be disposed at the end of this method, so we need to copy it to a new stream. | ||
var memoryStream = new MemoryStream(); | ||
|
||
x.Stream.CopyTo(memoryStream); | ||
memoryStream.Position = 0; | ||
|
||
return new ComponentStream | ||
{ | ||
Stream = memoryStream, | ||
Location = x.Location, | ||
Pattern = x.Pattern, | ||
}; | ||
}); | ||
} |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.