Skip to content

Commit

Permalink
Nullable Annotations (#102)
Browse files Browse the repository at this point in the history
* Nullable Annotations
  • Loading branch information
gfs authored Jun 5, 2020
1 parent 06af9ec commit 41be2e1
Show file tree
Hide file tree
Showing 45 changed files with 408 additions and 367 deletions.
11 changes: 3 additions & 8 deletions src/Shared/CommonInitialization.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,24 +12,21 @@ public static class CommonInitialization
/// <summary>
/// Static HttpClient for use in all HTTP connections.
/// </summary>
public static HttpClient WebClient { get; private set; } = null;
public static HttpClient? WebClient { get; private set; } = null;

/// <summary>
/// User Agent string, when needed to connect to external resources.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Modified through reflection.")]
private static string ENV_HTTPCLIENT_USER_AGENT = "OSSDL";

/// <summary>
/// Common Logger for all OSS Gadget tools.
/// </summary>
public static NLog.Logger Logger { get; private set; }

/// <summary>
/// Prevent being initialized multiple times.
/// </summary>
private static bool Initialized = false;

public static NLog.ILogger Logger { get; set; } = NLog.LogManager.GetCurrentClassLogger();

/// <summary>
/// Initializes common infrastructure, like logging.
/// </summary>
Expand All @@ -52,8 +49,6 @@ public static void Initialize()

WebClient = new HttpClient(handler);
WebClient.DefaultRequestHeaders.UserAgent.ParseAdd(ENV_HTTPCLIENT_USER_AGENT);

Logger = NLog.LogManager.GetCurrentClassLogger();

// @TODO Does this actually run?
System.Runtime.Loader.AssemblyLoadContext.Default.Unloading += (_) =>
Expand Down
19 changes: 8 additions & 11 deletions src/Shared/Helpers/ConsoleHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@ namespace Microsoft.CST.OpenSource.Shared
{
public class ConsoleHelper
{
static StreamWriter streamWriter;
static FileStream fileStream;
static StreamWriter? streamWriter;
static FileStream? fileStream;

public static bool RedirectConsole(string outFile)
{
Expand Down Expand Up @@ -41,17 +41,14 @@ public static void RestoreConsole()
standardOutput.AutoFlush = true;
Console.SetOut(standardOutput);

if (streamWriter != null)
{
streamWriter.Close();
fileStream.Close();
streamWriter?.Close();
fileStream?.Close();

streamWriter.Dispose();
fileStream.Dispose();
streamWriter?.Dispose();
fileStream?.Dispose();

fileStream = null;
streamWriter = null;
}
fileStream = null;
streamWriter = null;
}
}
}
33 changes: 4 additions & 29 deletions src/Shared/Helpers/OutputBuilder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -31,36 +31,11 @@ enum OutputFormat
List<Result> sarifResults = new List<Result>();

// cache variables to avoid reflection
static string _AssemblyName = null;
string AssemblyName {
get
{
_AssemblyName ??= Assembly.GetEntryAssembly().GetName().Name;
return _AssemblyName;
}
}
static readonly string AssemblyName = Assembly.GetEntryAssembly()?.GetName().Name ?? string.Empty;

static string _Version = null;
string Version
{
get
{
_Version ??= Assembly.GetEntryAssembly().
GetCustomAttribute<AssemblyFileVersionAttribute>().Version.ToString();
return _Version;
}
}
static readonly string Version = Assembly.GetEntryAssembly()?.GetCustomAttribute<AssemblyFileVersionAttribute>()?.Version.ToString() ?? string.Empty;

static string _Company = null;
string Company
{
get
{
_Company ??= Assembly.GetEntryAssembly().
GetCustomAttribute<AssemblyCompanyAttribute>().Company;
return _Company;
}
}
static readonly string Company = Assembly.GetEntryAssembly()?.GetCustomAttribute<AssemblyCompanyAttribute>()?.Company ?? string.Empty;

public OutputBuilder(string format)
{
Expand Down Expand Up @@ -122,7 +97,7 @@ public static List<Location> BuildPurlLocation(PackageURL purl)
{
Address = new Address()
{
FullyQualifiedName = projectManager.GetPackageAbsoluteUri(purl).AbsoluteUri,
FullyQualifiedName = projectManager?.GetPackageAbsoluteUri(purl)?.AbsoluteUri,
AbsoluteAddress = 1,
Name = purl.ToString()
}
Expand Down
61 changes: 34 additions & 27 deletions src/Shared/Helpers/PackageDownloader.cs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ public class PackageDownloader

List<PackageURL> PackageVersions { get; set; }

BaseProjectManager packageManager { get; set; }
BaseProjectManager? packageManager { get; set; }

string destinationDirectory { get; set; }

Expand All @@ -34,15 +34,15 @@ public class PackageDownloader
private bool actualCaching = false;

// folders created
List<string> downloadPaths { get; set; }
List<string> downloadPaths { get; set; } = new List<string>();

/// <summary>
/// Constuctor - creates a class object for downloading packages
/// </summary>
/// <param name="purl">package to download</param>
/// <param name="destinationDir">the directory where the package needs to be placed</param>
/// <param name="doCaching">check and use the cache if it exists - create if not</param>
public PackageDownloader(PackageURL purl, string destinationDir = null, bool doCaching = false)
public PackageDownloader(PackageURL? purl, string? destinationDir = null, bool doCaching = false)
{
if (purl == null)
{
Expand Down Expand Up @@ -144,6 +144,9 @@ public async Task<List<string>> DownloadPackageLocalCopy(PackageURL purl,
downloadDirectories.AddRange(await this.Download(version, metadataOnly, doExtract));
}

// Add the return values to our internal storage to be cleaned up later by CleanPackageLocalCopy
this.downloadPaths.AddRange(downloadDirectories);

return downloadDirectories;
}

Expand Down Expand Up @@ -174,22 +177,21 @@ public async void ClearPackageLocalCopy()
{
try
{
if (this.downloadPaths != null)
foreach (string packageDirectory in this.downloadPaths)
{
foreach (string packageDirectory in this.downloadPaths)
if (Directory.Exists(packageDirectory))
{
if (Directory.Exists(packageDirectory))
{
Logger.Trace("Removing directory {0}", packageDirectory);
Directory.Delete(packageDirectory, true);
}
Logger.Trace("Removing directory {0}", packageDirectory);
Directory.Delete(packageDirectory, true);
}
}
}
catch (Exception ex)
{
Logger.Warn("Error removing {0}: {1}", destinationDirectory, ex.Message);
}

this.downloadPaths.Clear();
}


Expand All @@ -212,31 +214,36 @@ public async Task<List<string>> Download(
bool doExtract)
{
List<string> downloadPaths = new List<string>();
if (metadataOnly)
if (packageManager != null)
{
var metadata = await this.packageManager.GetMetadata(purl);
if (metadata != null)
if (metadataOnly)
{
var outputFilename = Path.Combine(this.packageManager.TopLevelExtractionDirectory, $"metadata-{purl.ToStringFilename()}");

// this will be effectively the same as above, if the cache doesnt exist
if (!this.actualCaching)
var metadata = await packageManager.GetMetadata(purl);
if (metadata != null)
{
while (File.Exists(outputFilename))
var outputFilename = Path.Combine(packageManager.TopLevelExtractionDirectory, $"metadata-{purl.ToStringFilename()}");

// this will be effectively the same as above, if the cache doesnt exist
if (!this.actualCaching)
{
outputFilename = Path.Combine(this.packageManager.TopLevelExtractionDirectory, $"metadata-{purl.ToStringFilename()}-{DateTime.Now.Ticks}");
while (File.Exists(outputFilename))
{
outputFilename = Path.Combine(packageManager.TopLevelExtractionDirectory, $"metadata-{purl.ToStringFilename()}-{DateTime.Now.Ticks}");
}
}
File.WriteAllText(outputFilename, metadata);
downloadPaths.Add(outputFilename);
}
File.WriteAllText(outputFilename, metadata);
downloadPaths.Add(outputFilename);
}
else
{
// only version download requests reach here
downloadPaths.AddRange(await packageManager.DownloadVersion(purl, doExtract, this.actualCaching));
}
}
else
{
// only version download requests reach here
downloadPaths.AddRange(await this.packageManager.DownloadVersion(purl, doExtract, this.actualCaching));
this.downloadPaths = downloadPaths;
}

// Add the return values to our internal storage to be cleaned up later by CleanPackageLocalCopy
this.downloadPaths.AddRange(downloadPaths);

return downloadPaths;
}
Expand Down
1 change: 1 addition & 0 deletions src/Shared/Helpers/RepoSearch.cs
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,7 @@ public async Task<Dictionary<PackageURL, double>> ResolvePackageLibraryAsync(Pac

if (repoMappings == null || !repoMappings.Any())
{
repoMappings = new Dictionary<PackageURL, double>();
Logger.Info("No repositories were found after searching metadata.");
}
}
Expand Down
18 changes: 18 additions & 0 deletions src/Shared/OSSGadget.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
using System;
using Microsoft.CST.OpenSource.Shared;

namespace Microsoft.CST.OpenSource
{
public class OSSGadget
{
/// <summary>
/// Logger for this class
/// </summary>
public static NLog.ILogger Logger { get; set; } = NLog.LogManager.GetCurrentClassLogger();

public OSSGadget()
{
CommonInitialization.Initialize();
}
}
}
Loading

0 comments on commit 41be2e1

Please sign in to comment.