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

Apply is null pattern and analyzer #644

Merged
merged 1 commit into from Aug 28, 2021
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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
6 changes: 6 additions & 0 deletions .editorconfig
Expand Up @@ -79,3 +79,9 @@ csharp_new_line_before_catch = true
csharp_new_line_before_finally = true
csharp_new_line_before_members_in_object_initializers = true
csharp_new_line_before_members_in_anonymous_types = true

# CSIsNull001: Use `is null` for null checks
dotnet_diagnostic.CSIsNull001.severity = warning

# CSIsNull002: Use `is object` for non-null checks
dotnet_diagnostic.CSIsNull002.severity = warning
6 changes: 5 additions & 1 deletion src/Directory.Build.props
Expand Up @@ -24,9 +24,13 @@
<LibGit2SharpNativeVersion>2.0.312</LibGit2SharpNativeVersion>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Net.Compilers.Toolset" Version="3.8.0-5.final" PrivateAssets="all" />
<PackageReference Include="Microsoft.Net.Compilers.Toolset" Version="3.11.0" PrivateAssets="all" />
<PackageReference Include="Microsoft.NETFramework.ReferenceAssemblies" Version="1.0.0" PrivateAssets="All" />
<PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.0.0" PrivateAssets="All" />
<PackageReference Include="CSharpIsNullAnalyzer" Version="0.1.288-beta">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers</IncludeAssets>
</PackageReference>
</ItemGroup>
<ItemGroup>
<None Include="$(MSBuildThisFileDirectory)..\3rdPartyNotices.txt" Pack="true" PackagePath="" />
Expand Down
2 changes: 1 addition & 1 deletion src/NerdBank.GitVersioning.Tests/BuildIntegrationTests.cs
Expand Up @@ -219,7 +219,7 @@ public async Task GetBuildVersion_In_Git_But_Head_Lacks_VersionFile()
var repo = new Repository(this.RepoPath); // do not assign Repo property to avoid commits being generated later
repo.Commit("empty", this.Signer, this.Signer, new CommitOptions { AllowEmptyCommit = true });
this.WriteVersionFile("3.4");
Assumes.True(repo.Index[VersionFile.JsonFileName] == null);
Assumes.True(repo.Index[VersionFile.JsonFileName] is null);
var buildResult = await this.BuildAsync();
Assert.Equal("3.4.0." + this.GetVersion().Revision, buildResult.BuildVersion);
Assert.Equal("3.4.0+" + repo.Head.Tip.Id.Sha.Substring(0, VersionOptions.DefaultGitCommitIdShortFixedLength), buildResult.AssemblyInformationalVersion);
Expand Down
Expand Up @@ -89,7 +89,7 @@ public void ReadStreamTest()

DeltaInstruction? current;

while ((current = DeltaStreamReader.Read(stream)) != null)
while ((current = DeltaStreamReader.Read(stream)) is not null)
{
instructions.Add(current.Value);
}
Expand Down Expand Up @@ -139,7 +139,7 @@ public void ReadStreamTest_Memory()

DeltaInstruction? current;

