Skip to content

Commit

Permalink
Add C# 8 nullable annotations and fix null dereference issues (#139)
Browse files Browse the repository at this point in the history
* Update dependencies.
  • Loading branch information
gfs authored Mar 17, 2020
1 parent 7759bd0 commit 988836c
Show file tree
Hide file tree
Showing 43 changed files with 4,288 additions and 1,195 deletions.
23 changes: 11 additions & 12 deletions DevSkim-DotNet/Microsoft.DevSkim.CLI/Catalogue.cs
Original file line number Diff line number Diff line change
Expand Up @@ -56,8 +56,7 @@ private string GetProperty(Rule rule, string propName)
{
foreach(Attribute attr in property.GetCustomAttributes(true))
{
JsonPropertyAttribute jsonAttr = (attr as JsonPropertyAttribute);
if (jsonAttr != null && jsonAttr.PropertyName == propName)
if (attr is JsonPropertyAttribute jsonAttr && jsonAttr.PropertyName == propName)
{
return GetPropertyValue(property, rule);
}
Expand All @@ -75,23 +74,23 @@ private string GetProperty(Rule rule, string propName)
private string GetPropertyValue(PropertyInfo property, Rule rule)
{
string result = string.Empty;
switch (property.PropertyType.Name)
switch (property.GetValue(rule))
{
case "String":
result = property.GetValue(rule) as string;
case string s:
result = s;
break;
case "String[]":
string[] list = (property.GetValue(rule) as string[]);
result = (list == null) ? string.Empty : string.Join(",", list);
case string[] list:
result = string.Join(",", list);
break;
case "SearchPattern[]":
case "SearchCondition[]":
case "CodeFix[]":
case SearchPattern[] _:
case SearchCondition[] _:
case CodeFix[] _:
result = "#UNSUPPORTED PROPERTY";
break;
default:
result = property.GetValue(rule).ToString();
result = property.GetValue(rule)?.ToString() ?? string.Empty;
break;

}

return result;
Expand Down
32 changes: 17 additions & 15 deletions DevSkim-DotNet/Microsoft.DevSkim.CLI/Commands/AnalyzeCommand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ public int Run()
return (int)ExitCode.CriticalError;
}

Verifier verifier = null;
Verifier? verifier = null;
if (_rulespath.Count() > 0)
{
// Setup the rules
Expand All @@ -126,13 +126,17 @@ public int Run()

if (!_ignoreDefaultRules)
{
Assembly assembly = Assembly.GetAssembly(typeof(Boundary));
Assembly? assembly = Assembly.GetAssembly(typeof(Boundary));
string filePath = "Microsoft.DevSkim.Resources.devskim-rules.json";
Stream resource = assembly.GetManifestResourceStream(filePath);
using (StreamReader file = new StreamReader(resource))
Stream? resource = assembly?.GetManifestResourceStream(filePath);
if (resource is Stream)
{
rules.AddString(file.ReadToEnd(), filePath, null);
}
using (StreamReader file = new StreamReader(resource))
{
rules.AddString(file.ReadToEnd(), filePath, null);
}
}

}

// Initialize the processor
Expand All @@ -158,8 +162,8 @@ public int Run()
}

Writer outputWriter = WriterFactory.GetWriter(_fileFormat,
(string.IsNullOrEmpty(_outputFile)) ? null : "text",
_outputFormat);
_outputFormat,
string.IsNullOrEmpty(_outputFile)?Console.Out: File.CreateText(_outputFile));
if (string.IsNullOrEmpty(_outputFile))
outputWriter.TextWriter = Console.Out;
else
Expand Down Expand Up @@ -230,13 +234,11 @@ public int Run()
issue.Rule.Severity,
issue.Rule.Name);

IssueRecord record = new IssueRecord()
{
Filename = filename,
Filesize = fileText.Length,
TextSample = fileText.Substring(issue.Boundary.Index, issue.Boundary.Length),
Issue = issue
};
IssueRecord record = new IssueRecord(
Filename: filename,
Filesize: fileText.Length,
TextSample: fileText.Substring(issue.Boundary.Index, issue.Boundary.Length),
Issue: issue);

outputWriter.WriteIssue(record);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ public int Run()

