Skip to content
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

refactor: IDE0007 Use var instead of explicit type #405

Merged
merged 2 commits into from
Sep 26, 2023
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
4 changes: 0 additions & 4 deletions .editorconfig
Original file line number Diff line number Diff line change
Expand Up @@ -919,10 +919,6 @@ dotnet_diagnostic.CS8632.severity = suggestion
# IDE0005: Using directive is unnecessary
dotnet_diagnostic.IDE0005.severity = suggestion

# https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/style-rules/ide0007
# IDE0007: use 'var' instead of explicit type
dotnet_diagnostic.IDE0007.severity = suggestion

# https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/style-rules/ide0009
# IDE0009: Add 'this' or 'Me' qualification
dotnet_diagnostic.IDE0009.severity = suggestion
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ public class ComponentDetectionToSBOMPackageAdapter

try
{
ScanResultWithLicense? componentDetectionScanResult = JsonConvert.DeserializeObject<ScanResultWithLicense>(File.ReadAllText(bcdeOutputPath));
var componentDetectionScanResult = JsonConvert.DeserializeObject<ScanResultWithLicense>(File.ReadAllText(bcdeOutputPath));

if (componentDetectionScanResult == null)
{
Expand Down
2 changes: 1 addition & 1 deletion src/Microsoft.Sbom.Api/Config/ApiConfigurationBuilder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ public static InputConfiguration GetConfiguration(
throw new ArgumentNullException(nameof(metadata));
}

RuntimeConfiguration sanitizedRuntimeConfiguration = SanitiseRuntimeConfiguration(runtimeConfiguration);
var sanitizedRuntimeConfiguration = SanitiseRuntimeConfiguration(runtimeConfiguration);

var configuration = new InputConfiguration
{
Expand Down
2 changes: 1 addition & 1 deletion src/Microsoft.Sbom.Api/Config/ArgRevivers.cs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ public static IList<ManifestInfo> ReviveManifestInfo(string _, string value)
try
{
IList<ManifestInfo> manifestInfos = new List<ManifestInfo>();
string[] values = value.Split(',');
var values = value.Split(',');
foreach (var manifestInfoStr in values)
{
manifestInfos.Add(ManifestInfo.Parse(manifestInfoStr));
Expand Down
2 changes: 1 addition & 1 deletion src/Microsoft.Sbom.Api/Config/ConfigFileParser.cs
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ public async Task<ConfigFile> ParseFromJsonFile(string filePath)
throw new ArgumentNullException($"{nameof(filePath)} cannot be emtpy.");
}

using Stream openStream = fileSystemUtils.OpenRead(filePath);
using var openStream = fileSystemUtils.OpenRead(filePath);
return await JsonSerializer.DeserializeAsync<ConfigFile>(openStream);
}
}
2 changes: 1 addition & 1 deletion src/Microsoft.Sbom.Api/Config/ConfigSanitizer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -175,7 +175,7 @@ private ConfigurationSetting<string> GetNamespaceBaseUri(IConfiguration configur
// If assembly name is not defined and namespace was not provided then return the default namespace as per spdx spec https://spdx.github.io/spdx-spec/v2.2.2/document-creation-information/#653-examples.
if (string.IsNullOrWhiteSpace(assemblyConfig.DefaultSBOMNamespaceBaseUri) && string.IsNullOrEmpty(configuration.NamespaceUriBase?.Value))
{
string defaultNamespaceUriBase = $"https://spdx.org/spdxdocs/sbom-tool-{SBOMToolVersion}-{Guid.NewGuid()}";
var defaultNamespaceUriBase = $"https://spdx.org/spdxdocs/sbom-tool-{SBOMToolVersion}-{Guid.NewGuid()}";

logger.Information($"No namespace URI base provided, using unique generated default value {defaultNamespaceUriBase}");

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ public void Validate(string propertyName, object propertyValue, AttributeCollect
throw new ArgumentException($"'{nameof(propertyName)}' cannot be null or empty", nameof(propertyName));
}

Attribute attribute = attributeCollection[supportedAttribute];
var attribute = attributeCollection[supportedAttribute];
if (attribute == null)
{
return;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ public override void ValidateInternal(string paramName, object paramValue, Attri
{
if (paramValue != null && paramValue is int value)
{
IntRangeAttribute intRangeAttribute = attribute as IntRangeAttribute;
var intRangeAttribute = attribute as IntRangeAttribute;

if (value < intRangeAttribute.MinRange || value > intRangeAttribute.MaxRange)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ public ComponentToExternalReferenceInfoConverter(ILogger log)

Task.Run(async () =>
{
await foreach (ScannedComponent scannedComponent in componentReader.ReadAllAsync())
await foreach (var scannedComponent in componentReader.ReadAllAsync())
{
try
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ public ExternalReferenceInfoToPathConverter(ILogger log)

Task.Run(async () =>
{
await foreach (ExternalDocumentReferenceInfo externalDocumentRef in externalDocumentRefReader.ReadAllAsync())
await foreach (var externalDocumentRef in externalDocumentRefReader.ReadAllAsync())
{
try
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,11 +37,11 @@ public SbomToolManifestPathConverter(IConfiguration configuration, IOSUtils osUt

public (string, bool) Convert(string path, bool prependDotToPath = false)
{
string dotString = prependDotToPath ? "." : string.Empty;
var dotString = prependDotToPath ? "." : string.Empty;

// relativeTo
string buildDropPath = configuration.BuildDropPath.Value;
bool isOutsideDropPath = false;
var buildDropPath = configuration.BuildDropPath.Value;
var isOutsideDropPath = false;
if (path == null)
{
throw new ArgumentNullException(nameof(path));
Expand All @@ -59,8 +59,8 @@ public SbomToolManifestPathConverter(IConfiguration configuration, IOSUtils osUt
}
}

string relativePath = fileSystemUtils.GetRelativePath(buildDropPath, path);
string formattedRelativePath = $"{dotString}/{relativePath.Replace("\\", "/")}";
var relativePath = fileSystemUtils.GetRelativePath(buildDropPath, path);
var formattedRelativePath = $"{dotString}/{relativePath.Replace("\\", "/")}";

return (formattedRelativePath, isOutsideDropPath);
}
Expand Down
4 changes: 2 additions & 2 deletions src/Microsoft.Sbom.Api/Entities/FileValidationResult.cs
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,8 @@ public class FileValidationResult
// TODO: Deprecate FileValidationResult to use EntityError
public EntityError ToEntityError()
{
EntityErrorType errorType = EntityErrorType.Other;
EntityType entityType = EntityType.Unknown;
var errorType = EntityErrorType.Other;
var entityType = EntityType.Unknown;
Entity entity = null;

switch (ErrorType)
Expand Down
6 changes: 3 additions & 3 deletions src/Microsoft.Sbom.Api/Executors/ChannelUtils.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ public ChannelReader<T> Merge<T>(params ChannelReader<T>[] inputs)
{
async Task Redirect(ChannelReader<T> input)
{
await foreach (T item in input.ReadAllAsync())
await foreach (var item in input.ReadAllAsync())
{
await output.Writer.WriteAsync(item);
}
Expand Down Expand Up @@ -56,13 +56,13 @@ public IList<ChannelReader<T>> Split<T>(ChannelReader<T> input, int n)
{
var index = 0;

await foreach (T item in input.ReadAllAsync())
await foreach (var item in input.ReadAllAsync())
{
await outputs[index].Writer.WriteAsync(item);
index = (index + 1) % n;
}

foreach (Channel<T> ch in outputs)
foreach (var ch in outputs)
{
ch.Writer.Complete();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ public ComponentDetectionBaseWalker(
// Enable SPDX22 detector which is disabled by default.
cliArgumentBuilder.AddDetectorArg("SPDX22SBOM", "EnableIfDefaultOff");

if (sbomConfigs.TryGet(Constants.SPDX22ManifestInfo, out ISbomConfig spdxSbomConfig))
if (sbomConfigs.TryGet(Constants.SPDX22ManifestInfo, out var spdxSbomConfig))
{
var directory = Path.GetDirectoryName(spdxSbomConfig.ManifestJsonFilePath);
if (!string.IsNullOrEmpty(directory))
Expand Down Expand Up @@ -117,18 +117,18 @@ async Task Scan(string path)
// Check if the configuration is set to fetch license information.
if (configuration.FetchLicenseInformation?.Value == true)
{
List<string> listOfComponentsForApi = licenseInformationFetcher.ConvertComponentsToListForApi(uniqueComponents);
var listOfComponentsForApi = licenseInformationFetcher.ConvertComponentsToListForApi(uniqueComponents);

// Check that an API call hasn't already been made. During the first execution of this class this list is empty (because we are detecting the files section of the SBOM). During the second execution we have all the components in the project. There are subsequent executions but not important in this scenario.
if (!licenseInformationRetrieved && listOfComponentsForApi?.Count > 0)
{
licenseInformationRetrieved = true;

List<string> apiResponses = await licenseInformationFetcher.FetchLicenseInformationAsync(listOfComponentsForApi);
var apiResponses = await licenseInformationFetcher.FetchLicenseInformationAsync(listOfComponentsForApi);

foreach (string response in apiResponses)
foreach (var response in apiResponses)
{
Dictionary<string, string> licenseInfo = licenseInformationFetcher.ConvertClearlyDefinedApiResponseToList(response);
var licenseInfo = licenseInformationFetcher.ConvertClearlyDefinedApiResponseToList(response);

if (licenseInfo != null)
{
Expand All @@ -143,10 +143,10 @@ async Task Scan(string path)
}

// Converts every ScannedComponent into an ExtendedScannedComponent and attempts to add license information before writing to the channel.
foreach (ScannedComponent scannedComponent in uniqueComponents)
foreach (var scannedComponent in uniqueComponents)
{
string componentName = scannedComponent.Component.PackageUrl?.Name;
string componentVersion = scannedComponent.Component.PackageUrl?.Version;
var componentName = scannedComponent.Component.PackageUrl?.Name;
var componentVersion = scannedComponent.Component.PackageUrl?.Version;

ScannedComponentWithLicense extendedComponent;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ public ExternalDocumentReferenceWriter(

Task.Run(async () =>
{
await foreach (ExternalDocumentReferenceInfo externalDocumentReferenceInfo in externalDocumentReferenceInfos.ReadAllAsync())
await foreach (var externalDocumentReferenceInfo in externalDocumentReferenceInfos.ReadAllAsync())
{
foreach (var config in externalDocumentReferenceArraySupportingConfigs)
{
Expand Down
6 changes: 3 additions & 3 deletions src/Microsoft.Sbom.Api/Executors/FileHasher.cs
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ public FileHasher(

Task.Run(async () =>
{
await foreach (string file in fileInfo.ReadAllAsync())
await foreach (var file in fileInfo.ReadAllAsync())
{
await GenerateHash(file, output, errors, fileLocation, prependDotToPath);
}
Expand All @@ -114,11 +114,11 @@ public FileHasher(
private async Task GenerateHash(string file, Channel<InternalSbomFileInfo> output, Channel<FileValidationResult> errors, FileLocation fileLocation, bool prependDotToPath = false)
{
string relativeFilePath = null;
bool isOutsideDropPath = false;
var isOutsideDropPath = false;
try
{
(relativeFilePath, isOutsideDropPath) = manifestPathConverter.Convert(file, prependDotToPath);
Checksum[] fileHashes = hashCodeGenerator.GenerateHashes(file, HashAlgorithmNames);
var fileHashes = hashCodeGenerator.GenerateHashes(file, HashAlgorithmNames);
if (fileHashes == null || fileHashes.Length == 0 || fileHashes.Any(f => string.IsNullOrEmpty(f.ChecksumValue)))
{
throw new HashGenerationException($"Failed to generate hashes for '{file}'.");
Expand Down
2 changes: 1 addition & 1 deletion src/Microsoft.Sbom.Api/Executors/FileInfoWriter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ public FileInfoWriter(ManifestGeneratorProvider manifestGeneratorProvider, ILogg

Task.Run(async () =>
{
await foreach (InternalSbomFileInfo fileInfo in fileInfos.ReadAllAsync())
await foreach (var fileInfo in fileInfos.ReadAllAsync())
{
await Generate(filesArraySupportingSBOMs, fileInfo, result, errors);
}
Expand Down
6 changes: 3 additions & 3 deletions src/Microsoft.Sbom.Api/Executors/FileListEnumerator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -73,14 +73,14 @@ await errors.Writer.WriteAsync(new FileValidationResult
}

// Split on Environment.NewLine and discard blank lines.
string[] separator = new string[] { Environment.NewLine };
IEnumerable<string> files = allText.Split(separator, StringSplitOptions.None)
var separator = new string[] { Environment.NewLine };
var files = allText.Split(separator, StringSplitOptions.None)
.Where(t => !string.IsNullOrEmpty(t));
foreach (var oneFile in files)
{
try
{
string absoluteFileName = fileSystemUtils.AbsolutePath(oneFile);
var absoluteFileName = fileSystemUtils.AbsolutePath(oneFile);
if (!fileSystemUtils.FileExists(absoluteFileName))
{
await errors.Writer.WriteAsync(new FileValidationResult
Expand Down
2 changes: 1 addition & 1 deletion src/Microsoft.Sbom.Api/Executors/HashValidator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ private async Task Validate(InternalSbomFileInfo fileHash, Channel<FileValidatio
Path = fileHash.Path
};

if (manifestData.HashesMap.TryGetValue(fileHash.Path, out Checksum[] expectedHashes))
if (manifestData.HashesMap.TryGetValue(fileHash.Path, out var expectedHashes))
{
manifestData.HashesMap.Remove(fileHash.Path);

Expand Down
30 changes: 15 additions & 15 deletions src/Microsoft.Sbom.Api/Executors/LicenseInformationFetcher.cs
Original file line number Diff line number Diff line change
Expand Up @@ -30,13 +30,13 @@ public LicenseInformationFetcher(ILogger log, IRecorder recorder, ILicenseInform

public List<string> ConvertComponentsToListForApi(IEnumerable<ScannedComponent> scannedComponents)
{
List<string> listOfComponentsForApi = new List<string>();
var listOfComponentsForApi = new List<string>();

foreach (var scannedComponent in scannedComponents)
{
string[] parts = scannedComponent.Component.Id.Split(' ');
string componentVersion = scannedComponent.Component.PackageUrl?.Version;
string componentType = scannedComponent.Component.PackageUrl?.Type.ToLower();
var parts = scannedComponent.Component.Id.Split(' ');
var componentVersion = scannedComponent.Component.PackageUrl?.Version;
var componentType = scannedComponent.Component.PackageUrl?.Type.ToLower();

if (parts.Length > 2)
{
Expand All @@ -46,7 +46,7 @@ public List<string> ConvertComponentsToListForApi(IEnumerable<ScannedComponent>
// If the clearlyDefinedName contains a / then split it and use the first part as the clearlyDefinedNamespace and the second part as the clearlyDefinedName
if (!string.IsNullOrEmpty(componentName) && componentName.Contains('/'))
{
string[] clearlyDefinedNameParts = componentName.Split('/');
var clearlyDefinedNameParts = componentName.Split('/');
clearlyDefinedNamespace = clearlyDefinedNameParts[0];
componentName = clearlyDefinedNameParts[1];
}
Expand Down Expand Up @@ -90,20 +90,20 @@ public async Task<List<string>> FetchLicenseInformationAsync(List<string> listOf
// Will attempt to extract license information from a clearlyDefined batch API response. Will always return a dictionary which may be empty depending on the response.
public Dictionary<string, string> ConvertClearlyDefinedApiResponseToList(string httpResponseContent)
{
Dictionary<string, string> extractedLicenses = new Dictionary<string, string>();
var extractedLicenses = new Dictionary<string, string>();

try
{
JObject responseObject = JObject.Parse(httpResponseContent);
var responseObject = JObject.Parse(httpResponseContent);

foreach (JToken packageInfoToken in responseObject.Values())
foreach (var packageInfoToken in responseObject.Values())
{
JObject packageInfo = packageInfoToken.ToObject<JObject>();
JObject coordinates = packageInfo.Value<JObject>("coordinates");
string packageNamespace = coordinates.Value<string>("namespace");
string packageName = coordinates.Value<string>("name");
string packageVersion = coordinates.Value<string>("revision");
string declaredLicense = packageInfo
var packageInfo = packageInfoToken.ToObject<JObject>();
var coordinates = packageInfo.Value<JObject>("coordinates");
var packageNamespace = coordinates.Value<string>("namespace");
var packageName = coordinates.Value<string>("name");
var packageVersion = coordinates.Value<string>("revision");
var declaredLicense = packageInfo
.Value<JObject>("licensed")
.Value<string>("declared");

Expand Down Expand Up @@ -152,7 +152,7 @@ public void AppendLicensesToDictionary(Dictionary<string, string> partialLicense

public string GetFromLicenseDictionary(string key)
{
string value = string.Empty;
var value = string.Empty;

if (licenseDictionary.ContainsKey(key))
{
Expand Down
16 changes: 8 additions & 8 deletions src/Microsoft.Sbom.Api/Executors/LicenseInformationService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -31,19 +31,19 @@ public LicenseInformationService(ILogger log, IRecorder recorder, HttpClient htt

public async Task<List<string>> FetchLicenseInformationFromAPI(List<string> listOfComponentsForApi)
{
int batchSize = 500;
List<HttpResponseMessage> responses = new List<HttpResponseMessage>();
List<string> responseContent = new List<string>();
var batchSize = 500;
var responses = new List<HttpResponseMessage>();
var responseContent = new List<string>();

Uri uri = new Uri("https://api.clearlydefined.io/definitions?expand=-files");
var uri = new Uri("https://api.clearlydefined.io/definitions?expand=-files");

httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
httpClient.Timeout = TimeSpan.FromSeconds(ClientTimeoutSeconds);

for (int i = 0; i < listOfComponentsForApi.Count; i += batchSize)
for (var i = 0; i < listOfComponentsForApi.Count; i += batchSize)
{
List<string> batch = listOfComponentsForApi.Skip(i).Take(batchSize).ToList();
string formattedData = JsonSerializer.Serialize(batch);
var batch = listOfComponentsForApi.Skip(i).Take(batchSize).ToList();
var formattedData = JsonSerializer.Serialize(batch);

log.Debug($"Retrieving license information for {batch.Count} components...");

Expand All @@ -67,7 +67,7 @@ public async Task<List<string>> FetchLicenseInformationFromAPI(List<string> list
log.Debug($"Retrieving license information for {batch.Count} components took {stopwatch.Elapsed.TotalSeconds} seconds");
}

foreach (HttpResponseMessage response in responses)
foreach (var response in responses)
{
if (response.IsSuccessStatusCode)
{
Expand Down
2 changes: 1 addition & 1 deletion src/Microsoft.Sbom.Api/Executors/ManifestFileFilterer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ public ChannelReader<FileValidationResult> FilterManifestFiles()
{
try
{
string file = fileSystemUtils.JoinPaths(configuration.BuildDropPath.Value, manifestFile);
var file = fileSystemUtils.JoinPaths(configuration.BuildDropPath.Value, manifestFile);
if (!rootPathFilter.IsValid(file))
{
// This path is filtered, remove from the manifest map.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ public ManifestFolderFilterer(

Task.Run(async () =>
{
await foreach (string file in files.ReadAllAsync())
await foreach (var file in files.ReadAllAsync())
{
await FilterFiles(file, errors, output);
}
Expand Down
Loading
Loading