while ((current = DeltaStreamReader.Read(ref memory)) != null)
while ((current = DeltaStreamReader.Read(ref memory)) is not null)
{
instructions.Add(current.Value);
}
Expand Down
4 changes: 2 additions & 2 deletions src/NerdBank.GitVersioning.Tests/ReleaseManagerTests.cs
Expand Up @@ -320,7 +320,7 @@ public void PrepeareRelease_ReleaseBranchWithVersionDecrement(string initialVers

// prepare release
var releaseManager = new ReleaseManager();
releaseManager.PrepareRelease(this.RepoPath, releaseUnstableTag, (nextVersion == null ? null : Version.Parse(nextVersion)), parameterVersionIncrement);
releaseManager.PrepareRelease(this.RepoPath, releaseUnstableTag, (nextVersion is null ? null : Version.Parse(nextVersion)), parameterVersionIncrement);

// check if a branch was created
Assert.Contains(this.LibGit2Repository.Branches, branch => branch.FriendlyName == expectedBranchName);
Expand Down Expand Up @@ -394,7 +394,7 @@ public void PrepareRelease_MasterWithVersionDecrement(string initialVersion, str
// running PrepareRelease should result in an error
// because we're trying to add a prerelease tag to a version without prerelease tag
this.AssertError(
() => new ReleaseManager().PrepareRelease(this.RepoPath, releaseUnstableTag, (nextVersion == null ? null : Version.Parse(nextVersion))),
() => new ReleaseManager().PrepareRelease(this.RepoPath, releaseUnstableTag, (nextVersion is null ? null : Version.Parse(nextVersion))),
ReleasePreparationError.VersionDecrement);
}

Expand Down
6 changes: 3 additions & 3 deletions src/NerdBank.GitVersioning.Tests/RepoTestBase.cs
Expand Up @@ -143,7 +143,7 @@ protected void AddCommits(int count = 1)

protected Commit? WriteVersionTxtFile(string version = "1.2", string prerelease = "", string? relativeDirectory = null)
{
if (relativeDirectory == null)
if (relativeDirectory is null)
{
relativeDirectory = string.Empty;
}
Expand All @@ -163,7 +163,7 @@ protected void AddCommits(int count = 1)
{
Requires.NotNull(versionData, nameof(versionData));

if (relativeDirectory == null)
if (relativeDirectory is null)
{
relativeDirectory = string.Empty;
}
Expand Down Expand Up @@ -197,7 +197,7 @@ protected void AddCommits(int count = 1)
if (Path.GetExtension(relativeFilePath) == ".json")
{
string txtFilePath = relativeFilePath.Substring(0, relativeFilePath.Length - 4) + "txt";
if (!File.Exists(Path.Combine(this.RepoPath, txtFilePath)) && this.LibGit2Repository.Index[txtFilePath] != null)
if (!File.Exists(Path.Combine(this.RepoPath, txtFilePath)) && this.LibGit2Repository.Index[txtFilePath] is not null)
{
this.LibGit2Repository.Index.Remove(txtFilePath);
}
Expand Down
2 changes: 1 addition & 1 deletion src/NerdBank.GitVersioning.Tests/TestUtilities.cs
Expand Up @@ -54,7 +54,7 @@ internal static void ExtractEmbeddedResource(string resourcePath, string extract

using (var stream = GetEmbeddedResource(resourcePath))
{
Requires.Argument(stream != null, nameof(resourcePath), "Resource not found.");
Requires.Argument(stream is not null, nameof(resourcePath), "Resource not found.");
using (var extractedFile = File.OpenWrite(extractedFilePath))
{
stream.CopyTo(extractedFile);
Expand Down
2 changes: 1 addition & 1 deletion src/NerdBank.GitVersioning.Tests/VersionFileTests.cs
Expand Up @@ -140,7 +140,7 @@ public void SetVersion_WritesSimplestFile(string version, string assemblyVersion
var versionOptions = new VersionOptions
{
Version = SemanticVersion.Parse(version),
AssemblyVersion = assemblyVersion != null || precision != null ? new VersionOptions.AssemblyVersionOptions(assemblyVersion != null ? new Version(assemblyVersion) : null, precision) : null,
AssemblyVersion = assemblyVersion is not null || precision is not null ? new VersionOptions.AssemblyVersionOptions(assemblyVersion is not null ? new Version(assemblyVersion) : null, precision) : null,
VersionHeightOffset = versionHeightOffset,
Inherit = inherit,
};
Expand Down
Expand Up @@ -51,7 +51,7 @@ public override object ReadJson(JsonReader reader, Type objectType, object exist
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
var data = value as VersionOptions.AssemblyVersionOptions;
if (data != null)
if (data is not null)
{
if (data.PrecisionOrDefault == VersionOptions.DefaultVersionPrecision && !this.includeDefaults)
{
Expand Down
4 changes: 2 additions & 2 deletions src/NerdBank.GitVersioning/CloudBuildServices/GitLab.cs
Expand Up @@ -14,13 +14,13 @@
internal class GitLab : ICloudBuild
{
public string BuildingBranch =>
Environment.GetEnvironmentVariable("CI_COMMIT_TAG") == null ?
Environment.GetEnvironmentVariable("CI_COMMIT_TAG") is null ?
$"refs/heads/{Environment.GetEnvironmentVariable("CI_COMMIT_REF_NAME")}" : null;

public string BuildingRef => this.BuildingBranch ?? this.BuildingTag;

public string BuildingTag =>
Environment.GetEnvironmentVariable("CI_COMMIT_TAG") != null ?
Environment.GetEnvironmentVariable("CI_COMMIT_TAG") is not null ?
$"refs/tags/{Environment.GetEnvironmentVariable("CI_COMMIT_TAG")}" : null;

public string GitCommitId => Environment.GetEnvironmentVariable("CI_COMMIT_SHA");
Expand Down
2 changes: 1 addition & 1 deletion src/NerdBank.GitVersioning/CloudBuildServices/TeamCity.cs
Expand Up @@ -19,7 +19,7 @@ internal class TeamCity : ICloudBuild

public string GitCommitId => Environment.GetEnvironmentVariable("BUILD_VCS_NUMBER");

public bool IsApplicable => this.GitCommitId != null;
public bool IsApplicable => this.GitCommitId is not null;

public bool IsPullRequest => false;

Expand Down
4 changes: 2 additions & 2 deletions src/NerdBank.GitVersioning/FilterPathJsonConverter.cs
Expand Up @@ -22,7 +22,7 @@ public override object ReadJson(JsonReader reader, Type objectType, object exist
throw new NotSupportedException();
}

if (this.repoRelativeBaseDirectory == null)
if (this.repoRelativeBaseDirectory is null)
{
throw new ArgumentNullException(nameof(this.repoRelativeBaseDirectory), $"Base directory must not be null to be able to deserialize filter paths. Ensure that one was passed to {nameof(VersionOptions.GetJsonSettings)}, and that the version.json file is being written to a Git repository.");
}
Expand All @@ -37,7 +37,7 @@ public override void WriteJson(JsonWriter writer, object value, JsonSerializer s
throw new NotSupportedException();
}

if (this.repoRelativeBaseDirectory == null)
if (this.repoRelativeBaseDirectory is null)
{
throw new ArgumentNullException(nameof(this.repoRelativeBaseDirectory), $"Base directory must not be null to be able to serialize filter paths. Ensure that one was passed to {nameof(VersionOptions.GetJsonSettings)}, and that the version.json file is being written to a Git repository.");
}
Expand Down
16 changes: 8 additions & 8 deletions src/NerdBank.GitVersioning/LibGit2/LibGit2GitExtensions.cs
Expand Up @@ -60,13 +60,13 @@ internal static int GetVersionHeight(LibGit2Context context, Version? baseVersio
var tracker = new GitWalkTracker(context);

var versionOptions = tracker.GetVersion(context.Commit);
if (versionOptions == null)
if (versionOptions is null)
{
return 0;
}

var baseSemVer =
baseVersion != null ? SemanticVersion.Parse(baseVersion.ToString()) :
baseVersion is not null ? SemanticVersion.Parse(baseVersion.ToString()) :
versionOptions.Version ?? SemVer0;

var versionHeightPosition = versionOptions.VersionHeightPosition;
Expand Down Expand Up @@ -174,7 +174,7 @@ public static IEnumerable<Commit> GetCommitsFromVersion(LibGit2Context context,
var tracker = new GitWalkTracker(context);
var possibleCommits = from commit in GetCommitsReachableFromRefs(context.Repository)
let commitVersionOptions = tracker.GetVersion(commit)
where commitVersionOptions != null
where commitVersionOptions is not null
where !IsCommitIdMismatch(version, commitVersionOptions, commit)
where !IsVersionHeightMismatch(version, commitVersionOptions, commit, tracker)
select commit;
Expand Down Expand Up @@ -221,7 +221,7 @@ private static bool CommitMatchesVersion(this Commit commit, SemanticVersion exp

var commitVersionData = tracker.GetVersion(commit);
var semVerFromFile = commitVersionData?.Version;
if (semVerFromFile == null)
if (semVerFromFile is null)
{
return false;
}
Expand Down Expand Up @@ -250,7 +250,7 @@ private static bool CommitMatchesVersion(this Commit commit, Version expectedVer

var commitVersionData = tracker.GetVersion(commit);
var semVerFromFile = commitVersionData?.Version;
if (semVerFromFile == null)
if (semVerFromFile is null)
{
return false;
}
Expand Down Expand Up @@ -422,7 +422,7 @@ bool TryCalculateHeight(Commit commit)

int height = 1;

if (includePaths != null)
if (includePaths is not null)
{
// If there are no include paths, or any of the include
// paths refer to the root of the repository, then do not
Expand Down Expand Up @@ -527,8 +527,8 @@ internal static Version GetIdAsVersionHelper(this Commit? commit, VersionOptions

// Don't use the ?? coalescing operator here because the position property getters themselves can return null, which should NOT be overridden with our default.
// The default value is only appropriate if versionOptions itself is null.
var versionHeightPosition = versionOptions != null ? versionOptions.VersionHeightPosition : SemanticVersion.Position.Build;
var commitIdPosition = versionOptions != null ? versionOptions.GitCommitIdPosition : SemanticVersion.Position.Revision;
var versionHeightPosition = versionOptions is not null ? versionOptions.VersionHeightPosition : SemanticVersion.Position.Build;
var commitIdPosition = versionOptions is not null ? versionOptions.GitCommitIdPosition : SemanticVersion.Position.Revision;

// The compiler (due to WinPE header requirements) only allows 16-bit version components,
// and forbids 0xffff as a value.
Expand Down
6 changes: 3 additions & 3 deletions src/NerdBank.GitVersioning/Managed/ManagedGitContext.cs
Expand Up @@ -94,7 +94,7 @@ internal override int CalculateVersionHeight(VersionOptions? committedVersion, V
{
var workingCopyVersion = workingVersion?.Version?.Version;

if (workingCopyVersion == null || !workingCopyVersion.Equals(headCommitVersion))
if (workingCopyVersion is null || !workingCopyVersion.Equals(headCommitVersion))
{
// The working copy has changed the major.minor version.
// So by definition the version height is 0, since no commit represents it yet.
Expand Down Expand Up @@ -153,8 +153,8 @@ private Version GetIdAsVersionHelper(VersionOptions? versionOptions, int version

// Don't use the ?? coalescing operator here because the position property getters themselves can return null, which should NOT be overridden with our default.
// The default value is only appropriate if versionOptions itself is null.
var versionHeightPosition = versionOptions != null ? versionOptions.VersionHeightPosition : SemanticVersion.Position.Build;
var commitIdPosition = versionOptions != null ? versionOptions.GitCommitIdPosition : SemanticVersion.Position.Revision;
var versionHeightPosition = versionOptions is not null ? versionOptions.VersionHeightPosition : SemanticVersion.Position.Build;
var commitIdPosition = versionOptions is not null ? versionOptions.GitCommitIdPosition : SemanticVersion.Position.Revision;

// The compiler (due to WinPE header requirements) only allows 16-bit version components,
// and forbids 0xffff as a value.
Expand Down
12 changes: 6 additions & 6 deletions src/NerdBank.GitVersioning/Managed/ManagedGitExtensions.cs
Expand Up @@ -35,13 +35,13 @@ internal static int GetVersionHeight(ManagedGitContext context, Version? baseVer
var tracker = new GitWalkTracker(context);

var versionOptions = tracker.GetVersion(context.Commit.Value);
if (versionOptions == null)
if (versionOptions is null)
{
return 0;
}

var baseSemVer =
baseVersion != null ? SemanticVersion.Parse(baseVersion.ToString()) :
baseVersion is not null ? SemanticVersion.Parse(baseVersion.ToString()) :
versionOptions.Version ?? SemVer0;

var versionHeightPosition = versionOptions.VersionHeightPosition;
Expand Down Expand Up @@ -69,7 +69,7 @@ private static bool CommitMatchesVersion(GitCommit commit, SemanticVersion expec

var commitVersionData = tracker.GetVersion(commit);
var semVerFromFile = commitVersionData?.Version;
if (commitVersionData == null || semVerFromFile == null)
if (commitVersionData is null || semVerFromFile is null)
{
return false;
}
Expand Down Expand Up @@ -167,7 +167,7 @@ bool TryCalculateHeight(GitCommit commit)

int height = 1;

if (pathFilters != null)
if (pathFilters is not null)
{
var relevantCommit = true;

Expand Down Expand Up @@ -250,7 +250,7 @@ private static bool IsRelevantCommit(GitRepository repository, GitTree tree, Git
isRelevant = IsRelevantCommit(
repository,
repository.GetTree(entry.Sha),
parentEntry == null ? GitTree.Empty : repository.GetTree(parentEntry.Sha),
parentEntry is null ? GitTree.Empty : repository.GetTree(parentEntry.Sha),
$"{fullPath}/",
filters);
}
Expand All @@ -262,7 +262,7 @@ private static bool IsRelevantCommit(GitRepository repository, GitTree tree, Git
}
}

if (parentEntry != null)
if (parentEntry is not null)
{
parent.Children.Remove(child.Key);
}
Expand Down
2 changes: 1 addition & 1 deletion src/NerdBank.GitVersioning/ManagedGit/GitCommitReader.cs
Expand Up @@ -38,7 +38,7 @@ public static class GitCommitReader
/// </returns>
public static GitCommit Read(Stream stream, GitObjectId sha, bool readAuthor = false)
{
if (stream == null)
if (stream is null)
{
throw new ArgumentNullException(nameof(stream));
}
Expand Down
2 changes: 1 addition & 1 deletion src/NerdBank.GitVersioning/ManagedGit/GitObjectId.cs
Expand Up @@ -174,7 +174,7 @@ public override bool Equals(object? obj)
/// </summary>
public override string ToString()
{
if (this.sha == null)
if (this.sha is null)
{
this.sha = this.CreateString(0, 20);
}
Expand Down
4 changes: 2 additions & 2 deletions src/NerdBank.GitVersioning/ManagedGit/GitPack.cs
Expand Up @@ -146,7 +146,7 @@ public bool TryGetObject(GitObjectId objectId, string objectType, out Stream? va
{
var offset = this.GetOffset(objectId);

if (offset == null)
if (offset is null)
{
value = null;
return false;
Expand Down Expand Up @@ -268,7 +268,7 @@ public void Dispose()
var indexReader = this.indexReader.Value;
var offset = indexReader.GetOffset(objectId);

if (offset != null)
if (offset is not null)
{
this.offsets.Add(objectId, offset.Value);
}
Expand Down
Expand Up @@ -169,15 +169,15 @@ protected override void Dispose(bool disposing)

private bool TryGetInstruction(out DeltaInstruction instruction)
{
if (this.current != null && this.offset < this.current.Value.Size)
if (this.current is not null && this.offset < this.current.Value.Size)
{
instruction = this.current.Value;
return true;
}

this.current = DeltaStreamReader.Read(this.deltaStream);

if (this.current == null)
if (this.current is null)
{
instruction = default;
return false;
Expand Down
Expand Up @@ -32,7 +32,7 @@ public unsafe class GitPackIndexMappedReader : GitPackIndexReader
/// </param>
public GitPackIndexMappedReader(FileStream stream)
{
if (stream == null)
if (stream is null)
{
throw new ArgumentNullException(nameof(stream));
}
Expand Down
4 changes: 2 additions & 2 deletions src/NerdBank.GitVersioning/ManagedGit/GitPackReader.cs
Expand Up @@ -13,12 +13,12 @@ internal static class GitPackReader

public static Stream GetObject(GitPack pack, Stream stream, long offset, string objectType, GitPackObjectType packObjectType)
{
if (pack == null)
if (pack is null)
{
throw new ArgumentNullException(nameof(pack));
}

if (stream == null)
if (stream is null)
{
throw new ArgumentNullException(nameof(stream));
}
Expand Down