From 9ead4781720fd277d41a16ea2ade0874e4282723 Mon Sep 17 00:00:00 2001 From: Andrew Arnott Date: Mon, 23 Aug 2021 16:06:41 -0600 Subject: [PATCH] Apply `is null` pattern and analyzer --- .editorconfig | 6 ++++++ src/Directory.Build.props | 6 +++++- .../BuildIntegrationTests.cs | 2 +- .../ManagedGit/DeltaStreamReaderTests.cs | 4 ++-- .../ReleaseManagerTests.cs | 4 ++-- src/NerdBank.GitVersioning.Tests/RepoTestBase.cs | 6 +++--- .../TestUtilities.cs | 2 +- .../VersionFileTests.cs | 2 +- .../AssemblyVersionOptionsConverter.cs | 2 +- .../CloudBuildServices/GitLab.cs | 4 ++-- .../CloudBuildServices/TeamCity.cs | 2 +- .../FilterPathJsonConverter.cs | 4 ++-- .../LibGit2/LibGit2GitExtensions.cs | 16 ++++++++-------- .../Managed/ManagedGitContext.cs | 6 +++--- .../Managed/ManagedGitExtensions.cs | 12 ++++++------ .../ManagedGit/GitCommitReader.cs | 2 +- .../ManagedGit/GitObjectId.cs | 2 +- src/NerdBank.GitVersioning/ManagedGit/GitPack.cs | 4 ++-- .../ManagedGit/GitPackDeltafiedStream.cs | 4 ++-- .../ManagedGit/GitPackIndexMappedReader.cs | 2 +- .../ManagedGit/GitPackReader.cs | 4 ++-- .../ManagedGit/GitRepository.cs | 10 +++++----- src/NerdBank.GitVersioning/ReleaseManager.cs | 8 ++++---- src/NerdBank.GitVersioning/SemanticVersion.cs | 4 ++-- .../SemanticVersionJsonConverter.cs | 2 +- src/NerdBank.GitVersioning/VersionOptions.cs | 8 +++----- src/NerdBank.GitVersioning/VersionOracle.cs | 2 +- .../ContextAwareTask.cs | 6 +++--- .../GetBuildVersion.cs | 8 ++++---- .../NativeVersionInfo.cs | 4 ++-- .../SetCloudBuildVariables.cs | 6 +++--- src/nbgv/Program.cs | 14 +++++++------- 32 files changed, 88 insertions(+), 80 deletions(-) diff --git a/.editorconfig b/.editorconfig index 98824c08..fb31b8c2 100644 --- a/.editorconfig +++ b/.editorconfig @@ -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 diff --git a/src/Directory.Build.props b/src/Directory.Build.props index 7f82c288..94a570b3 100644 --- a/src/Directory.Build.props +++ b/src/Directory.Build.props @@ -24,9 +24,13 @@ 2.0.312 - + + + all + runtime; build; native; contentfiles; analyzers + diff --git a/src/NerdBank.GitVersioning.Tests/BuildIntegrationTests.cs b/src/NerdBank.GitVersioning.Tests/BuildIntegrationTests.cs index b2ab89f5..d931f2e2 100644 --- a/src/NerdBank.GitVersioning.Tests/BuildIntegrationTests.cs +++ b/src/NerdBank.GitVersioning.Tests/BuildIntegrationTests.cs @@ -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); diff --git a/src/NerdBank.GitVersioning.Tests/ManagedGit/DeltaStreamReaderTests.cs b/src/NerdBank.GitVersioning.Tests/ManagedGit/DeltaStreamReaderTests.cs index 2e475ca9..279e0a16 100644 --- a/src/NerdBank.GitVersioning.Tests/ManagedGit/DeltaStreamReaderTests.cs +++ b/src/NerdBank.GitVersioning.Tests/ManagedGit/DeltaStreamReaderTests.cs @@ -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); } @@ -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); } diff --git a/src/NerdBank.GitVersioning.Tests/ReleaseManagerTests.cs b/src/NerdBank.GitVersioning.Tests/ReleaseManagerTests.cs index c69f5120..c95500bf 100644 --- a/src/NerdBank.GitVersioning.Tests/ReleaseManagerTests.cs +++ b/src/NerdBank.GitVersioning.Tests/ReleaseManagerTests.cs @@ -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); @@ -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); } diff --git a/src/NerdBank.GitVersioning.Tests/RepoTestBase.cs b/src/NerdBank.GitVersioning.Tests/RepoTestBase.cs index 4bcd8bbb..5cc81647 100644 --- a/src/NerdBank.GitVersioning.Tests/RepoTestBase.cs +++ b/src/NerdBank.GitVersioning.Tests/RepoTestBase.cs @@ -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; } @@ -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; } @@ -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); } diff --git a/src/NerdBank.GitVersioning.Tests/TestUtilities.cs b/src/NerdBank.GitVersioning.Tests/TestUtilities.cs index a67edbd1..6d61fbf1 100644 --- a/src/NerdBank.GitVersioning.Tests/TestUtilities.cs +++ b/src/NerdBank.GitVersioning.Tests/TestUtilities.cs @@ -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); diff --git a/src/NerdBank.GitVersioning.Tests/VersionFileTests.cs b/src/NerdBank.GitVersioning.Tests/VersionFileTests.cs index a4ad2af3..f6330e61 100644 --- a/src/NerdBank.GitVersioning.Tests/VersionFileTests.cs +++ b/src/NerdBank.GitVersioning.Tests/VersionFileTests.cs @@ -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, }; diff --git a/src/NerdBank.GitVersioning/AssemblyVersionOptionsConverter.cs b/src/NerdBank.GitVersioning/AssemblyVersionOptionsConverter.cs index 0f88e0f5..0e88f638 100644 --- a/src/NerdBank.GitVersioning/AssemblyVersionOptionsConverter.cs +++ b/src/NerdBank.GitVersioning/AssemblyVersionOptionsConverter.cs @@ -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) { diff --git a/src/NerdBank.GitVersioning/CloudBuildServices/GitLab.cs b/src/NerdBank.GitVersioning/CloudBuildServices/GitLab.cs index aa0c649a..21abebd2 100644 --- a/src/NerdBank.GitVersioning/CloudBuildServices/GitLab.cs +++ b/src/NerdBank.GitVersioning/CloudBuildServices/GitLab.cs @@ -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"); diff --git a/src/NerdBank.GitVersioning/CloudBuildServices/TeamCity.cs b/src/NerdBank.GitVersioning/CloudBuildServices/TeamCity.cs index e4df2b69..ec0cd84b 100644 --- a/src/NerdBank.GitVersioning/CloudBuildServices/TeamCity.cs +++ b/src/NerdBank.GitVersioning/CloudBuildServices/TeamCity.cs @@ -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; diff --git a/src/NerdBank.GitVersioning/FilterPathJsonConverter.cs b/src/NerdBank.GitVersioning/FilterPathJsonConverter.cs index acd57e03..304c41f0 100644 --- a/src/NerdBank.GitVersioning/FilterPathJsonConverter.cs +++ b/src/NerdBank.GitVersioning/FilterPathJsonConverter.cs @@ -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."); } @@ -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."); } diff --git a/src/NerdBank.GitVersioning/LibGit2/LibGit2GitExtensions.cs b/src/NerdBank.GitVersioning/LibGit2/LibGit2GitExtensions.cs index 3d17c5f6..045c647a 100644 --- a/src/NerdBank.GitVersioning/LibGit2/LibGit2GitExtensions.cs +++ b/src/NerdBank.GitVersioning/LibGit2/LibGit2GitExtensions.cs @@ -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; @@ -174,7 +174,7 @@ public static IEnumerable 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; @@ -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; } @@ -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; } @@ -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 @@ -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. diff --git a/src/NerdBank.GitVersioning/Managed/ManagedGitContext.cs b/src/NerdBank.GitVersioning/Managed/ManagedGitContext.cs index d42f1aec..a6d4fab5 100644 --- a/src/NerdBank.GitVersioning/Managed/ManagedGitContext.cs +++ b/src/NerdBank.GitVersioning/Managed/ManagedGitContext.cs @@ -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. @@ -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. diff --git a/src/NerdBank.GitVersioning/Managed/ManagedGitExtensions.cs b/src/NerdBank.GitVersioning/Managed/ManagedGitExtensions.cs index 58b8206e..2f05103e 100644 --- a/src/NerdBank.GitVersioning/Managed/ManagedGitExtensions.cs +++ b/src/NerdBank.GitVersioning/Managed/ManagedGitExtensions.cs @@ -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; @@ -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; } @@ -167,7 +167,7 @@ bool TryCalculateHeight(GitCommit commit) int height = 1; - if (pathFilters != null) + if (pathFilters is not null) { var relevantCommit = true; @@ -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); } @@ -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); } diff --git a/src/NerdBank.GitVersioning/ManagedGit/GitCommitReader.cs b/src/NerdBank.GitVersioning/ManagedGit/GitCommitReader.cs index 25b22e49..8af84e05 100644 --- a/src/NerdBank.GitVersioning/ManagedGit/GitCommitReader.cs +++ b/src/NerdBank.GitVersioning/ManagedGit/GitCommitReader.cs @@ -38,7 +38,7 @@ public static class GitCommitReader /// public static GitCommit Read(Stream stream, GitObjectId sha, bool readAuthor = false) { - if (stream == null) + if (stream is null) { throw new ArgumentNullException(nameof(stream)); } diff --git a/src/NerdBank.GitVersioning/ManagedGit/GitObjectId.cs b/src/NerdBank.GitVersioning/ManagedGit/GitObjectId.cs index b18d04a9..76b5d672 100644 --- a/src/NerdBank.GitVersioning/ManagedGit/GitObjectId.cs +++ b/src/NerdBank.GitVersioning/ManagedGit/GitObjectId.cs @@ -174,7 +174,7 @@ public override bool Equals(object? obj) /// public override string ToString() { - if (this.sha == null) + if (this.sha is null) { this.sha = this.CreateString(0, 20); } diff --git a/src/NerdBank.GitVersioning/ManagedGit/GitPack.cs b/src/NerdBank.GitVersioning/ManagedGit/GitPack.cs index 5d19128d..576dd50d 100644 --- a/src/NerdBank.GitVersioning/ManagedGit/GitPack.cs +++ b/src/NerdBank.GitVersioning/ManagedGit/GitPack.cs @@ -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; @@ -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); } diff --git a/src/NerdBank.GitVersioning/ManagedGit/GitPackDeltafiedStream.cs b/src/NerdBank.GitVersioning/ManagedGit/GitPackDeltafiedStream.cs index f2ab7d0e..3cff6c53 100644 --- a/src/NerdBank.GitVersioning/ManagedGit/GitPackDeltafiedStream.cs +++ b/src/NerdBank.GitVersioning/ManagedGit/GitPackDeltafiedStream.cs @@ -169,7 +169,7 @@ 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; @@ -177,7 +177,7 @@ private bool TryGetInstruction(out DeltaInstruction instruction) this.current = DeltaStreamReader.Read(this.deltaStream); - if (this.current == null) + if (this.current is null) { instruction = default; return false; diff --git a/src/NerdBank.GitVersioning/ManagedGit/GitPackIndexMappedReader.cs b/src/NerdBank.GitVersioning/ManagedGit/GitPackIndexMappedReader.cs index 279f0403..b3690166 100644 --- a/src/NerdBank.GitVersioning/ManagedGit/GitPackIndexMappedReader.cs +++ b/src/NerdBank.GitVersioning/ManagedGit/GitPackIndexMappedReader.cs @@ -32,7 +32,7 @@ public unsafe class GitPackIndexMappedReader : GitPackIndexReader /// public GitPackIndexMappedReader(FileStream stream) { - if (stream == null) + if (stream is null) { throw new ArgumentNullException(nameof(stream)); } diff --git a/src/NerdBank.GitVersioning/ManagedGit/GitPackReader.cs b/src/NerdBank.GitVersioning/ManagedGit/GitPackReader.cs index a1eba9ae..354060d4 100644 --- a/src/NerdBank.GitVersioning/ManagedGit/GitPackReader.cs +++ b/src/NerdBank.GitVersioning/ManagedGit/GitPackReader.cs @@ -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)); } diff --git a/src/NerdBank.GitVersioning/ManagedGit/GitRepository.cs b/src/NerdBank.GitVersioning/ManagedGit/GitRepository.cs index 459f23c6..05e8fd53 100644 --- a/src/NerdBank.GitVersioning/ManagedGit/GitRepository.cs +++ b/src/NerdBank.GitVersioning/ManagedGit/GitRepository.cs @@ -192,7 +192,7 @@ public string ShortenObjectId(GitObjectId objectId, int minimum) { var objectish = sha.Substring(0, length); - if (this.Lookup(objectish) != null) + if (this.Lookup(objectish) is not null) { return objectish; } @@ -263,7 +263,7 @@ public GitCommit GetCommit(GitObjectId sha, bool readAuthor = false) { using (Stream? stream = this.GetObjectBySha(sha, "commit")) { - if (stream == null) + if (stream is null) { throw new GitException($"The commit {sha} was not found in this repository.") { ErrorCode = GitException.ErrorCodes.ObjectNotFound }; } @@ -396,7 +396,7 @@ public GitCommit GetCommit(GitObjectId sha, bool readAuthor = false) // It's possible for the same object to be present in both the object database and the pack files, // or in multiple pack files. - if (objectId != null && !possibleObjectIds.Contains(objectId.Value)) + if (objectId is not null && !possibleObjectIds.Contains(objectId.Value)) { if (possibleObjectIds.Count > 0) { @@ -435,7 +435,7 @@ public GitTree GetTree(GitObjectId sha) { using (Stream? stream = this.GetObjectBySha(sha, "tree")) { - if (stream == null) + if (stream is null) { throw new GitException($"The tree {sha} was not found in this repository.") { ErrorCode = GitException.ErrorCodes.ObjectNotFound }; } @@ -461,7 +461,7 @@ public GitObjectId GetTreeEntry(GitObjectId treeId, ReadOnlySpan nodeName) { using (Stream? treeStream = this.GetObjectBySha(treeId, "tree")) { - if (treeStream == null) + if (treeStream is null) { throw new GitException($"The tree {treeId} was not found in this repository.") { ErrorCode = GitException.ErrorCodes.ObjectNotFound }; } diff --git a/src/NerdBank.GitVersioning/ReleaseManager.cs b/src/NerdBank.GitVersioning/ReleaseManager.cs index e30efa6a..a59e4739 100644 --- a/src/NerdBank.GitVersioning/ReleaseManager.cs +++ b/src/NerdBank.GitVersioning/ReleaseManager.cs @@ -243,7 +243,7 @@ public void PrepareRelease(string projectDirectory, string releaseUnstableTag = // get the current version var versionOptions = context.VersionFile.GetVersion(); - if (versionOptions == null) + if (versionOptions is null) { this.stderr.WriteLine($"Failed to load version file for directory '{projectDirectory}'."); throw new ReleasePreparationException(ReleasePreparationError.NoVersionFile); @@ -274,7 +274,7 @@ public void PrepareRelease(string projectDirectory, string releaseUnstableTag = var nextDevVersion = this.GetNextDevVersion(versionOptions, nextVersion, versionIncrement); // check if the release branch already exists - if (repository.Branches[releaseBranchName] != null) + if (repository.Branches[releaseBranchName] is not null) { this.stderr.WriteLine($"Cannot create branch '{releaseBranchName}' because it already exists."); throw new ReleasePreparationException(ReleasePreparationError.BranchAlreadyExists); @@ -371,7 +371,7 @@ private void UpdateVersion(LibGit2Context context, SemanticVersion oldVersion, S private Signature GetSignature(Repository repository) { var signature = repository.Config.BuildSignature(DateTimeOffset.Now); - if (signature == null) + if (signature is null) { this.stderr.WriteLine("Cannot create commits in this repo because git user name and email are not configured."); throw new ReleasePreparationException(ReleasePreparationError.UserNotConfigured); @@ -430,7 +430,7 @@ private SemanticVersion GetNextDevVersion(VersionOptions versionOptions, Version var currentVersion = versionOptions.Version; SemanticVersion nextDevVersion; - if (nextVersionOverride != null) + if (nextVersionOverride is not null) { nextDevVersion = new SemanticVersion(nextVersionOverride, currentVersion.Prerelease, currentVersion.BuildMetadata); } diff --git a/src/NerdBank.GitVersioning/SemanticVersion.cs b/src/NerdBank.GitVersioning/SemanticVersion.cs index 9b503b46..ad07b529 100644 --- a/src/NerdBank.GitVersioning/SemanticVersion.cs +++ b/src/NerdBank.GitVersioning/SemanticVersion.cs @@ -155,7 +155,7 @@ internal enum Position /// /// Gets a value indicating whether this instance is the default "0.0" instance. /// - internal bool IsDefault => this.Version?.Major == 0 && this.Version.Minor == 0 && this.Version.Build == -1 && this.Version.Revision == -1 && this.Prerelease == null && this.BuildMetadata == null; + internal bool IsDefault => this.Version?.Major == 0 && this.Version.Minor == 0 && this.Version.Build == -1 && this.Version.Revision == -1 && this.Prerelease is null && this.BuildMetadata is null; /// /// Gets the debugger display for this instance. @@ -239,7 +239,7 @@ public override string ToString() /// true if the instances have equal values; false otherwise. public bool Equals(SemanticVersion other) { - if (other == null) + if (other is null) { return false; } diff --git a/src/NerdBank.GitVersioning/SemanticVersionJsonConverter.cs b/src/NerdBank.GitVersioning/SemanticVersionJsonConverter.cs index a064cb19..a4ae7f34 100644 --- a/src/NerdBank.GitVersioning/SemanticVersionJsonConverter.cs +++ b/src/NerdBank.GitVersioning/SemanticVersionJsonConverter.cs @@ -32,7 +32,7 @@ public override object ReadJson(JsonReader reader, Type objectType, object exist public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { var version = value as SemanticVersion; - if (version != null) + if (version is not null) { writer.WriteValue(version.ToString()); return; diff --git a/src/NerdBank.GitVersioning/VersionOptions.cs b/src/NerdBank.GitVersioning/VersionOptions.cs index 7aee1dfa..cac77f86 100644 --- a/src/NerdBank.GitVersioning/VersionOptions.cs +++ b/src/NerdBank.GitVersioning/VersionOptions.cs @@ -570,9 +570,7 @@ internal bool IsDefaultVersionTheOnlyPropertySet { get { - return this.Version != null - && this.AssemblyVersion == null - && (this.CloudBuild?.IsDefault ?? true) + return this.Version is not null && this.AssemblyVersion is null && (this.CloudBuild?.IsDefault ?? true) && this.VersionHeightOffset == 0 && !this.SemVer1NumericIdentifierPadding.HasValue && !this.Inherit; @@ -693,7 +691,7 @@ public bool Equals(NuGetPackageVersionOptions? x, NuGetPackageVersionOptions? y) return true; } - if (x == null || y == null) + if (x is null || y is null) { return false; } @@ -1575,7 +1573,7 @@ public bool Equals(ReleaseOptions? x, ReleaseOptions? y) /// public int GetHashCode(ReleaseOptions? obj) { - if (obj == null) + if (obj is null) return 0; unchecked diff --git a/src/NerdBank.GitVersioning/VersionOracle.cs b/src/NerdBank.GitVersioning/VersionOracle.cs index 84c83019..93a11394 100644 --- a/src/NerdBank.GitVersioning/VersionOracle.cs +++ b/src/NerdBank.GitVersioning/VersionOracle.cs @@ -294,7 +294,7 @@ public IEnumerable BuildMetadataWithCommitId var properties = this.GetType().GetTypeInfo().GetProperties(BindingFlags.Public | BindingFlags.DeclaredOnly | BindingFlags.Instance); foreach (var property in properties) { - if (property.GetCustomAttribute() == null) + if (property.GetCustomAttribute() is null) { var value = property.GetValue(this); if (value is object) diff --git a/src/Nerdbank.GitVersioning.Tasks/ContextAwareTask.cs b/src/Nerdbank.GitVersioning.Tasks/ContextAwareTask.cs index b4c1e51b..f3bb3e17 100644 --- a/src/Nerdbank.GitVersioning.Tasks/ContextAwareTask.cs +++ b/src/Nerdbank.GitVersioning.Tasks/ContextAwareTask.cs @@ -31,11 +31,11 @@ public override bool Execute() var outerProperties = this.GetType().GetRuntimeProperties().ToDictionary(i => i.Name); var innerProperties = innerTaskType.GetRuntimeProperties().ToDictionary(i => i.Name); var propertiesDiscovery = from outerProperty in outerProperties.Values - where outerProperty.SetMethod != null && outerProperty.GetMethod != null + where outerProperty.SetMethod is not null && outerProperty.GetMethod is not null let innerProperty = innerProperties[outerProperty.Name] select new { outerProperty, innerProperty }; var propertiesMap = propertiesDiscovery.ToArray(); - var outputPropertiesMap = propertiesMap.Where(pair => pair.outerProperty.GetCustomAttribute() != null).ToArray(); + var outputPropertiesMap = propertiesMap.Where(pair => pair.outerProperty.GetCustomAttribute() is not null).ToArray(); foreach (var propertyPair in propertiesMap) { @@ -54,7 +54,7 @@ public override bool Execute() return result; #else // On .NET Framework (on Windows), we find native binaries by adding them to our PATH. - if (this.UnmanagedDllDirectory != null) + if (this.UnmanagedDllDirectory is not null) { string pathEnvVar = Environment.GetEnvironmentVariable("PATH"); string[] searchPaths = pathEnvVar.Split(Path.PathSeparator); diff --git a/src/Nerdbank.GitVersioning.Tasks/GetBuildVersion.cs b/src/Nerdbank.GitVersioning.Tasks/GetBuildVersion.cs index 2a9c00d4..77b79342 100644 --- a/src/Nerdbank.GitVersioning.Tasks/GetBuildVersion.cs +++ b/src/Nerdbank.GitVersioning.Tasks/GetBuildVersion.cs @@ -237,7 +237,7 @@ protected override bool ExecuteInner() oracle.PublicRelease = string.Equals(this.DefaultPublicRelease, "true", StringComparison.OrdinalIgnoreCase); } - if (this.BuildMetadata != null) + if (this.BuildMetadata is not null) { oracle.BuildMetadata.AddRange(this.BuildMetadata.Split(';')); } @@ -259,7 +259,7 @@ protected override bool ExecuteInner() this.PrereleaseVersion = oracle.PrereleaseVersion; this.GitCommitId = oracle.GitCommitId; this.GitCommitIdShort = oracle.GitCommitIdShort; - this.GitCommitDateTicks = oracle.GitCommitDate != null ? oracle.GitCommitDate.Value.UtcTicks.ToString(CultureInfo.InvariantCulture) : null; + this.GitCommitDateTicks = oracle.GitCommitDate is not null ? oracle.GitCommitDate.Value.UtcTicks.ToString(CultureInfo.InvariantCulture) : null; this.GitVersionHeight = oracle.VersionHeight; this.BuildMetadataFragment = oracle.BuildMetadataFragment; this.CloudBuildNumber = oracle.CloudBuildNumberEnabled ? oracle.CloudBuildNumber : null; @@ -279,7 +279,7 @@ protected override bool ExecuteInner() var allVariables = oracle.CloudBuildAllVars .Select(item => new TaskItem(item.Key, new Dictionary { { "Value", item.Value } })); - if (cloudBuildVersionVars != null) + if (cloudBuildVersionVars is not null) { cloudBuildVersionVars = cloudBuildVersionVars .Union(allVariables); @@ -290,7 +290,7 @@ protected override bool ExecuteInner() } } - if (cloudBuildVersionVars != null) + if (cloudBuildVersionVars is not null) { this.CloudBuildVersionVars = cloudBuildVersionVars.ToArray(); } diff --git a/src/Nerdbank.GitVersioning.Tasks/NativeVersionInfo.cs b/src/Nerdbank.GitVersioning.Tasks/NativeVersionInfo.cs index 8709c89e..8153a545 100644 --- a/src/Nerdbank.GitVersioning.Tasks/NativeVersionInfo.cs +++ b/src/Nerdbank.GitVersioning.Tasks/NativeVersionInfo.cs @@ -106,7 +106,7 @@ BLOCK NBGV_VERSION_BLOCK public override bool Execute() { this.generator = this.CreateGenerator(); - if (this.generator != null) + if (this.generator is not null) { this.generator.StartFile(); @@ -300,7 +300,7 @@ protected void AddCodeComment(string comment, string token) { var sr = new StringReader(comment); string line; - while ((line = sr.ReadLine()) != null) + while ((line = sr.ReadLine()) is not null) { this.codeBuilder.Append(token); this.codeBuilder.AppendLine(line); diff --git a/src/Nerdbank.GitVersioning.Tasks/SetCloudBuildVariables.cs b/src/Nerdbank.GitVersioning.Tasks/SetCloudBuildVariables.cs index 9939043d..b721152c 100644 --- a/src/Nerdbank.GitVersioning.Tasks/SetCloudBuildVariables.cs +++ b/src/Nerdbank.GitVersioning.Tasks/SetCloudBuildVariables.cs @@ -20,7 +20,7 @@ public class SetCloudBuildVariables : Task public override bool Execute() { var cloudBuild = CloudBuild.Active; - if (cloudBuild != null) + if (cloudBuild is not null) { var envVars = new Dictionary(StringComparer.OrdinalIgnoreCase); @@ -42,7 +42,7 @@ public override bool Execute() } } - if (this.CloudBuildVersionVars != null) + if (this.CloudBuildVersionVars is not null) { foreach (var variable in this.CloudBuildVersionVars) { @@ -82,7 +82,7 @@ private void PipeOutputToMSBuildLog(string output, bool warning) using (var logReader = new StringReader(output)) { string line; - while ((line = logReader.ReadLine()) != null) + while ((line = logReader.ReadLine()) is not null) { // The prefix is presumed to nullify the effect in a real cloud build, // yet make it detectable by a unit test. diff --git a/src/nbgv/Program.cs b/src/nbgv/Program.cs index 7df6b7bf..e9ae5d75 100644 --- a/src/nbgv/Program.cs +++ b/src/nbgv/Program.cs @@ -282,7 +282,7 @@ private static int OnInstallCommand(string path, string version, IReadOnlyList met } var oracle = new VersionOracle(context, CloudBuild.Active); - if (metadata != null) + if (metadata is not null) { oracle.BuildMetadata.AddRange(metadata); } @@ -418,7 +418,7 @@ private static int OnGetVersionCommand(string project, IReadOnlyList met } var property = oracle.GetType().GetProperty(variable, CaseInsensitiveFlags); - if (property == null) + if (property is null) { Console.Error.WriteLine("Variable \"{0}\" not a version property.", variable); return (int)ExitCodes.BadVariable; @@ -447,7 +447,7 @@ private static int OnSetVersionCommand(string project, string version) using var context = GitContext.Create(searchPath, writable: true); var existingOptions = context.VersionFile.GetVersion(out string actualDirectory); string versionJsonPath; - if (existingOptions != null) + if (existingOptions is not null) { existingOptions.Version = semver; versionJsonPath = context.VersionFile.SetVersion(actualDirectory, existingOptions); @@ -598,7 +598,7 @@ private static int OnCloudCommand(string project, IReadOnlyList metadata using var context = GitContext.Create(searchPath, writable: AlwaysUseLibGit2); var oracle = new VersionOracle(context, cloudBuild: activeCloudBuild); - if (metadata != null) + if (metadata is not null) { oracle.BuildMetadata.AddRange(metadata); } @@ -620,7 +620,7 @@ private static int OnCloudCommand(string project, IReadOnlyList metadata } } - if (define != null) + if (define is not null) { foreach (string def in define) { @@ -641,7 +641,7 @@ private static int OnCloudCommand(string project, IReadOnlyList metadata } } - if (activeCloudBuild != null) + if (activeCloudBuild is not null) { if (string.IsNullOrEmpty(version)) {