JsonSerializerSettings settings = new JsonSerializerSettings();
settings.Formatting = (_indent) ? Formatting.Indented : Formatting.None;
settings.Error = delegate (object sender, Newtonsoft.Json.Serialization.ErrorEventArgs e)
settings.Error = delegate (object? sender, Newtonsoft.Json.Serialization.ErrorEventArgs e)
{
e.ErrorContext.Handled = true;
};
Expand Down
12 changes: 6 additions & 6 deletions DevSkim-DotNet/Microsoft.DevSkim.CLI/Commands/RootCommand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,17 +10,17 @@ public class RootCommand : ICommand
{
public static void Configure(CommandLineApplication app)
{
app.FullName = Assembly.GetEntryAssembly()
.GetCustomAttribute<AssemblyProductAttribute>()
app.FullName = Assembly.GetEntryAssembly()?
.GetCustomAttribute<AssemblyProductAttribute>()?
.Product;

app.Name = Assembly.GetEntryAssembly()
.GetCustomAttribute<AssemblyTitleAttribute>()
app.Name = Assembly.GetEntryAssembly()?
.GetCustomAttribute<AssemblyTitleAttribute>()?
.Title;

app.HelpOption("-?|-h|--help");
app.VersionOption("-v|--version", Assembly.GetEntryAssembly()
.GetCustomAttribute<AssemblyInformationalVersionAttribute>()
app.VersionOption("-v|--version", Assembly.GetEntryAssembly()?
.GetCustomAttribute<AssemblyInformationalVersionAttribute>()?
.InformationalVersion);

app.Command("analyze", AnalyzeCommand.Configure, false);
Expand Down
15 changes: 12 additions & 3 deletions DevSkim-DotNet/Microsoft.DevSkim.CLI/ErrorMessage.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,19 @@ namespace Microsoft.DevSkim.CLI
{
class ErrorMessage
{
public string File { get; set; }
public string Path { get; set; }
public string? File { get; set; }
public string? Path { get; set; }
public string Message { get; set; }
public string RuleID { get; set; }
public string? RuleID { get; set; }
public bool Warning { get; set; }

public ErrorMessage(string Message, string? File = null, string? RuleID = null, string? Path = null, bool Warning = false)
{
this.File = File;
this.Path = Path;
this.Message = Message;
this.RuleID = RuleID;
this.Warning = Warning;
}
}
}
8 changes: 4 additions & 4 deletions DevSkim-DotNet/Microsoft.DevSkim.CLI/ExceptionLogger.cs
Original file line number Diff line number Diff line change
Expand Up @@ -27,10 +27,10 @@ private void LogException(Exception e)
Environment.Exit((int)ExitCode.CriticalError);
}

public string WriteRaw(string rawData)
public string? WriteRaw(string? rawData)
{
string fileName = "devskim_exception.log";
FileStream fs = null;
string? fileName = "devskim_exception.log";
FileStream? fs = null;
try
{
fs = new FileStream(fileName, FileMode.Append, FileAccess.Write, FileShare.ReadWrite);
Expand Down Expand Up @@ -68,7 +68,7 @@ public string Write(Exception ex)
string message = "Message: " + ex.Message + "\r\n";
message += "StackTrace: " + ex.StackTrace;

return WriteRaw(message);
return WriteRaw(message) ?? string.Empty;
}
}
}
16 changes: 12 additions & 4 deletions DevSkim-DotNet/Microsoft.DevSkim.CLI/IssueRecord.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,17 @@ namespace Microsoft.DevSkim.CLI
{
public class IssueRecord
{
public string Filename { get; set; }
public int Filesize { get; set; }
public string TextSample { get; set; }
public Issue Issue { get; set; }
public string Filename { get; }
public int Filesize { get; }
public string TextSample { get; }
public Issue Issue { get; }

public IssueRecord(string Filename, int Filesize, string TextSample, Issue Issue)
{
this.Filename = Filename;
this.Filesize = Filesize;
this.TextSample = TextSample;
this.Issue = Issue;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@
<PackageIcon>devskim-icon-128.png</PackageIcon>
<PackageProjectUrl>https://github.com/Microsoft/DevSkim</PackageProjectUrl>
<PackageVersion>0.0.0</PackageVersion>
<LangVersion>8.0</LangVersion>
<Nullable>Enable</Nullable>
</PropertyGroup>

<ItemGroup>
Expand All @@ -36,7 +38,7 @@
</ItemGroup>

<ItemGroup>
<None Include="..\Content\LICENSE.txt" Pack="true" PackagePath=""/>
<None Include="..\Content\devskim-icon-128.png" Pack="true" PackagePath=""/>
<None Include="..\Content\LICENSE.txt" Pack="true" PackagePath="" />
<None Include="..\Content\devskim-icon-128.png" Pack="true" PackagePath="" />
</ItemGroup>
</Project>
17 changes: 17 additions & 0 deletions DevSkim-DotNet/Microsoft.DevSkim.CLI/Microsoft.DevSkim.CLI.sln
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 15
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Microsoft.DevSkim.CLI", "Microsoft.DevSkim.CLI.csproj", "{15A5C17C-D5B0-4F90-8DF4-D8C0EBAAC3D5}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{15A5C17C-D5B0-4F90-8DF4-D8C0EBAAC3D5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{15A5C17C-D5B0-4F90-8DF4-D8C0EBAAC3D5}.Debug|Any CPU.Build.0 = Debug|Any CPU
{15A5C17C-D5B0-4F90-8DF4-D8C0EBAAC3D5}.Release|Any CPU.ActiveCfg = Release|Any CPU
{15A5C17C-D5B0-4F90-8DF4-D8C0EBAAC3D5}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
EndGlobal
52 changes: 28 additions & 24 deletions DevSkim-DotNet/Microsoft.DevSkim.CLI/Tester.cs
Original file line number Diff line number Diff line change
Expand Up @@ -31,10 +31,11 @@ public int Run(string directory)
{
List<string> missingTest = new List<string>();

foreach (Rule r in _rules)
foreach (Rule? r in _rules)
{
if (!_coverageList.Contains(r.Id))
missingTest.Add(r.Id);
if (r is Rule)
if (!_coverageList.Contains(r.Id))
missingTest.Add(r.Id);
}

if (missingTest.Count > 0)
Expand Down Expand Up @@ -66,7 +67,7 @@ private bool TestFile(string fileName)

// See if file name is a valid rule ID and preload default values
string defaultId = Path.GetFileNameWithoutExtension(fileName);
string[] languages = null;
string[]? languages = null;
Rule fileRule = _rules.FirstOrDefault(x => x.Id == defaultId);
if (fileRule != null)
languages = fileRule.AppliesTo;
Expand Down Expand Up @@ -140,7 +141,7 @@ private bool TestFile(string fileName)
return result;
}

private string[] GetLanguges(string header, string[] defaultLanguages)
private string[] GetLanguges(string header, string[]? defaultLanguages)
{
List<string> result = new List<string>();

Expand All @@ -166,29 +167,32 @@ private Dictionary<int, List<string>> GetExpectations(string header, string defa

Regex reg = new Regex("^line: *(\\d*)( *expect *)?(.*)", RegexOptions.Multiline);
MatchCollection matches = reg.Matches(header);
foreach(Match match in matches)
foreach(Match? match in matches)
{
int line;
List<string> ids = new List<string>();
if (int.TryParse(match.Groups[1].Value, out line))
if (match is { })
{
// get list of ids or used default one
if (match.Groups[2].Value.Trim() == "expect" && !string.IsNullOrEmpty(match.Groups[3].Value))
int line;
List<string> ids = new List<string>();
if (int.TryParse(match.Groups[1].Value, out line))
{
ids.AddRange(match.Groups[3].Value.Split(',')
.Select(x => x.Trim()));
}
else
{
ids.Add(defaultId);
// get list of ids or used default one
if (match.Groups[2].Value.Trim() == "expect" && !string.IsNullOrEmpty(match.Groups[3].Value))
{
ids.AddRange(match.Groups[3].Value.Split(',')
.Select(x => x.Trim()));
}
else
{
ids.Add(defaultId);
}

// Add line and ids to the result set
if (result.ContainsKey(line))
result[line].AddRange(ids);
else
result.Add(line, ids);
}

// Add line and ids to the result set
if (result.ContainsKey(line))
result[line].AddRange(ids);
else
result.Add(line, ids);
}
}
}

return result;
Expand Down
Loading

0 comments on commit 988836c

Please sign in to comment.